Blockchain notes
Week 2
Step-by-Step: RSA Key Generation
1. Pick Two Big Prime Numbers:
Choose two random prime numbers, call them:
• p
• q
These need to be big and secret.
2. Multiply Them to Get n:
Compute:
n=p×q
This n becomes part of both your public and private key.
3. Compute Euler’s Totient Function:
φ(n) = (p - 1) × (q - 1)
This is used to help find the keys.
Step 4: Choose a Public Key Exponent e
Now you already have:
• n=p×q
• φ(n) = (p − 1) × (q − 1)
Next, you need to choose a number called e, which will be part of your public
key.
What should e be?
• It must be greater than 1 and smaller than φ(n)
• Most importantly, it should not share any factors with φ(n) — this
means:
gcd(e, φ(n)) = 1
That just means: e and φ(n) are co-prime (they don’t have any common
divisors except 1)
Example:
Say φ(n) = 40
Pick e = 3 → check: gcd(3, 40) = 1 → good choice
Or e = 9 → gcd(9, 40) = 1 → also fine
But e = 10 → gcd(10, 40) = 10 → not co-prime → invalid
Step 5: Find the Private Key d
Now that you have e, you need to find the matching private key value d.
You want d to be the inverse of e in modular math:
d × e ≡ 1 mod φ(n) optional
This is called the modular inverse of e modulo φ(n).
Example:
Let’s say:
• e=3
• φ(n) = 40
We want:
d × 3 mod 40 = 1
Try d = 27:
27 × 3 = 81 → 81 mod 40 = 1
So d = 27 is the correct private key!
Final Keys:
• Public Key = (e, n) → shared with the world
• Private Key = (d, n) → kept secret
Great question — and very important to understand!
What is the point of RSA? Why go through all this?
The main purpose of RSA is to allow secure communication between people (or
computers) — even if they’ve never met before — without sharing a secret password in
advance.
Here's the Big Idea:
Imagine you want someone to send you a secret message, but you're not there to meet them
in person and give them a password.
With RSA, you can:
1. Share your public key with the whole world (it’s safe!).
2. Anyone can use that public key to encrypt a message to you.
3. Only you can decrypt the message — using your private key (which no one else
has).
Real-Life Example:
Say Alice wants to send Bob a secret:
1. Bob makes his RSA keys:
o Public Key: (e, n)
o Private Key: (d, n)
2. Bob shares the public key with Alice.
3. Alice uses the public key to encrypt her message:
4. cipher = message^e mod n
5. Bob uses his private key to decrypt:
6. message = cipher^d mod n
Even if a hacker sees the public key and the encrypted message, they can’t decrypt it —
because finding d (the private key) is very hard unless they can factor n (which is almost
impossible when n is large enough).
Summary: RSA Helps With
Encryption – Send messages securely over insecure networks
Authentication – Prove a message came from a specific person (digital signatures)
Key exchange – Help two parties agree on secret keys safely
Would you like to see how RSA is used in real-world things like WhatsApp, online banking,
or digital signatures?
Encryption and decryption
Absolutely! Let's walk through this RSA encryption and decryption example in very simple,
clear steps — like solving a puzzle.
Step 1: Key Generation (making public and private keys)
1. Choose two prime numbers:
• p = 17, q = 11
2. Multiply them to get n:
• n = p × q = 17 × 11 = 187
This n is part of both your public and private keys.
3. Compute Euler’s totient function (φ):
• φ(n) = (p - 1) × (q - 1) = 16 × 10 = 160
4. Choose public exponent e:
• Let e = 7
(It must be co-prime to 160 — and 7 is)
5. Compute the private exponent d:
• We need d such that:
• d × e ≡ 1 (mod 160)
Try d = 23, because:
23 × 7 = 161 ≡ 1 mod 160
So now you have:
• Public key = (e, n) = (7, 187)
• Private key = (d, n) = (23, 187)
Step 2: Encryption
Say the original message (as a number) is:
• M = 88
We want to encrypt it using the public key:
C = M^e mod n
= 88^7 mod 187
Instead of calculating 88^7 directly (huge!), we break it down using properties of
exponents:
Trick:
88^7 = 88 × 88^2 × 88^4
We compute these one by one, using mod 187 each time:
• 88 mod 187 = 88
• 88^2 = 7744 → 7744 mod 187 = 77
• 88^4 = 77^2 = 5929 → 5929 mod 187 = 132
Now:
88^7 mod 187 = 88 × 77 × 132 mod 187
= (88 × 77 = 6776 → 6776 × 132 = 894432)
→ 894432 mod 187 = 11
So:
• Encrypted message (ciphertext) = C = 11
Step 3: Decryption
Now we decrypt C = 11 using the private key (d = 23):
M = C^d mod n
= 11^23 mod 187
Again, instead of directly calculating 11^23, we break it down:
We write 23 in binary:
23 = 10111 → means 1×16 + 0×8 + 1×4 + 1×2 + 1×1
So:
11^23 = 11^16 × 11^4 × 11^2 × 11^1
Now compute each:
• 11^1 mod 187 = 11
• 11^2 = 121 → mod 187 = 121
• 11^4 = 121^2 = 14641 → mod 187 = 55
• 11^8 = (11^4)^2 = 55^2 = 3025 → mod 187 = 33
• 11^16 = (11^8)^2 = 33^2 = 1089 → mod 187 = 33
Now multiply:
11^23 mod 187 = 11 × 121 × 55 × 33 × 33
= (multiply them) = 79720245
→ mod 187 = 88
You get back the original message: M = 88
Final Summary
• You encrypted the number 88 and got 11
• You decrypted 11 and got back 88
This is the magic of RSA — encrypt with one key, decrypt with the other.
Digital Signatures
Verification of a Digital Signature — Step-by-Step
Scenario: Alice wants to send a message to Bob, and Bob must verify it's really from
her and untampered.
Case 1: Signing the Entire Message
Alice:
1. Has a private key KpriA.
2. She writes a message: M = "Send 5 coins to Bob".
3. She encrypts the message with her private key:
M′ = E(M, KpriA)
This encrypted version M′ is the digital signature.
4. She sends both:
o The original message M
o The signature M′
Bob (the receiver):
1. Receives:
o Message: M
o Signature: M′
2. He uses Alice's public key KpubA to decrypt the signature:
ini
CopyEdit
M1 = E(M′, KpubA)
3. He compares:
o The decrypted message M1
o With the original message M that Alice sent.
If they match → The signature is valid, and the message was not tampered.
If not → Either the message or the signature has been altered, or it wasn’t Alice.
Case 2: Signing a Hash of the Message (More Common in Practice)
This method is faster and more efficient, especially with large messages.
Alice:
1. Writes the message M = "Send 5 coins to Bob".
2. Computes the hash of the message: H(M)
o This hash is a short, fixed-length representation (e.g., 256 bits).
3. She encrypts the hash with her private key:
S = E(H(M), KpriA)
This is the digital signature S.
4. She sends:
o The original message M
o The signature S
Bob:
1. Receives:
o Message M
o Signature S
2. Computes the hash of the message on his side: H1 = H(M)
3. Decrypts the signature using Alice's public key:
H2 = E(S, KpubA)
4. Compares:
o H1 (computed hash)
o H2 (decrypted hash)
If H1 == H2 → the message is authentic and unchanged.
Consensus, its Limitations, and how Proof
of Work (PoW) solved it
What is Consensus?
Consensus means all computers (nodes) in a network agree on the same decision (like
which transaction or block to accept).
• In small/private networks: Nodes know each other, and can message to agree.
• In open networks (like Bitcoin): Anyone can join, even attackers, so agreement
becomes harder.
What are the Limitations of Traditional Consensus?
1. Need for Trusted Identities
o Traditional consensus assumes you know and trust the participants.
o In an open network, you don't know who is honest or fake.
2. Message Passing Problems
o Needs direct communication between nodes.
o Messages can be delayed, lost, or faked.
3. Byzantine Problems
o Some nodes can act maliciously, lie, or confuse others.
oHard to agree when you can’t trust everyone.
4. Closed Networks Assumption
o Classical algorithms like Paxos or PBFT work best in small, closed systems,
not huge, open ones like blockchain.
How Proof of Work (PoW) Solved It
Bitcoin introduced Proof of Work (PoW) — a new way to reach consensus without
trusting anyone.
Here's how it works:
1. Instead of messaging, everyone solves a hard puzzle (like finding a special number).
2. Whoever solves it first becomes the leader and proposes the next block.
3. Others easily verify the solution — no need to trust the leader.
4. Majority follows the longest valid chain (most "work" done).
Key Ideas in PoW:
• Hard to solve, easy to check puzzles.
• No need for trusted identities.
• No direct message passing.
• Majority of computing power controls the network (not majority of people).
Summary in One Line
Traditional consensus fails in open, untrusted networks — PoW replaced trust and messaging
with puzzle solving and majority computing power.
Week 3
Smart Contracts
Here’s a summary of the smart contracts content:
Summary: Smart Contracts
1. DLTs for Code Execution
• Distributed Ledger Technologies (like blockchain) can execute code automatically,
not just record transactions.
• Main Idea: Blockchain can execute programs as transactions.
2. What is a Smart Contract?
• Smart Contract = Code that executes automatically on a decentralized network.
• Once deployed, it self-executes, is immutable, and operates based on consensus.
3. Traditional Digital Contracts
• Traditional systems involve manual checks and reliance on a central server.
• Issues: Trust in the central server, risk of data manipulation.
4. Decentralized Code Execution with Blockchain
• Instead of trusting a server, you submit code to blockchain where it is executed by the
network.
• Example: Payment and delivery function where execution is guaranteed, and every
step is recorded.
5. Smart Contract Execution Process
• The contract is encrypted, submitted to the blockchain, and executed by the network.
• Consensus ensures proper execution and prevents tampering or cheating.
6. Why Smart Contracts Matter
• They eliminate the need for middlemen, enabling trustworthy, automatic, and
transparent transactions.
7. Two Parts of Smart Contract Interaction
• Deployment (storing the code on blockchain) happens once.
• Execution/Interaction (calling the contract’s functions) happens many times.
8. Analogy
• Deploying a contract = Publishing a book in a library.
• Calling the contract = Reading the book and interacting with it.
Conclusion
• Smart contracts are self-executing and immutable agreements stored and executed on
blockchain, with results validated by consensus.
What is Blockchain?
• Blockchain is a platform that allows people or organizations to perform
transactional services.
• Key point: It connects people who may not trust each other — blockchain
technology ensures security without needing trust.
• It's a shared, append-only ledger:
o "Append-only" means you can only add data; you can't change or delete old
data.
o Every transaction is digitally signed and encrypted.
o This ledger is replicated across multiple nodes (computers in the network).
The Block in a Blockchain – Securing Data Cryptographically
• Transactions inside the block are:
o Digitally signed (to prove authenticity).
o Encrypted (to keep data secure).
• Verification: Peers in the network verify transactions.
• Cryptographic security:
o Participants can only view data they're authorized to.
o Protects data privacy and security.
Structure of a Block
• A block is a container that holds a series of transactions.
• In Bitcoin:
o A block typically holds 500+ transactions.
o Average block size is about 1 MB (Satoshi Nakamoto proposed a limit in
2010).
o Block size can grow up to 8 MB or more, but larger blocks:
▪ Allow more transactions.
▪ Take longer to verify and propagate across the network.
Block Components (Reference: Bitcoin)
Each block has two main parts:
1. Block Header
2. List of Transactions
Block Header Details
• Block header holds metadata about the block:
1. Previous Block Hash (connects blocks together — makes tampering nearly
impossible).
2. Mining Statistics (timestamp, nonce, difficulty).
3. Merkle Tree Root (summarizes all transactions in the block).
• Previous Block Hash links each block to its predecessor:
o Example:
▪ H0
▪ H1 = Hash(H0)
▪ H2 = Hash(H1)
▪ and so on…
o This forms the actual blockchain.
Block Generation Puzzle ("Proof of Work")
• Miners need to solve a puzzle:
o They must find a nonce (random number) so that the hash of the block has a
certain number of leading zeros.
• Example:
o Required hash: 0000000000000000004a2b84f93a285b7a7...
• This process is called mining.
Mining and Difficulty
• Mining:
o Hashing the block header with a random nonce.
o If the hash meets the difficulty target, the block is valid.
• Difficulty and Bits:
o "Bits" are a compact way to express difficulty.
o Target is calculated from bits.
o Difficulty is a ratio:
▪ Difficulty = (maximum possible target) ÷ (current target).
• Mining is computationally expensive:
o Requires high computing power.
o Consumes a lot of energy.
Hashes in a Block Header
• A block’s identifier is the hash of its header.
• Key elements for generating block hash:
o Timestamp
o Previous Block Hash
o Merkle Root
o Difficulty Bits
o Nonce
o Version
• Hashing is usually done with double SHA256 (hash of the hash).
What exactly are Bitcoin Scripts?
Bitcoin Scripts are small programs that tell the Bitcoin network how and when a bitcoin
can be spent.
• Every time you receive bitcoins, they aren't just sitting there free.
• They are locked with a set of rules (written in a script).
• You must satisfy those rules to spend them.
Think of it like a lock and key:
• The script is the lock.
• When you want to spend, you must provide the key.
• Only if the lock accepts your key, Bitcoin will allow the spend.
How does it work?
When someone sends you Bitcoin:
• They attach a scriptPubKey to it (this defines the lock).
When you want to spend that Bitcoin:
• You create a scriptSig (this is your key).
The network combines your key and the lock, runs the script, and checks if everything is
correct.
• If yes, you can spend it.
• If no, your transaction is rejected.
A simple real-world example:
Suppose:
• Alice sends Bitcoin to Bob.
How does she ensure only Bob can use it?
1. Alice creates a script that says:
"To spend this Bitcoin, you must show a signature that matches Bob's public
key."
2. Bob, when spending, shows:
o His public key.
o His signature.
Bitcoin runs the scripts:
• Checks if Bob’s public key matches.
• Checks if the signature is valid.
If everything is good ➔ Bitcoin moves to Bob.
What do the scripts look like?
Bitcoin scripts are very simple instructions like:
• OP_DUP: Copy the top thing on the stack.
• OP_HASH160: Hash something.
• OP_EQUALVERIFY: Check if two things are equal.
• OP_CHECKSIG: Verify a signature.
It’s like basic math on a whiteboard where Bitcoin is the referee!
Opcode Function
OP_DUP Duplicate the top item on the stack.
Apply SHA-256 followed by RIPEMD-160 hashing
OP_HASH160
to the top item (typically the public key).
Check if the top two items are equal, and if not, mark
OP_EQUALVERIFY
the script as failed.
Check if the signature matches the public key. Verifies
OP_CHECKSIG
that the spender is authorized.
Mark transaction output as provably unspendable
OP_RETURN
(used to store data in the blockchain).
Pushes TRUE onto the stack (used in "anyone-can-
OP_TRUE
spend" scripts).
Makes sure that the current block height/time is
OP_CHECKLOCKTIMEVERIFY greater than a specified lock time (used to "freeze"
funds until a time).
OP_DROP Remove the top item from the stack.
Absolutely!
Let’s now explain the entire journey — from the very beginning when Alice joins the
Bitcoin network, all the way to her transaction getting recorded on the blockchain.
I’ll go step-by-step, with detailed but clear explanations:
Week 4
Step 1: Alice Joins the Bitcoin P2P
Network
• Alice runs a Bitcoin node (like Bitcoin Core software) on her computer.
• How joining works:
1. Her node contacts Seed Nodes (publicly known, stable Bitcoin nodes) to get a
list of active peers.
2. She connects to several random peers in the network.
3. Her node downloads the current blockchain history from peers (can take
hours because it’s huge — hundreds of GB).
4. Once synced, her node is fully active and participating in the network.
• Important: All nodes are treated equally — no central server.
Step 2: Alice Creates a Transaction
• Now, Alice wants to send 10 BTC to Bob.
• Using her wallet app, she creates a transaction:
o She specifies the amount and destination address.
o She digitally signs the transaction with her private key (proving ownership of
the Bitcoins).
o She attaches scripts that specify how Bob can spend the coins.
At this stage, it’s just a "proposal" created locally.
Step 3: Alice Broadcasts (Floods) the
Transaction
• Alice’s node broadcasts the transaction to its connected peers.
• Those peers validate the transaction:
o Is it correctly signed?
o Does Alice own enough Bitcoin (checking the blockchain)?
o Is the script safe (no malicious code)?
o No double spending?
If valid, each peer adds it to its mempool and relays it to their peers.
If invalid, they drop it.
Flooding = transaction spreads across the network.
Step 4: Nodes Maintain Their Mempool
• Every node maintains a mempool (temporary storage of unconfirmed transactions).
• Alice’s transaction sits in the mempool, waiting to be picked up by a miner.
• Because of network delays, some nodes might see slightly different sets of pending
transactions.
Step 5: Miners Pick Transactions
• Miners are nodes that try to create new blocks.
• Each miner selects transactions from their own mempool:
o Prioritizing those with higher fees.
o Ensuring validity (no invalid or conflicting transactions).
• The selected transactions are assembled into a candidate block.
Step 6: Miner Starts Mining (Proof of
Work)
• Miner builds a block:
o It contains:
▪ Block header (previous block’s hash, timestamp, nonce, etc.)
▪ List of transactions (including Alice's)
• Miner starts doing Proof-of-Work:
o Trying to find a nonce that makes the block hash meet the required difficulty
target.
• This step is computationally intensive — like winning a lottery.
Step 7: Miner Finds a Valid Block
• One lucky miner eventually solves the puzzle.
• They broadcast the newly mined block to the entire network.
Step 8: Other Nodes Validate the New
Block
• Upon receiving the new block:
o Nodes verify:
▪ Is the Proof-of-Work valid?
▪ Is the block structure correct?
▪ Are all transactions inside valid?
▪ Does the block properly link to the current chain?
• If all checks pass, they accept the block and append it to their local blockchain copy.
Step 9: Transaction is Officially
Recorded
• Alice’s transaction, included inside the block, is now:
o Confirmed (1 confirmation).
o Irreversible after a few more blocks (6 confirmations is standard for high
security).
Now Bob officially owns the 10 BTC.
Super Quick Timeline of Alice’s
Journey
1. Alice joins Bitcoin network
2. Alice creates transaction
3. Transaction floods across nodes
4. Nodes validate + add to mempool
5. Miner picks transaction from mempool
6. Miner mines a block
7. Block is broadcast and validated
8. Alice's transaction is confirmed in the blockchain
Summary Table
Step Action Purpose
1 Join network Become part of Bitcoin P2P.
2 Create transaction Specify who to send BTC to.
3 Broadcast Spread transaction to network.
4 Validate Ensure transaction is legitimate.
5 Miner picks transaction Prepare to record it.
6 Mining Solve Proof-of-Work puzzle.
7 Broadcast block Inform network of new block.
8 Validate block Ensure no cheating.
9 Confirm transaction Make transaction permanent.
Important Insights
• Flooding and Validation happen before mining.
• Mining gives the final "seal" of trust.
• Nodes individually validate everything — no trust needed.
• Consensus happens automatically based on Proof-of-Work and longest chain rules.
1. Block Reward and Coin Creation
• Controlled Supply:
Bitcoin's value comes from being limited. If people could create unlimited bitcoins,
they’d become worthless. So, Bitcoin has rules that automatically reject any fake or
malicious coins.
• Mining:
Bitcoins are created as rewards for mining — finding new blocks in the blockchain.
When a miner discovers a block, they are awarded newly created bitcoins.
• Block Rate Adjustment:
Mining is calibrated so that on average, a block is found every 10 minutes. Every
2016 blocks (~2 weeks), the network adjusts the mining difficulty so that even if
computers get faster, it still roughly takes 2 weeks for 2016 blocks.
• End of Bitcoin Mining:
Bitcoin is designed to mine its last coin around 2140, assuming the rules don't change.
2. Block Reward Reduction
• Halving Event:
The number of bitcoins given as a reward per block is cut in half every 210,000
blocks (~every 4 years).
Example:
o Initially, miners got 50 BTC per block.
o Then 25 BTC, then 12.5 BTC, and so on.
• Impact of Halving:
o Over time, miners earn fewer bitcoins for each block they mine.
o This limits Bitcoin’s total supply to just under 21 million coins.
o Miners will increasingly rely on transaction fees to earn money in the future.
3. Projected Number of Bitcoins
• There is a theoretical limit — ~21 million bitcoins.
• The number of new bitcoins entering the system shrinks over time because of the
halving events.
4. Sending Bitcoin (How Payments Work)
• Basic steps:
o Bob sends his address (a kind of public identifier) to Alice.
o Alice creates a transaction by mentioning Bob’s address and the amount of
bitcoins she wants to send.
o Alice signs the transaction using her private key to prove ownership.
o She broadcasts this signed transaction to the Bitcoin network.
• Security:
The network can use Alice’s public key to verify that the transaction was validly
signed.
5. Double Spending Problem
• What is it?
Double spending means using the same bitcoin twice — like spending the same Rs.
500 note in two shops.
• In traditional banking:
A central server (the bank) ensures that once you spend money, it's deducted from
your balance immediately.
• In Bitcoin:
There is no central server. So to prevent double spending:
o Bitcoin uses the blockchain.
o Longest Chain Rule:
If there are competing transaction histories, the network accepts the longest
valid chain as the true one.
o Once a transaction is deep enough in the blockchain (confirmed in several
blocks), it is practically impossible to reverse.
6. Bitcoin Anonymity
• No Accounts:
You don't need a username, password, or email to use Bitcoin. You just need a wallet
that generates a public-private key pair.
• Public Key & Address:
o A Bitcoin address is derived from your public key.
o Example address: 1PHYrmdJ22MKbJevpb3MBNpVckjZHt89hz
o A user can create unlimited addresses.
• Privacy:
Since there are no names attached to addresses, it's hard to link real-world identity
to Bitcoin balances unless you reveal it yourself.
7. Reality of Bitcoins
• No Physical Coins:
Bitcoins are not tangible or stored as files — they are just records showing you have
control of certain addresses.
• Access to Bitcoins:
To “own” bitcoins means having:
o The public key others use to send bitcoins to you.
o The private key you use to spend them.
• Private Key Importance:
If you lose your private key, you lose access to your bitcoins forever.
8. Physical and Online Payments
• You just need your private key to make a payment.
• You can store private keys:
o On a desktop, phone, or even printed as a QR code on paper.
• Offline Payments:
For in-store transactions, you can present the QR code or use an app, similar to
PayTm or Google Pay.
9. Bitcoin Exchanges
• Trading Bitcoin:
You can buy and sell bitcoins like a commodity.
• Centralized Exchanges (e.g., WazirX, CoinDCX, ZebPay):
o Require KYC (Know Your Customer) verification with ID proof.
o Let you deposit INR (or other currencies) to buy/sell bitcoins.
o Let you set prices and withdraw your money into a bank account.
o Some offer prepaid cards that you can use anonymously.
• Decentralized Exchanges:
o No central authority.
o Handle trading peer-to-peer with smart contracts or other mechanisms.
Summary of Topics Covered:
• Mining and block reward system
• How rewards decrease over time
• How Bitcoin solves double spending
• The nature of Bitcoin’s anonymity
• How Bitcoin payments work (online and offline)
• Role of exchanges in Bitcoin trading
Alright, here’s a detailed explanation of your PDF titled "Permissionless Model":
1. Permissionless Model
• Definition:
A permissionless model refers to an open network where anyone can join and
initiate transactions without needing any prior approval.
• Key Features:
o Anyone can join or leave the network freely.
o The assumption is that more than 50% of participants are honest.
(Otherwise, the system's trust and functioning collapse — similar to society!)
2. Permissionless Blockchain Challenges
• Participants are anonymous:
They don't necessarily know or trust each other.
• No direct message passing:
Unlike closed networks, participants cannot rely on direct communication.
• Anyone can propose blocks:
Anyone can submit a new block to the blockchain.
• Who adds the next block?:
o It's a challenge to decide which block is officially added.
o Different participants might see blocks in different orders because:
▪ The network is asynchronous.
▪ There is no global clock to synchronize everyone.
• Monopoly prevention:
It's important to prevent any one participant or group from dominating the
network.
3. Synchronous vs Asynchronous Networks
• Synchronous Networks:
o Messages arrive with minimal or no delay.
o You can expect responses on time.
• Asynchronous Networks:
o No guarantee of message delivery time.
o Messages might be delayed indefinitely.
o Blockchain networks (like Bitcoin) operate asynchronously.
4. Failures in Distributed Systems
Failures are inevitable in networks. Three types are described:
• Crash Fault:
A node simply stops responding.
• Link Fault (or Network Fault):
A communication link fails; messages are lost or delayed.
• Byzantine Fault:
A node behaves maliciously, e.g., sending wrong or conflicting information.
5. FLP Impossibility
• FLP Theorem:
In an asynchronous network, perfect consensus is impossible if even one node can
fail.
• Consensus cannot guarantee both:
o Safety (correctness) and
o Liveness (progress).
Simultaneously achieving both is mathematically impossible under these conditions.
6. Safety vs Liveness
• Nakamoto Consensus (Bitcoin’s Proof of Work) prioritizes liveness over safety:
o Focus is on keeping the system moving forward (new blocks get added).
o Safety (e.g., block finality) is achieved eventually, once blocks become
buried under enough confirmations.
7. The Consensus Problem (Illustration with Miners)
• Scenario:
o Many transactions are floating around (unconfirmed).
o Multiple miners try to create the next block using different transactions.
• Miners view different sets of transactions:
o Because the network is asynchronous and each miner may receive different
transactions at different times.
• Different blocks could be created simultaneously:
o This creates a temporary fork in the blockchain.
• Challenge:
o Which block should be accepted as the next official one?
o Blockchain uses mechanisms like longest chain rule to resolve these forks.
8. Conclusion
• Message passing cannot be trusted in open networks (can't guarantee quick delivery).
• FLP impossibility states we can't simultaneously guarantee both safety and
liveness.
• In blockchains, liveness is prioritized:
o It's more important to add a block now and worry about finality later.
• Miners see different blocks — hence, conflicts happen, but the blockchain protocol
handles them over time.
In short:
Permissionless blockchain networks are open, decentralized, asynchronous systems where
trust is minimized, failures are tolerated, and eventual consensus is the goal — not
immediate correctness.
Would you like me to also create a simple diagram summarizing this?
It could make it even easier to visualize!
Alright, I'll explain the PDF you uploaded ("Nakamoto Consensus") in detail.
Nakamoto Consensus:
It talks about how Bitcoin (and similar blockchains) achieve consensus — meaning how all
participants agree on the same history of transactions — using Nakamoto Consensus (Proof
of Work or PoW system).
It dives into topics like:
• The consensus problem itself
• The tradeoff between safety and liveness
• Mining, forks, attacks (like 51% attacks), and
• Challenges like the monopoly problem.
In-Depth Explanation:
1. What is the Consensus Problem?
• In a blockchain, there are many miners each with their own list of unconfirmed
transactions (TXs).
• They need to agree on the next block to add to the chain.
• Challenge:
They all have slightly different views.
➔ How do they pick a single correct block?
2. Safety vs. Liveness:
Concept Meaning
Safety The block added must be correct and everyone must agree on it.
Progress must continue — add blocks and move forward even if agreement isn't
Liveness
perfect.
Details:
• Safety-1: The block must be valid (correct hash, valid transactions, nonce).
• Safety-2: All miners should agree on a single block.
• Problem: Miners don't know each other directly. Coordination is hard.
3. How PoW (Proof of Work) Handles It:
• Compromise: PoW focuses on liveness more than perfect safety.
• If two miners create two blocks at once ➔ forks happen.
• The fork is resolved later when the chain grows longer.
4. Mining a Block:
• Each miner:
1. Picks some transactions.
2. Packs them into a block.
3. Tries to find a nonce such that the block's hash meets certain difficulty
criteria.
4. First miner to find it broadcasts the block.
5. Others verify it quickly (because verifying is easy).
5. Forks in the Blockchain:
• When two miners solve the PoW puzzle at almost the same time ➔ Fork occurs.
• Different parts of the network might temporarily believe different blocks are the
"latest."
• Resolution:
Whichever chain becomes longer (i.e., more proof of work added) is considered the
valid one.
Miners will abandon the shorter fork.
6. Problems with PoW:
a) Consensus Finality Delay:
• Unlike traditional systems, consensus is not immediate.
• Finality happens after multiple blocks (Bitcoin waits for 6 confirmations).
b) Attacks:
• Sybil Attack: Create many fake nodes to control the network.
➔ Bitcoin limits connections to prevent this.
• Denial of Service (DoS): Overload a node with data.
➔ Solutions: limit forwarding, disconnect spammy nodes.
c) Breaking PoW:
• While PoW is hard to break, it is not impossible.
• Example:
In 2013, [Link] mining pool was accused of repeated fraud by controlling large
hash power.
7. The Monopoly Problem:
• Miners with more resources have a higher chance of mining blocks.
• Over time, rewards decrease ➔ small miners leave ➔ large miners dominate ➔
centralization.
• 51% Attack:
If one group controls more than 50% of hash power, they can:
o Reverse transactions,
o Double-spend,
o Prevent other miners from mining valid blocks.
o (Real example: Kryptom blockchain in 2016)
Conclusion:
• Nakamoto Consensus allows decentralized blockchains to move forward without
central control.
• It sacrifices perfect safety for guaranteed progress (liveness).
• It is resilient, but not invincible — especially against powerful mining groups.
Week 5
1. The Limits of Proof of Work (PoW)
The Good:
• PoW enables fully decentralized consensus.
• Works well for cryptocurrencies (e.g., Bitcoin, Ethereum).
The Bad:
• Trust is placed not in individuals, but in the network as a whole.
• Requires a very large network to prevent attacks like the 51% attack (where an
entity controlling 51% computing power can cheat).
• Not suitable for enterprises (who can't afford huge networks).
The Ugly:
• Very low transaction throughput:
o Bitcoin ≈ 3.3 to 7 transactions per second
o Ethereum ≈ 15 transactions per second
• Wasted computing power: Millions of miners attempt the same block but only one
succeeds.
2. Bitcoin Energy Consumption
• Bitcoin mining uses huge energy.
• Carbon footprint:
o 825.47 kg CO₂ per transaction (equal to 137,578 hours of YouTube
watching).
• Electricity:
o 1737.82 kWh per transaction (enough to power an average US household for
~60 days).
3. Alternatives to PoW
A. Proof of Stake (PoS)
• Idea proposed in 2011 on Bitcoin Forum.
• Instead of computing power, mining probability is based on how many coins you
own.
• If you own 1% of bitcoins, you can mine 1% of new blocks.
Advantages:
• Attacking is expensive (you must own most coins).
• Attackers hurt themselves because they lose the value of their coins during an attack.
Variants:
• Randomization + Stake: Used in Nxt and BlackCoin.
• Coin-age: Coins held for a longer time have more weight (used in Peercoin).
B. Proof of Burn (PoB)
• Miners must burn (destroy) coins by sending them to an unspendable address.
• Burning proves their commitment.
• Expensive like PoW but no real-world resources are wasted, only digital ones.
Comparison:
• PoW burns real-world resources (energy).
• PoB burns virtual resources (coins).
Important:
• PoB usually depends on cryptocurrencies originally created via PoW (e.g., Bitcoin).
• So, it cannot independently bootstrap a new blockchain without PoW.
C. Proof of Elapsed Time (PoET)
• Proposed by Intel for enterprise-grade blockchain (e.g., Hyperledger Sawtooth).
• Basic idea: Each participant waits a random time.
• The first to finish waiting wins the block creation right.
Verification Challenge:
• How do we know someone really waited?
• Intel SGX (Software Guard Extensions) is used:
o A trusted hardware platform that ensures the waiting was genuine.
o Special CPU instructions keep trusted code isolated and verifiable.
4. Conclusion
• PoW is very expensive (energy, resources).
• PoS and PoB can reduce costs but depend on already mined PoW coins.
• PoET offers low-cost consensus for enterprises but needs specialized hardware
(Intel SGX).
Quick Summary Table:
Feature PoW PoS PoB PoET
Time Waiting
Main Resource Computing Power Coin Ownership Burned Coins
(SGX secure)
Cost Very High Moderate Moderate Low
Environmental
Very High Low Low Very Low
Impact
Feature PoW PoS PoB PoET
Open Enterprise
Suitable for Cryptocurrencies Cryptocurrencies
cryptocurrencies applications
Would you also like me to create a mind map diagram summarizing it visually? (If yes,
I can generate a neat one for you!)
Method Functionality
Fetches the balance of an Ethereum account at a specific block
eth_getBalance
(e.g., "latest").
Creates and sends a new transaction from one account to
eth_sendTransaction another, or deploys a smart contract if the data field contains
contract code.
eth_getTransactionByHash Retrieves the details of a transaction using its transaction hash.
Fetches information about a block by specifying its block
eth_getBlockByNumber
number (e.g., "latest" or a hex number like "0xA1B2C3").
Week 6
Alright, I’ll explain the Week 6_1.pdf you shared in detail.
This document mainly talks about blockchain in permissioned environments and how
smart contracts are executed there, using the idea of state machine replication and
consensus.
I'll break it down carefully:
1. Permissioned Model
• What is it?
A permissioned blockchain is a blockchain where all participants are pre-approved
and authenticated before they can join.
• Key Points:
o Users are known to the system (through something like an MSP –
Membership Service Provider).
o Even though users know each other, they might not trust each other fully.
o Therefore, security and consensus protocols are still necessary.
o This model is suitable for business applications, like supply chain tracking,
where a closed set of players interact.
2. Smart Contracts Over Closed Networks
• What is a Smart Contract?
o It's a self-executing program where terms are embedded directly into code.
o Example source quoted: [Link]
• How smart contracts work here:
1. The contract is stored on the blockchain.
2. When an event is triggered, the smart contract executes locally on each
peer.
3. After execution, a transaction is created as an output.
4. Other peers validate this transaction.
5. If valid, it’s committed to the blockchain.
6. This might trigger further events.
• Challenge Raised in the PDF:
o "Do we need to execute the code on each peer?"
o The answer is: not necessarily.
▪ Instead, only a subset of peers can execute.
▪ Then, share the agreed result (state) with others.
▪ Need a proof that the result is genuine.
3. Smart Contracts as State Machines
• State Machine Representation:
o Any deterministic program (same output for same input) can be modeled as
a state machine.
• Example given:
• S1:
• while (moreGoods == 1)
• DeliverGoods();
•
• S2:
• if (allOrderComplete == 0) goto S1;
• else
• S3:
• printf("Goods transfer complete");
Here, S1, S2, and S3 are states, and the system moves based on conditions.
4. State Machine Replication
• Concept:
o The state machine (smart contract logic) is replicated across multiple nodes
(peers).
• How it works:
1. Transactions like T1 ("I have delivered 100kg potatoes") and T2 ("I have
delivered 50kg tomatoes") occur.
2. Peers reach consensus on the order of these transactions.
3. Every peer independently executes these transactions in the same order.
4. All peers reach the same final state after executing all transactions.
• Importance of Consensus:
o Without consensus, peers might have different views of the blockchain's
current state.
o Majority voting helps agree on the correct final state.
• Example in the PDF:
o S2 (intermediate state) and S3 (completion state).
o If some nodes reach S2 and others S3, the network needs to agree (majority),
ensuring everyone eventually agrees on S2 or S3, maintaining consistency.
5. Conclusion
• Consensus is still crucial even in permissioned environments where everyone is
"known."
• The model discussed extends the state machine replication technique from open
(public) blockchains to permissioned (private) models.
Summary Flow
Permissioned Blockchain → Smart Contract → Execution at subset of nodes → State
Machine Model → Replication → Consensus → Final Agreement
Crash faults and Crash Fault Tolerance (CFT) are fundamental concepts in distributed
systems, particularly in consensus algorithms. Let’s break this down clearly:
What Are Crash Faults?
Crash faults refer to a failure type where a node (i.e., a server or process in a distributed
system):
• Suddenly stops working.
• Does not send or receive any messages after crashing.
• Does not behave erratically or send incorrect data (unlike Byzantine faults).
Think of it like a machine that just powers off unexpectedly and doesn’t come back up.
What Is Crash Fault Tolerance (CFT)?
Crash Fault Tolerance (CFT) is the ability of a distributed system to continue operating
correctly even if some nodes crash. The key is that the system must still reach consensus
(i.e., agreement among the non-faulty nodes) despite some participants going silent.
CFT Consensus – In Detail
Let’s dive deeper into how CFT-based consensus works:
1. Assumptions
CFT consensus algorithms assume:
• Nodes may crash, but they don’t behave maliciously or send false messages.
• The network is reliable enough to deliver messages in a timely manner (or has
timeouts).
• A majority of nodes are correct and operational.
2. Goal
Ensure all non-faulty nodes:
• Agree on the same value.
• Don’t get stuck waiting for crashed nodes.
• Progress even if a subset crashes.
3. Number of Nodes Required
To tolerate f crash faults, you need at least:
n = f + 1
to make progress, but for most consensus protocols like Paxos or Raft, you typically need:
n = 2f + 1
This ensures a majority quorum can always be formed.
Examples of CFT Consensus Protocols
1. Paxos
• A classic algorithm by Leslie Lamport.
• Uses roles like proposer, acceptor, and learner.
• Tolerates crash faults through majority quorums.
• Complex in implementation, but very robust.
2. Raft
• Designed to be easier to understand than Paxos.
• Uses a leader-based approach:
o One leader handles all client requests and replicates logs to followers.
o If the leader crashes, a new leader is elected.
• Tolerates crash faults of up to ⌊(n−1)/2⌋ nodes.
Trade-offs of CFT
Pros Cons
Simpler and faster than Byzantine Fault Only protects against crash faults, not
Tolerance (BFT) malicious ones
Widely used in practice (e.g., Raft in etcd, Not secure against message corruption or
Consul, Kubernetes) tampering
Real-World Use Cases
• Kubernetes (uses etcd, based on Raft)
• Consul by HashiCorp
• Zookeeper (uses Zab, similar to Paxos)
Summary
• Crash faults = silent failure of nodes.
• CFT = system continues to work even if some nodes crash.
• Used in protocols like Raft and Paxos.
• Requires majority quorums to tolerate up to f crash faults with 2f + 1 nodes.
Would you like a diagram or example of how Raft or Paxos works during a crash scenario?
Sure! I’ll explain the entire PDF you uploaded, step-by-step and in detail, covering every
topic mentioned.
Full Explanation of the Paxos PDF
1. What is Paxos?
Paxos is a consensus algorithm used to agree on a single value among a group of
participants (even if some participants fail or messages are delayed).
It’s crucial for distributed systems to agree (reach consensus) on a decision to maintain
consistency.
• CFT (Crash Fault Tolerance): Paxos assumes nodes can crash but not behave
maliciously (Byzantine faults are not considered).
2. Roles in Paxos
In Paxos, each node can play one or more of these roles:
• Proposer: Suggests a value for consensus.
• Acceptor: Votes on proposals.
• Learner: Learns the final chosen value.
Important: A node can act as multiple roles (Proposer, Acceptor, and/or Learner).
Example (used in the PDF):
• Proposers suggest "Dinner" or "Movie" (like people deciding what to do).
• Acceptors vote based on majority.
• Learners find out what was finally agreed.
3. Paxos Basics
• Paxos uses state machine replication — every node should apply the same set of
commands in the same order.
• Each proposer and acceptor maintains a state.
• A unique IDp (ID for a proposal) is generated (e.g., by hashing timestamp + proposer
ID).
• Single Consensus: A basic Paxos run reaches one consensus.
Multi-Paxos is used to reach multiple consensuses (over time).
4. The Paxos Algorithm (Step-by-Step)
Step 1: Prepare Phase
• A Proposer sends a PREPARE(IDp) message to a majority of Acceptors.
• IDp must be unique and increasing.
Step 2: Promise Phase
• Acceptors respond:
o If IDp is greater than what they’ve seen before → send PROMISE(IDp).
o Otherwise, they ignore.
Once majority promises are received, lower ID proposals are rejected.
Step 3: Accept-Request Phase
• Proposer sends ACCEPT-REQUEST(IDp, Value) to Acceptors.
• If Acceptors had promised earlier, they accept this value.
Step 4: Accept Phase
• Acceptors send back ACCEPT(IDp, Value) messages.
• Learners receive the accepted value.
Consensus is reached when a majority accepts the same (IDp, Value).
5. Handling Multiple Proposers
When multiple proposers are active:
• If Acceptors already accepted a value (say from IDa), they reply with:
o PROMISE(IDp, accepted IDa, VALUE)
• Then, the new proposer must:
o Pick the highest accepted value from the promises it received (ensuring
consistency).
o Cannot randomly propose a new value if there's an older value already
partially accepted.
6. Paxos Correctness: Safety and Liveness
Safety
• Paxos guarantees that only one value is chosen, even if nodes fail or recover.
• No two different values can be agreed upon for the same instance.
Liveness
• Paxos might not terminate quickly.
• If messages are lost, proposers conflict, or network delays happen, the algorithm may
not make progress.
(Paxos prefers safety over liveness.)
7. Majority Voting in Paxos
• To reach consensus, a majority of acceptors must agree.
• Any two majorities overlap in at least one acceptor, ensuring consistency.
• Examples covered:
o When multiple PREPAREs happen.
o What happens when a lower-ID proposal tries to continue (it fails if a higher-
ID consensus is underway).
8. Liveness Problem Example
The PDF shows how:
• A proposer can keep retrying with higher ID numbers (ID 150, ID 200, etc.).
• But if other proposers keep interfering, Paxos may delay termination.
9. Majority of Accepts and Conflict
• If a value is accepted by a majority:
o New proposals with a lower ID cannot succeed.
o New proposals with a different value but higher ID also fail, because
acceptors remember old values.
This ensures that once a value is chosen, it stays chosen.
10. Paxos for Leader Election
Paxos can be used to elect a leader:
• Instead of agreeing on a general value, nodes agree on a Leader ID.
• The same Paxos phases are followed.
11. Multi-Paxos
When you need continuous consensus (like in databases, blockchains):
• You don't run Paxos once.
• Instead, you run multiple Paxos instances (one per round).
Each consensus decision is tagged with a round number.
12. Paxos Attack Example
The PDF briefly shows that if a node sends wrong messages, Paxos can struggle:
• Example: Node accepts a PREPARE50 after promising PREPARE100.
• This breaks the proper promise system and can cause problems.
Therefore, trust assumptions are critical in Paxos (no Byzantine behavior).
Summary
Aspect Details
What is Paxos? Consensus algorithm for distributed systems.
Roles Proposer, Acceptor, Learner (nodes can play multiple roles).
Algorithm Prepare → Promise → Accept-Request → Accept
Safety Only one value is chosen.
Liveness Progress may not always be guaranteed.
Multi-Paxos Runs multiple rounds for many consensus decisions.
Leader Election Paxos can select a leader using consensus.
Week 7
Alright, the PDF you uploaded is about "Liveness in Practical Byzantine Fault Tolerance
(PBFT)". Let me explain it clearly in parts:
PBFT Basics
• PBFT (Practical Byzantine Fault Tolerance) is a consensus algorithm designed to
work even when some nodes behave maliciously (called Byzantine faults).
• It needs 3f + 1 nodes to tolerate f faulty nodes.
Key Components in PBFT
1. Primary (Leader) – One node coordinates the protocol.
2. Replicas (Backups) – Other nodes that validate and agree on requests.
3. Message Flow – For every client request:
o Pre-Prepare → Primary proposes an order for the request.
o Prepare → Replicas agree on the proposed order.
o Commit → Replicas commit to the request.
o Reply → Final reply is sent back to the client.
Diagram shown:
Client → Primary (P) → Replicas (R1, R2, R3)
Request → Pre-Prepare → Prepare → Commit → Reply
Safety in PBFT
• Single primary avoids the chaos (ping-pong) that happens in other protocols like
Paxos (where many leaders might propose different things).
• 2f+1 quorum ensures:
o Enough correct nodes to reach consensus even if some are faulty.
o Primary can make progress even if some nodes are slow or unresponsive.
Conclusion for safety:
As long as fewer than f nodes are malicious, PBFT guarantees no two correct nodes disagree.
Liveness in PBFT
• Problem: What if the primary fails (e.g., goes offline or behaves incorrectly)?
o Progress stops because everything depends on the primary.
o In a purely asynchronous system, you can't easily tell if the primary is slow or
dead.
Key Idea:
PBFT cannot guarantee liveness (making progress) without extra assumptions.
Weak Synchrony Assumptions
PBFT assumes a "weak synchrony" model to eventually detect a bad primary:
• (1) Sender and receiver are correct.
• (2) Messages are retransmitted until received.
• (3) Message delivery time has a finite but unknown upper bound.
View Change Protocol
What happens when the primary is suspected to be faulty?
• Non-faulty replicas detect the problem (e.g., based on timeouts).
• Start a View Change to choose a new primary.
Steps:
1. Replica starts a timer when it receives a request.
2. If no progress before the timer expires → trigger view change to move to next view
(v+1).
How View Change Works
• Replicas send VIEW-CHANGE messages with:
o n: last stable checkpoint.
o C: set of 2f+1 checkpoint proofs.
o P: prepared messages after n.
• New primary is selected (e.g., round robin or election).
View Change Steps Simplified:
1. Timeout triggers view change at replica.
2. Replicas send VIEW-CHANGE messages.
3. 2f+1 VIEW-CHANGE messages collected → quorum achieved.
4. New primary is chosen.
5. Replicas send View Change ACKs.
6. New View message is sent to begin work again.
Final Takeaways
• PBFT ensures safety with 2f+1 nodes even under Byzantine faults.
• Liveness is vulnerable if the primary is faulty.
• Weak synchrony assumptions + view change help recover liveness.
Week 8
Alright! Let's break down your PDF in detail — it covers Hyperledger Fabric, focusing
mainly on Smart Contracts (Chaincode), Transaction Flow, and Building a DApp.
I'll walk through it systematically:
Part 1: Fabric Smart Contracts and
Chaincode
What is a Smart Contract?
• It's a piece of code that defines business logic (rules/processes) that participants agree
to follow when interacting on the Fabric ledger.
• In Fabric, smart contracts are packaged as Chaincode.
Reference given:
Smart Contract in Fabric Documentation
What is Fabric Transaction Flow?
• How transactions are proposed, endorsed, ordered, and committed to the ledger.
Reference given:
Fabric Transaction Flow Documentation
Writing Chaincode
• Supported languages: Go, [Link], Java.
• Chaincode runs separately from the peer node, inside its own container.
• Uses fabric-contract-api which provides a simple contract interface for building
chaincode.
APIs for different languages:
• Go API
• [Link] API
• Java API
Example: Building a Basic Chaincode in Go
Structure:
type SmartContract struct {
[Link]
}
Functions:
• InitLedger — Initializes ledger with default data (optional in newer Fabric
versions).
• CreateKey — Stores a key-value pair.
• QueryKey — Fetches a value using a key.
Chaincode Startup:
chaincode, err := [Link](new(SmartContract))
[Link]()
Conclusion from Part 1
• Chaincodes manage key-value pairs in the World State.
• Any business rules can be embedded.
Part 2: Hyperledger Fabric Application
(Writing a DApp)
This is about writing a decentralized app (DApp) to interact with Fabric.
Fabric Application Architecture Overview
• Client Application (Your DApp)
• Fabric SDK (library to interact with Fabric)
• Peer nodes (that host Ledgers and Chaincodes)
• Certificate Authorities (CAs) (for identity management)
• Orderers (for ordering transactions)
A diagram was shown, representing connections between:
• Organizations (O1, O2, O3)
• Peers
• Orderer
• Ledger (Blockchain + World State)
• Chaincode
• MSP (Membership Service Provider)
• Client Application through the Fabric SDK.
Reference:
Write Your First Fabric App
Prerequisites
• Fabric DApps can be built in:
o [Link]
o Java
o Go
o Python
SDK references:
Hyperledger Fabric SDKs
Steps to Build the Fabric DApp
1. Imports
You need to import modules like:
const FabricCAServices = require('fabric-ca-client')
const {Wallets, Gateway} = require('fabric-network')
const fs = require('fs')
const path = require('path')
2. Setup Connection Profile and CA Client
• Connection Profile ([Link]) provides network configuration.
• Connect to CA (Certificate Authority) to enroll users.
Example:
const ccpPath =
[Link]('../organizations/peerOrganizations/[Link]/connectio
[Link]')
const ccp = [Link]([Link](ccpPath, 'utf8'))
const caInfo = [Link]['[Link]']
const caTLSCACerts = [Link]
const ca = new FabricCAServices([Link], { trustedRoots: caTLSCACerts,
verify: false }, [Link])
3. Enroll CA Admin
You enroll the admin using CA and store their identity:
const enrollment = await [Link]({ enrollmentID: 'admin',
enrollmentSecret: 'adminpw' })
await [Link]('admin', { ...admin identity info... })
4. Register and Enroll a New User
Register a new user (appUser) through the admin, enroll them, and save into wallet.
5. Connect to Fabric Network
Using the Gateway to:
• Connect to the channel (mychannel).
• Get the Chaincode handle.
Example:
const gateway = new Gateway()
await [Link](ccp, {wallet, identity:'appUser', discovery:
{enabled: true, asLocalhost: true}})
const network = await [Link]('mychannel')
const contract = [Link]('keyvaluechaincode')
6. Query and Invoke Chaincode
• Query key-value pairs:
const result = await [Link]("QueryKey", "nptel")
• Create or update keys:
await [Link]("CreateKey", "nptel", "a new value")
7. Disconnect
Always close your connection once done:
await [Link]()
Final Conclusion
• You now know how to build and interact with Fabric using a DApp.
• You learned about Chaincode, Fabric SDK, Identities, Fabric CA, Querying and
Invoking Transactions.
TL;DR
Topic Summary
Smart Contracts Business logic stored on-chain, written as chaincode
Fabric Transaction
How Fabric processes transactions
Flow
Chaincode Writing In Go, Java, [Link]; Key-Value operations shown
Building DApp Setup CA, enroll admin and users, connect and interact
Fabric SDK, CA-client, connection profile JSON, Wallets, Gateway
Tools Used
APIs
Okay, here is a detailed summary of the three lectures (Lecture 40: CoSi, Lecture 39: Bitcoin-
NG, and Lecture 38: Consensus Scalability) based on the provided text and images:
Lecture 39: Bitcoin-NG (Next Generation)
• Introduction: This lecture introduces Bitcoin-NG, a specific protocol designed to
improve the scalability of PoW-based blockchains like Bitcoin, directly addressing
the limitations discussed in the previous lecture.
• Revisiting Nakamoto Consensus Issues:
o Transaction Scalability: Hampered by the fixed 10-minute block frequency
and block size limit (originally 1MB, later 8MB), leading to low TPS. The 10-
minute interval is necessary to allow time for difficult PoW mining, ensuring
security.
o Forks: Prevent consensus finality and create unfairness, disadvantaging
miners with poor network connectivity whose blocks may be orphaned.
• Core Idea of Bitcoin-NG: Decouple Leader Election from Transaction
Serialization.
o Bitcoin: PoW mining simultaneously elects a leader (winning miner) and
serializes transactions for one block.
o Bitcoin-NG:
▪ Leader Election: Uses PoW infrequently (e.g., ~10 mins) to elect a
leader. The block generated during this phase is called a Key Block.
▪ Transaction Serialization: The elected leader is then empowered to
create multiple subsequent blocks, called Microblocks, containing
transactions without performing PoW for each one. Microblocks are
generated frequently until the next leader is elected via a new Key
Block.
• Block Structure:
o Key Blocks: Used to choose a leader (similar to Bitcoin blocks). Contains
reference to previous block, timestamp, coinbase transaction, target hash
value, and nonce field. Generated infrequently based on PoW mining.
o Microblocks: Generated frequently by the current leader. Contain ledger
entries (transactions) and a header. The header includes a reference to the
previous block (key or micro), timestamp, Merkle root of transactions, and
crucially, a cryptographic signature from the leader (the miner who created
the last key block). This signature authenticates the microblock.
• Mechanism:
1. A miner solves PoW and generates a Key Block, becoming the leader.
2. This leader then rapidly generates Microblocks, filling them with transactions
and signing them with their private key (corresponding to the public key
implicitly included in the Key Block).
3. This continues until another miner generates the next Key Block, taking over
leadership.
• Microblock Fork Challenge: If microblock generation is very frequent, a new leader
might create a Key Block referencing an older microblock because they haven't
received the latest one yet, causing a fork where recent microblocks are orphaned.
Mitigation involves nodes waiting briefly before accepting microblocks to allow for
propagation.
• Performance Benefits:
o Latency: Significantly reduced because transactions are confirmed quickly in
microblocks, not waiting for the ~10 min key block interval.
o Throughput: Increased because many microblocks can be generated between
infrequent key blocks.
o Fairness: Improved compared to Bitcoin, as the impact of slow network
propagation is lessened (microblocks are smaller/more frequent than key
blocks).
• Conclusion (Lecture 39): Bitcoin-NG improves upon Bitcoin by separating leader
election (Key Blocks) from transaction processing (Microblocks). This allows for
higher throughput and lower latency while maintaining the decentralized nature of
PoW for leader selection. It represents a significant step towards scalable PoW
consensus but still falls short of BFT performance.
Lecture 40: Collective Signing (CoSi)
• Introduction: This lecture introduces Collective Signing (CoSi), a cryptographic
technique aimed at further enhancing consensus scalability, potentially building on
ideas like Bitcoin-NG or providing alternatives. It focuses on efficiently combining
signatures from multiple parties.
• What is Collective Signing (CoSi)?
o A method where a statement or transaction is signed by a group of authorities
or witnesses collectively, rather than individually or sequentially.
o Provides stronger assurance and trust, as multiple parties vouch for the
statement.
o Inspired by real-world scenarios like multi-level institutional approvals or
marriage witnesses.
o Goal: Scalable protocol ensuring statements are validated by a diverse group
before acceptance. (Based on Syta et al. paper).
• CoSi Architecture:
o Involves a leader (or authority) and multiple witness cosigners.
o Witnesses are organized in a tree structure. This allows for efficient
aggregation of cryptographic material (commitments and signatures).
o Signatures are aggregated from the leaves up to the root, making the process
scalable with the number of signers (logarithmic complexity instead of linear).
• Schnorr Multisignature:
o The core cryptographic primitive used in the basic CoSi protocol. It allows
multiple signatures on the same message to be aggregated into a single,
compact signature verifiable with a single aggregated public key.
o Relies on: Group G of prime order where the Discrete Logarithm Problem
(DLP) is hard.
o Key Generation: Each signer i has private key xi and public key g^xi.
o Signing (Multi-round protocol within the tree):
1. (Commitment Phase) Each signer i picks random vi, computes
commitment Vi = g^vi. Commitments are aggregated up the tree
(product V = Π Vi).
2. (Challenge Phase) Leader computes collective challenge c = H(V || S)
(S=message), sends c down the tree.
3. (Response Phase) Each signer computes response ri = vi - c*xi.
Responses are aggregated up the tree (sum r = Σ ri).
▪ Final aggregated signature is (c, r).
o Verification:
1. Compute the aggregated public key y = Π g^xi.
2. Given signature (c, r) and message S, compute V_check = g^r * y^c.
3. Compute c_check = H(V_check || S).
4. Verify if c_check == c. If true, the collective signature is valid.
o Scalability Benefit: Verification requires only the single aggregated public
key y, regardless of the number of signers.
• PBFT Emulation using CoSi:
o A key application: CoSi can simulate PBFT rounds more efficiently.
o Round 1 (CoSi): Can implement PBFT's pre-prepare and prepare phases
(broadcasting the proposal and collecting signed acknowledgments).
o Round 2 (CoSi): Can implement PBFT's commit phase (confirming sufficient
agreement).
o Result: Two CoSi rounds emulate three PBFT rounds, potentially reducing
communication/latency.
• Other Multisignatures: Mentions BLS (Boneh–Lynn–Shacham) signatures as
another important and scalable multisignature scheme based on bilinear pairings.
• Conclusion (Lecture 40): CoSi provides a scalable way for multiple authorities to
sign a message collectively. Using primitives like Schnorr or BLS multisignatures, it
allows for efficient aggregation and verification (via a single collective key). It can be
used to optimize consensus protocols like PBFT by reducing the number of
communication rounds needed.
Overall Synthesis:
These three lectures build upon each other to address the critical issue of scalability in
blockchain consensus.
• Lecture 38 establishes the problem by comparing the trade-offs between traditional
PoW (good node scalability, low throughput, probabilistic finality) and PBFT (limited
node scalability, high throughput, deterministic finality) and showing the difficulty of
simply tuning PoW parameters.
• Lecture 39 presents Bitcoin-NG as a concrete solution to improve PoW's throughput
and latency by decoupling leader election (infrequent Key Blocks) from transaction
serialization (frequent Microblocks signed by the leader), offering a better balance.
• Lecture 40 introduces CoSi as a more general cryptographic technique using
multisignatures (like Schnorr or BLS) to efficiently aggregate approval from multiple
parties. This offers further scalability improvements, particularly in verification, and
can even be used to emulate and potentially optimize protocols like PBFT.
The progression shows a move from identifying the scalability bottleneck in consensus
towards increasingly sophisticated protocol designs (Bitcoin-NG) and cryptographic
primitives (CoSi/multisignatures) to achieve better performance and efficiency in blockchain
systems.
Practical Byzantine Fault
Function Proof of Work (PoW)
Tolerance (PBFT)
Achieving decentralized consensus Achieving consensus in a
without a trusted authority, permissioned blockchain, ensuring
Primary Purpose
ensuring security in a agreement even with faulty or
permissionless blockchain. malicious nodes.
Tolerates honest majority but
Tolerates up to 1/3 of nodes being
Fault Tolerance doesn’t have a formal guarantee for
Byzantine or malicious.
Byzantine faults (malicious nodes).
Probabilistic finality — A block is
Instant finality — Once a
added to the chain, but it can be
Finality transaction is committed, it is final
reorganized if a longer chain is
and cannot be reverted.
found.
Mining: Miners compete to solve Voting: A leader node proposes a
Consensus Process cryptographic puzzles (hashing) to block, and other nodes (replicas)
propose the next block. vote on it in multiple rounds.
Low (each miner only
High (requires multiple rounds of
Communication communicates when submitting a
communication between all nodes
Overhead block, and the network propagates
to achieve consensus).
the block).
Practical Byzantine Fault
Function Proof of Work (PoW)
Tolerance (PBFT)
Low scalability — The network’s Moderate scalability — Can
throughput and speed can be scale to a certain number of nodes,
Scalability limited by block size and mining but performance degrades as the
difficulty. The more miners, the number of participants increases
more computation is required. due to communication overhead.
Hash-based security — The
Trust-based security — The
security is based on the
security is based on the
computational power of miners.
Security Model assumption that a majority of
The more computational work is
nodes are honest and will follow
done, the harder it is to reverse or
the protocol.
alter the blockchain.
Higher throughput — PBFT can
Lower throughput — Bitcoin
achieve a higher transaction rate
(PoW) has a low transaction
Throughput since it doesn’t rely on proof of
throughput due to block intervals
(Transaction Rate) work, but communication
(10 minutes for Bitcoin) and block
overhead limits scalability as the
size limits.
number of nodes increases.
High energy consumption — Low energy consumption —
PoW requires miners to use PBFT relies on communication
Energy
significant computational resources between nodes and does not
Consumption
to solve puzzles, which leads to require intensive computational
high energy consumption. work like PoW.
Highly decentralized — PoW
Less decentralized — Typically
allows anyone with computational
used in permissioned blockchains,
Decentralization power to join and participate in the
where the number of validators is
network, promoting
controlled.
decentralization.
Variable — Depends on the
Fixed — In PBFT, blocks are
mining difficulty and the
Block Creation created once consensus is reached,
computational power of miners.
Time which is typically faster than PoW
For Bitcoin, this is approximately
but depends on network size.
10 minutes per block.
Permissioned blockchains (e.g.,
Public, permissionless blockchains
Hyperledger, Tendermint, and
Use Cases (e.g., Bitcoin, Ethereum before the
certain private blockchain
shift to PoS).
networks).
Non-deterministic — Blockchains
Deterministic — PBFT ensures
using PoW can experience
Transaction that all nodes agree on the exact
"reorganizations," where the order
Ordering order of transactions, and once
of transactions may temporarily
committed, the order is fixed.
change if a longer chain is found.
Leader-based — A designated
No leader — Miners are chosen
leader (primary) proposes new
Leader Selection based on computational power, not
blocks. The leader rotates
in a fixed leadership role.
periodically to ensure fairness.
Practical Byzantine Fault
Function Proof of Work (PoW)
Tolerance (PBFT)
Low latency — PBFT can achieve
High latency — Transaction
Latency faster consensus and transaction
confirmations can take several
(Transaction finality compared to PoW.
minutes (Bitcoin) or longer
Confirmation However, it still depends on the
depending on network conditions
Time) number of nodes and network
and block size.
delays.
Permissionless — No need for Permissioned — Requires known
Network participants to trust one another; participants (validators). Typically
Requirements anyone can join the network and used in enterprise settings or
start mining. private networks.
Possible — A chain reorganization
can potentially "undo" recent Not possible — Once a
Transaction
transactions, although it’s highly transaction is committed in PBFT,
Reversal
unlikely with sufficient it is final and cannot be reversed.
confirmations.