UNIT 2: BLOCKCHAIN TECHNOLOGY - SHORT NOTES
1.0 FOUNDATIONAL CONCEPTS & DATA STRUCTURES
1.1 Cryptographic Hash Functions
A cryptographic hash function is a one-way mathematical function that maps input data of any size to a fixed-size output (hash/digest).
Core Properties:
| Property | Description | Importance in Blockchain |
|---|---|---|
| Deterministic | Same input → same hash, always. | Ensures block/tx integrity verification. |
| Pre-image Resistance | Hard to find input x given hash h. |
Protects against reversing hashes to find original data. |
| Second Pre-image Resistance | Hard to find x2 ≠ x1 such that hash(x1)=hash(x2). |
Prevents substitution attacks on existing data. |
| Collision Resistance | Hard to find any two inputs with same hash. | Fundamental for Merkle tree security & digital signatures. |
| Avalanche Effect | Tiny change in input → ~50% change in output bits. | Makes tampering easily detectable. |
| Pseudorandomness | Output appears random. | Prevents pattern prediction. |
Role in Blockchain:
-
Linking Blocks:
Previous Block Hashin header uses hash of prior block's header, creating an immutable chain. -
Data Integrity: Any change in block body (transactions) changes its Merkle root and thus the block hash.
-
Digital Signatures: Hashes of messages are signed, not the entire message, for efficiency.
[!TIP] Exam Focus: Be ready to define each property and give a blockchain-specific example (e.g., "Collision resistance prevents an attacker from creating a different block with the same hash as a valid one").
1.2 Merkle Trees (Hash Trees)
A Merkle Tree is a binary tree where every non-leaf node is the hash of its two child nodes.
Structure & Construction:
-
Leaf Nodes: Hashes of individual transactions (or data chunks).
-
Parent Nodes: Concatenate & hash child pairs:
Hash(Hash(Tx1) + Hash(Tx2)). -
Root Hash (Merkle Root): Single hash at the top, stored in the block header. Represents all transactions in the block.
Root = H(H(A)+H(B))
/ \
H(H(A)+H(B)) H(H(C)+H(D))
/ \ / \
H(A) H(B) H(C) H(D)
/ / / /
TxA TxB TxC TxD (Leaf Nodes)
Importance in Blockchain:
-
Efficient Verification (Merkle Proofs): A light client (SPV) can verify a transaction is in a block by receiving only the transaction hash and a few sibling hashes (~log₂N), not the entire block.
-
Data Integrity: Any change to a single transaction changes its leaf hash, propagating up to alter the root hash. Root in header would not match.
-
Scalability: Enables lightweight clients and simplifies block propagation (only need to send new transactions, not entire block history).
[!TIP] Common Pitfall: Merkle Trees are for efficient verification, not for storing the full transaction list. The block body still stores all transactions.
1.3 Block Structure
A block is a container for a set of transactions, cryptographically linked to its predecessor.
Components:
| Component | Sub-components | Purpose |
|---|---|---|
| Block Header (80 bytes) | 1. Version: Block version number.<br>2. Previous Block Hash: 256-bit hash of previous block's header.<br>3. Merkle Root: 256-bit hash of all transactions in this block.<br>4. Timestamp: Block creation time (seconds since epoch).<br>5. Difficulty Target: Proof-of-Work difficulty threshold.<br>6. Nonce: 32-bit number miners vary to solve PoW. | Maintains chain linkage (Prev Hash), data integrity (Merkle Root), and consensus (Difficulty, Nonce). |
| Block Body | 1. Transaction Counter: VarInt encoding number of txs.<br>2. Transactions: List of all transaction data. | Contains the actual ledger entries. |
Purpose: The header components collectively ensure immutability (via hashing), consensus (via PoW fields), and integrity (via Merkle root).
[!DIAGRAM: CANVAS] Draw this: A box labeled "Block". Inside, a top section "Block Header" with 6 labeled fields (Version, Prev Hash, Merkle Root, Timestamp, Bits/Difficulty, Nonce). Below, a section "Block Body" with "Tx Count" and a list of "Transaction 1, Transaction 2,...".
2.0 CONSENSUS MECHANISMS
2.1 Introduction to Consensus
Consensus is the mechanism by which all nodes in a distributed network agree on a single, consistent version of the ledger (the "truth").
Critical Need: Solves the Byzantine Generals' Problem—how to achieve agreement in a trustless, decentralized system with potentially faulty/malicious nodes.
Primary Goals:
-
Agreement: All honest nodes agree on the same block sequence.
-
Liveness: The network continues to produce new blocks (transactions get confirmed).
-
Safety: Once a block is confirmed, it cannot be reversed (finality).
2.2 Proof-of-Work (PoW)
Mechanism: Miners compete to find a nonce such that the block header hash is below a difficulty target.
$$H(\text{Version} \parallel \text{PrevHash} \parallel \text{MerkleRoot} \parallel \text{Timestamp} \parallel \text{Bits} \parallel \text{Nonce}) < \text{Target}$$
-
Cryptographic Puzzle: Brute-force search for a valid nonce.
-
Hashing Difficulty: Target is adjusted periodically (e.g., every 2016 blocks in Bitcoin) to maintain average block time (~10 mins).
-
Winner: First miner to find a valid nonce broadcasts the block. Others verify the PoW and the transactions.
Bitcoin's Implementation:
-
Block Reward: New BTC + transaction fees. This incentivizes mining.
-
Transaction Selection: Miners pick transactions from mempool, prioritizing those with higher fees.
-
Difficulty Adjustment: Every 2016 blocks, recalculate target based on actual time taken vs. expected (2 weeks).
Attacks & Challenges:
| Attack/Challenge | Description |
|---|---|
| 51% Attack | Entity controls >50% hash power → can double-spend, censor txs, but not steal funds. Costly to sustain. |
| Monopoly Problem | Economies of scale lead to mining centralization in large pools/farms. |
| Selfish Mining | Miners withhold found blocks to gain unfair advantage, reducing network efficiency. |
| Energy Consumption | Massive computational power (electricity) is wasted on PoW. |
Historical Context: HashCash (Adam Back, 1997) was an early PoW system to combat email spam. Bitcoin adapted it for consensus.
[!TIP] Exam Focus: Be prepared to write the PoW equation and explain the difficulty adjustment formula conceptually.
2.3 Alternative Consensus for Public/Permissionless: Proof-of-Elapsed-Time (PoET)
-
Mechanism: Uses Intel SGX (Software Guard Extensions) trusted execution environment.
-
Process:
-
Each validator randomly waits for a randomly chosen time (like a lottery timer) within an SGX enclave.
-
The validator whose timer expires first is the leader and proposes the next block.
-
Others verify the wait time was legitimately generated within SGX.
-
-
Advantages: Low energy consumption (no hashing race), fair leader selection.
-
Disadvantages: Requires trusted hardware (Intel SGX), potential SGX vulnerability exploits.
-
Use Case: Hyperledger Sawtooth.
2.4 Consensus for Permissioned Blockchains
Byzantine Fault Tolerance (BFT) & PBFT
-
Goal: Tolerate up to
fByzantine (malicious/faulty) nodes in a network of3f+1total nodes. -
Lamport-Shostak-Pease (BFT) Algorithm: The foundational theoretical algorithm. PBFT is its practical implementation.
-
PBFT Operation Phases (for a single consensus instance):
-
Pre-prepare: Leader assigns a sequence number to client request and broadcasts
<<PRE-PREPARE, view, seq-no, digest>>. -
Prepare: Each node broadcasts
<<PREPARE, view, seq-no, digest, node-id>>if request is valid. A node collects2fmatching PREPARE messages. -
Commit: Node broadcasts
<<COMMIT, view, seq-no, digest, node-id>>. Collects2f+1matching COMMIT messages → committed. -
Reply: Execute request and send reply to client. Client needs
f+1matching replies.
-
-
Use Case: Original Hyperledger Fabric (pre-1.0).
Raft Consensus Algorithm
-
Type: Crash Fault Tolerant (CFT), not BFT. Assumes nodes only fail/crash, not act maliciously.
-
Mechanism: Leader-based log replication.
-
Key Roles & Terms:
-
Leader: Handles all client requests, appends to log, replicates to followers.
-
Follower: Passive, receives log entries from leader.
-
Candidate: Used during elections.
-
Term: Arbitrary increasing index for leader elections (like "epoch").
-
Log: Ordered list of commands/transactions.
-
Commit Index: Highest log index known to be committed.
-
-
Process:
-
Election: If follower doesn't hear from leader (election timeout), becomes candidate, votes for self, requests votes. Wins if gets majority → becomes leader.
-
Log Replication: Leader appends new entry to its log, sends
AppendEntriesRPC to followers. Once replicated on majority, entry is committed.
-
-
Comparison with PBFT:
| Feature | PBFT (BFT) | Raft (CFT) | | :--- | :--- | :--- | | Fault Model | Byzantine (malicious) | Crash-only | | Complexity | High (O(n²) messages) | Low (O(n) messages) | | Performance | Lower throughput, higher latency | Higher throughput, lower latency | | Use Case | High-security consortiums | General permissioned enterprise |
[!TIP] Exam Focus: Know the 3f+1 rule for BFT. Be able to contrast Raft's leader-based simplicity with PBFT's multi-phase voting.
2.5 Bitcoin-Specific Consensus & Networking
Bitcoin P2P Network Architecture:
-
Node Discovery: Uses DNS seeds, hardcoded addresses, and
addrmessage propagation. -
Message Propagation: Key messages:
inv(inventory),getdata(request data),tx(transaction),block(block). -
Flooding Protocol: Nodes advertise new txs/blocks via
inv, peers request withgetdata.
Transaction & Block Propagation Workflow:
-
User creates/signs transaction → broadcasts to connected peers (
txmessage). -
Peers validate (scripts, fees, no double-spend) → add to mempool → forward to other peers (after
inv/getdata). -
Miner assembles block from mempool → solves PoW → broadcasts new block (
blockmessage). -
Nodes validate block (PoW, txs, prev hash) → add to chain → forward to peers.
Block Mining Process:
-
Transaction Selection: Pick txs from mempool, prioritize high-fee.
-
Fee Calculation: Sum of
(input value - output value)for all txs. -
Block Assembly: Create coinbase tx (block reward), build Merkle root, fill header.
-
PoW Computation: Iterate nonce (and extra nonce in coinbase) to find header hash < target.
-
Block Propagation: Broadcast winning block to network.
Types of Mining:
-
Solo Mining: Individual miner. Very low probability of finding block; high variance in rewards.
-
Pool Mining: Miners contribute hash power to a pool. Pool operator finds block, rewards split proportionally. Reduces variance.
[!TIP] Common Pitfall: Miners don't "verify transactions" in the sense of executing scripts—they include valid transactions from their mempool. Full nodes do the full validation upon block receipt.
3.0 SMART CONTRACTS
3.1 Definition & Essential Characteristics
A smart contract is self-executing code stored on a blockchain that automatically enforces the terms of an agreement when predefined conditions are met.
Essential Characteristics:
-
Self-executing: Runs automatically without intermediary upon trigger (e.g., tx receipt).
-
Immutable: Once deployed, code cannot be changed (unless upgrade mechanism built-in).
-
Deterministic: Same input (state + tx) → same output, on any node.
-
Trigger-based: Executed in response to transactions or events.
-
Stateful: Can store and modify state on the blockchain.
Development Lifecycle:
-
Writing: Code in high-level language (Solidity, Go).
-
Deployment: Compiled to bytecode, deployed via a special transaction (creates contract address).
-
Execution: Users interact by sending transactions to the contract's address with function call data.
-
Termination: Contract can be "killed" only if code includes a selfdestruct function (Ethereum) or is upgraded (Fabric).
3.2 Bitcoin Script (Stack-based, Non-Turing Complete)
-
Purpose: Simple locking/unlocking script mechanism for transaction validation. Not for general computation.
-
Stack-based: Operates on a LIFO stack. Opcodes push/pop values.
-
Non-Turing Complete: No loops, bounded execution (max 201 opcodes), stateless. Prevents infinite loops/DOS.
-
Script Types:
-
Pay-to-Public-Key-Hash (P2PKH): Standard.
scriptSig(signature+pubkey) must satisfyscriptPubKey(hash of pubkey). -
Pay-to-Script-Hash (P2SH): Allows complex scripts.
scriptPubKeycontains hash of redeem script.scriptSigprovides redeem script + data. -
Multi-signature (Multisig): Requires
Msignatures fromNpublic keys (e.g., 2-of-3).
-
-
Limitations: No state between txs, no loops, limited opcodes → cannot express complex logic.
3.3 Ethereum Smart Contracts (Turing Complete)
-
High-level Languages: Solidity (JS-like), Vyper (Python-like, security-focused).
-
Ethereum Virtual Machine (EVM):
-
Execution Environment: Sandboxed, deterministic runtime on every node.
-
Gas Model: Each EVM operation costs gas. Prevents infinite loops/DOS. User pays gas fee (
gasUsed * gasPrice). -
State Transitions: Contract execution changes global state (account balances, storage).
-
-
Process:
-
Write Solidity code.
-
Compile to EVM bytecode (and ABI).
-
Deploy: Send transaction with bytecode as data → creates contract address.
-
Interact: Send transaction to contract address with function selector + args. EVM executes on all nodes.
-
3.4 Hyperledger Fabric Smart Contracts (Chaincode)
-
Writing Chaincode:
-
Languages: Go (most common), Java, JavaScript (Node.js).
-
Endorsement Policies: Define which peers must execute/endorse a tx for it to be valid (e.g., "Org1's peer AND Org2's peer").
-
Access Control: Uses Fabric identities (MSP) to control who can invoke which functions.
-
-
Deployment & Lifecycle:
-
Install: Chaincode package installed on endorsing peers.
-
Instantiate/Upgrade: On a channel, define initial policy, endorsement policy, and init args. (Fabric v2.x uses "commit" after approval).
-
-
Invocation Flow:
Client App → Endorsing Peers (execute, simulate) → Ordering Service (order txs) → Committing Peers (validate, commit)
[!TIP] Key Difference: Ethereum contracts run on all nodes. Fabric chaincode runs only on endorsing peers for simulation; all peers commit the result. This enables privacy (data stays on endorsing peers).
4.0 BLOCKCHAIN TAXONOMY & PLATFORMS
4.1 Public vs. Private vs. Permissioned Blockchains
| Aspect | Public (Permissionless) | Private/Permissioned |
|---|---|---|
| Access | Anyone can read/write/validate. | Known, authorized participants only. |
| Identity | Pseudonymous. | Known, verified identities (MSP, certificates). |
| Consensus | Sybil-resistant (PoW, PoS). | Voting-based (PBFT, Raft, PoET). |
| Throughput | Low (Bitcoin: ~7 tps, Ethereum: ~15-30 tps). | High (100s-1000s tps). |
| Finality | Probabilistic (Bitcoin: ~6 blocks). | Immediate/Deterministic (BFT/Raft). |
| Trust Model | Trustless (no trust in nodes). | Trust in known participants. |
| Examples | Bitcoin, Ethereum, Litecoin. | Hyperledger Fabric, R3 Corda, Ripple (quasi). |
| Use Cases | Censorship-resistant apps, cryptocurrencies. | Enterprise B2B, supply chain, inter-bank. |
4.2 Enterprise Blockchain Platforms
Hyperledger Fabric
-
Architecture:
-
Peers: Host ledgers & chaincode. Endorsing peers execute chaincode.
-
Ordering Service: Consensus on tx order (Raft, Kafka, Solo). Does not execute chaincode.
-
Channels: Private subnets. Ledger data isolated per channel.
-
Membership Service Provider (MSP): Manages identities (X.509 certs) for orgs/users.
-
-
Key Concepts:
-
Ledger: Comprises World State (current DB of assets) & Blockchain (immutable log of all txs).
-
Chaincode: Smart contract. Runs in Docker container.
-
Endorsement Policy: Which peers must endorse a tx (e.g.,
AND('Org1.peer', 'Org2.peer')). -
Private Data Collections: Sensitive data shared only among specific orgs, not on all peers.
-
-
Use Cases: Supply chain traceability (food, diamonds), trade finance, healthcare records.
R3 Corda
-
Design Philosophy: Not a blockchain. A distributed ledger with privacy-by-design. No global broadcast of all data.
-
Key Concepts:
-
States: Immutable facts (e.g.,
CashState,IOUState). Represent current data. -
Contracts: Define legal rules for state evolution. Code + legal prose.
-
Notaries: Provide uniqueness consensus (prevent double-spend). Can be validating (see all data) or non-validating.
-
Flows: Encapsulate business logic for node communication (e.g.,
InitiatorFlow,ResponderFlow). -
Corda Network: Network of nodes (legal entities) with point-to-point communication.
-
-
Use Cases: Inter-bank settlements, trade finance, syndicated loans.
Ripple (XRP Ledger)
-
Consensus Protocol: Ripple Protocol Consensus Algorithm (RPCA).
-
Unique Node List (UNL): Each node has a list of trusted validators it listens to.
-
Process: Validators propose candidate sets, iterate until 80%+ agreement on a ledger version.
-
No Mining: All 100B XRP pre-mined. Validators are known entities (banks, payment providers).
-
-
Focus: Cross-border payments & digital assets. Gateways issue IOUs (BTC, USD, etc.). XRP used as bridge currency for liquidity.
-
Native Crypto: XRP (used for anti-spam transaction fee, destroyed on each tx).
5.0 APPLICATIONS & USE CASES
5.1 Financial Services
Cross-Border Payments
-
Traditional: SWIFT, correspondent banking → slow (3-5 days), expensive (high fees), opaque.
-
Blockchain (Ripple):
-
Disintermediation: Direct transfer between institutions via RippleNet.
-
Speed: Settlements in seconds.
-
Cost: Lower fees (using XRP as bridge asset reduces nostro accounts).
-
Transparency: Real-time tracking.
-
Supply Chain Finance
-
Traditional: Manual invoices, delays in payments, fraud risk (duplicate financing).
-
Blockchain Improvement:
-
Single Source of Truth: Immutable record of goods movement (IoT + blockchain).
-
Automated Payments: Smart contracts trigger payment upon verified delivery (via IoT sensor data or document hash).
-
Invoice Financing: Banks can verify invoice authenticity on-chain → faster credit, lower risk.
-
Reduced Fraud: Prevents duplicate invoice submission.
-
Mortgages
-
Traditional Process: Paper-heavy, multiple intermediaries (lenders, title companies, escrow), slow (30-60 days), fraud risk.
-
Blockchain Mortgage:
-
Digital Identity & KYC: Reusable, verifiable credentials.
-
Smart Contract Escrow: Automatically release funds to seller upon title transfer.
-
Automated Title Transfer: Title as a digital asset on-chain; transfer is atomic with payment.
-
Reduced Fraud: Immutable history of ownership, liens.
-
Faster Closing: Automated workflows reduce manual verification.
-
5.2 Identity Management
-
Self-Sovereign Identity (SSI): User owns and controls their identity data, not a central authority.
-
Blockchain Role:
-
Decentralized Identifiers (DIDs): Unique IDs anchored on-chain, pointing to off-chain data.
-
Verifiable Credentials (VCs): Issuer signs credential (e.g., "Degree from University X"). User presents VC; verifier checks signature + issuer's DID on-chain.
-
Immutable Audit Trail: All credential issuances/revocations logged.
-
-
Benefits: Privacy (minimal disclosure), Security (no central DB hack), User control, Reduced identity theft.
5.3 Industry-Specific Implementations (Hyperledger Fabric)
-
Healthcare: Secure, permissioned sharing of patient records among hospitals, insurers, labs. Patient controls access.
-
Diamond Tracking: Track diamond from mine to retailer (e.g., Everledger). Record characteristics, ownership history to prevent conflict diamonds.
-
Food Safety: Trace produce from farm to store (e.g., IBM Food Trust). Rapid source identification during contamination outbreaks.
[!TIP] Exam Focus: For use cases, structure answer as: Problem in Traditional System → Blockchain Solution (which feature?) → Benefits. E.g., "Cross-border: Problem is slow/expensive intermediaries → Solution: Ripple's direct settlement with XRP bridge → Benefits: Speed, cost reduction."
END OF UNIT 2 NOTES