UNIT 5: BLOCKCHAIN TECHNOLOGY - EXAM-FOCUSED NOTES
I. FOUNDATIONAL CONCEPTS & DATA STRUCTURES
Block Structure & Composition
A blockchain block is a container for data. Its structure is standardized (e.g., in Bitcoin).
| Field | Description |
|---|---|
| Block Header | 80-byte metadata containing: |
| • Version | Block version number. |
| • Previous Block Hash | 256-bit hash of the previous block's header (creates the "chain"). |
| • Merkle Root | 256-bit hash of the root of the Merkle tree of all transactions in the block. |
| • Timestamp | Block creation time (in seconds). |
| • Difficulty Target | The proof-of-work difficulty threshold for this block. |
| • Nonce | "Number used once" – a 32-bit field miners iterate to find a valid block hash. |
| Transaction Counter | Number of transactions in the block (varint). |
| Transaction List | The actual list of transactions (each transaction is a data structure). |
| Block Size Limit | Maximum allowed size (e.g., Bitcoin's 1-4 MB weight units). Ensures network propagation and validation speed. |
[!TIP] Exam Focus: Be prepared to draw and label the block structure. The Nonce and Merkle Root are critical for linking PoW and transaction integrity.
Cryptographic Hash Functions
A deterministic function that maps input data of any size to a fixed-size output (hash/digest).
Core Properties (CRITICAL FOR EXAMS):
-
Deterministic: Same input → same output, always.
-
Quick Computation: Hash can be computed swiftly for any input.
-
Pre-image Resistance: Given a hash
h, it is computationally infeasible to find any inputxsuch thathash(x) = h. -
Avalanche Effect: A tiny change in input (e.g., 1 bit) produces a drastically different hash (≈50% bits change).
-
Collision Resistance: Computationally infeasible to find two different inputs
xandysuch thathash(x) = hash(y).
Common Algorithms: SHA-256 (Bitcoin), Keccak-256 (Ethereum pre-Byzantium, SHA-3 family).
[!TIP] Common Pitfall: Do not confuse pre-image resistance (finding input from hash) with collision resistance (finding two inputs with same hash). Both are essential for blockchain security.
Merkle Trees (Hash Trees)
A binary tree structure where leaves are hashes of data blocks (transactions), and each non-leaf node is the hash of its two child nodes.
Construction Process:
-
Hash each transaction (e.g.,
H(Tx1),H(Tx2)...). These are leaf nodes. -
If odd number of leaves, duplicate the last one.
-
Pairwise concatenate and hash:
H(H(Tx1) || H(Tx2)),H(H(Tx3) || H(Tx4))... These become parent nodes. -
Repeat step 3 recursively until a single hash remains: the Merkle Root.
Importance in Blockchain (KEY EXAM TOPIC):
-
Efficient Verification (Merkle Proofs): A light client can verify a transaction's inclusion in a block by receiving only a small subset of hashes (the proof path) instead of the entire block. This is O(log n) data vs. O(n).
-
Data Integrity: Any alteration to a transaction changes its hash, which propagates up, changing the Merkle Root. Since the root is in the block header, it would break the block's hash and be detected.
-
Scalability: Enables Simplified Payment Verification (SPV) in Bitcoin.
[!TIP] Exam Question: "Explain why Merkle Trees are important for Blockchain." Structure your answer around Integrity, Efficiency (SPV), and Scalability. Use a small 4-transaction example in your explanation.
II. CONSENSUS MECHANISMS
The Consensus Problem & Goals
In a distributed, trustless network, achieve agreement on a single version of the truth (the ledger).
-
Agreement: All honest nodes agree on the same sequence of blocks.
-
Validity: All agreed-upon blocks/transactions are valid according to network rules.
-
Liveness: The network continues to make progress (new blocks are produced).
-
Fault Tolerance: The system can tolerate a certain number of faulty/Byzantine nodes.
Permissionless / Public Blockchain Consensus
Proof of Work (PoW)
Mechanism:
-
Miners collect pending transactions from the mempool.
-
They assemble a candidate block (with previous hash, merkle root, etc.).
-
They repeatedly change the Nonce (and sometimes extra nonce in coinbase) and compute the block's double SHA-256 hash:
H(H(Block Header)). -
The goal is to find a hash below the Difficulty Target:
H(H(Header)) < Target. -
Finding this "winning" nonce is the puzzle. It requires brute-force computation (work).
-
The first miner to find a valid nonce broadcasts the block. Others verify the PoW (quickly) and the transactions, then extend the chain.
Attacks on PoW:
-
51% Attack: If an entity controls >50% of the total network hash power, they can:
-
Double-spend their own coins (by reorganizing the chain).
-
Censor transactions.
-
Cannot steal others' funds or break cryptographic signatures.
-
-
Selfish Mining: A miner withholds a found block instead of broadcasting it, giving them a head start on the next block, increasing their revenue proportionally.
-
Block Withholding: A mining pool participant finds a block but does not submit it to the pool, harming the pool's revenue.
Monopoly Problem / Mining Centralization: Economies of scale in mining hardware (ASICs) and cheap electricity lead to centralized mining pools, contradicting the decentralization ethos.
HashCash & Bitcoin PoW: HashCash (Adam Back, 1997) was an anti-spam proof-of-work. Bitcoin adapted it by making the target dynamic (difficulty adjustment every 2016 blocks) to maintain ~10-minute block time.
[!TIP] Exam Focus: Be ready to explain the PoW mining process step-by-step and list & explain 2-3 attacks. The Monopoly Problem is a direct past question.
Permissioned / Private/Consortium Blockchain Consensus
Raft Consensus Algorithm
A crash-fault-tolerant (CFT) leader-based consensus protocol.
-
Leader Election: Nodes start as followers. If a follower receives no heartbeat from leader within timeout, it becomes a candidate, votes for itself, and requests votes. The candidate with majority votes becomes leader.
-
Log Replication: Leader receives client requests, appends to its log, and replicates to followers via
AppendEntriesRPCs. Once replicated on a majority, the entry is committed and applied to the state machine. -
Safety & Liveness: Guarantees that if a leader is elected, its log contains all committed entries. Provides liveness as long as a majority of nodes are operational and can communicate.
-
Use Case: Hyperledger Fabric (default ordering service - Solo & Raft).
Practical Byzantine Fault Tolerance (PBFT)
The Lamport-Shostak-Pease (PBFT) Algorithm. Tolerates Byzantine faults (arbitrary/malicious behavior).
-
Fault Tolerance: Works if
n >= 3t + 1, wheren= total nodes,t= max faulty/Byzantine nodes. Can tolerate up tot < n/3bad nodes. -
Three-Phase Protocol for Each Request:
-
Pre-Prepare: Leader assigns a sequence number
nto requestmand broadcasts<<PRE-PREPARE, n, m>>. -
Prepare: Each node
ithat receives a valid pre-prepare broadcasts<<PREPARE, n, d, i>>(wheredis message digest). A node enters prepared state when it receives2t+1matching prepare messages (including its own). -
Commit: Nodes broadcast
<<COMMIT, n, d, i>>. A node enters committed state on2t+1matching commit messages and then executes the request.
-
-
Complexity: Communication overhead is
O(n²).
Proof of Elapsed Time (PoET)
-
Mechanism: Uses a Trusted Execution Environment (TEE) like Intel SGX.
-
Each validator requests a random wait time from the TEE.
-
The TEE (secretly) selects a random wait time and returns a signed attestation.
-
The validator with the shortest randomly assigned wait time becomes the leader for the next block.
-
The leader assembles and proposes the block. Others verify the TEE attestation and block.
-
-
Advantages: Extremely energy-efficient (no computational race). Low-cost validation.
-
Requirements: Relies on hardware security (Intel SGX). Centralization risk around TEE manufacturers.
-
Use Case: Hyperledger Sawtooth (original implementation).
[!TIP] Exam Focus: You must be able to contrast Raft (CFT, leader-based) vs. PBFT (BFT, 3-phase, O(n²)) vs. PoET (TEE-based, lottery). Know the
t < n/3rule for PBFT.
III. BITCOIN NETWORK & TRANSACTION PROCESSING
Bitcoin P2P Network Architecture
-
Decentralized, unstructured gossip network.
-
Node Types:
-
Full Nodes: Validate all transactions and blocks, store full blockchain (~500GB). Enforce consensus rules.
-
Light/SPV Clients: Store only block headers, request Merkle proofs for transaction validity.
-
Mining Nodes: Full nodes that also run mining software.
-
-
Discovery: Uses DNS seeds, hardcoded IP addresses, and address relay from peers.
-
Message Propagation: Uses a "flooding" protocol. Messages (tx, block) are validated then relayed to all connected peers (except the source). Includes
inv(inventory),getdata,tx,blockmessages.
Transaction Lifecycle in Bitcoin
-
Creation: Sender constructs a transaction: inputs (UTXOs to spend), outputs (amounts + scriptPubKey), locktime.
-
Signing: Sender uses ECDSA (Elliptic Curve Digital Signature Algorithm) with their private key to sign the transaction hash. This creates the
scriptSigfor each input. -
Broadcast: Signed transaction is sent to connected nodes.
-
Validation (by nodes): Checks syntax, inputs are unspent (UTXO set), signatures valid, output sums ≤ input sums, no double-spend in mempool.
-
Mempool: Valid but unconfirmed transactions reside here.
-
Inclusion in Block: A miner selects transactions from mempool (prioritizing by fee), assembles a candidate block, and includes them via the mining process.
The Double-Spending Problem & Prevention
-
Problem: A malicious user spends the same UTXO twice, sending one transaction to a merchant and another to themselves (or different merchant).
-
Prevention:
-
Consensus & Longest Chain Rule: Miners include transactions in blocks. If two conflicting transactions (double-spend) are broadcast, the network will eventually accept only the one that gets buried under the most cumulative PoW (the longest valid chain). The other becomes an "orphan" and its outputs become spendable again.
-
Transaction Confirmations: A merchant should wait for a certain number of confirmations (blocks mined on top of the block containing their transaction). Each confirmation exponentially reduces the probability of a chain reorganization that reverses the transaction. 6 confirmations is a common heuristic for high value.
-
Bitcoin Script (Smart Contract Language)
-
Stack-based, Forth-like, Non-Turing Complete (no loops, bounded execution → prevents DoS).
-
Execution:
scriptSig(unlocking script) +scriptPubKey(locking script) are concatenated and executed. If final stack state isTRUE, transaction is valid. -
Common Script Types:
-
P2PK (Pay-to-Public-Key):
scriptPubKey: <PubKey> OP_CHECKSIG. Directly locks to a public key. (Rare now). -
P2PKH (Pay-to-Public-Key-Hash):
scriptPubKey: OP_DUP OP_HASH160 <PubKeyHash> OP_EQUALVERIFY OP_CHECKSIG. Locks to a hash of a public key (standard address1...).scriptSigprovides signature + public key. -
P2SH (Pay-to-Script-Hash):
scriptPubKey: OP_HASH160 <ScriptHash> OP_EQUAL. Allows complex redeem scripts to be hashed.scriptSigprovides{RedeemScript, data...}. Enables multi-sig and flexible contracts. -
Multi-Sig (P2MS):
scriptPubKey: <M> <PubKey1> <PubKey2> ... <PubKeyN> OP_CHECKMULTISIG. RequiresMofNsignatures.
-
-
Locktime & CheckSequenceVerify (CSV): Allows time-locked transactions (not valid until a certain block height or timestamp).
Block Mining Process
-
Transaction Selection: Miner selects transactions from mempool, usually by fee-per-byte. Creates a coinbase transaction (minting new BTC + fees) as first transaction.
-
Block Assembly: Constructs block header (with Merkle root of selected txs, previous hash, timestamp, difficulty, version). Sets nonce to 0.
-
Nonce Iteration & Hash Calculation: Repeatedly increments nonce, computes
SHA256(SHA256(BlockHeader)). Checks if result <Target. -
Block Propagation: Upon finding a valid nonce, miner broadcasts the full block to the network.
-
Validation & Chain Extension: Other nodes verify PoW, transactions, and block structure. If valid, they add it to their local chain and start mining the next block on this new tip.
Types of Mining:
-
Solo Mining: Miner works alone. Receives full block reward if they find a block. Probability is proportional to hash rate. High variance.
-
Pool Mining: Miners combine hash power in a pool. Pool operator assembles blocks. Miners work on a share (a lower-difficulty PoW). When the pool finds a block, reward is split among miners proportional to shares submitted. Reduces variance, provides steady income.
[!TIP] Exam Focus: You must explain the mining process steps and differentiate Solo vs. Pool Mining (including share concept and reward distribution).
IV. SMART CONTRACTS
Definition & Essential Characteristics
A smart contract is self-executing, immutable code deployed on a blockchain that automatically enforces the rules and penalties of an agreement when predefined conditions are met.
Essential Characteristics:
-
Self-Executing: Runs automatically without an intermediary upon trigger (e.g., transaction call).
-
Immutable: Once deployed, its code cannot be changed (unless explicitly programmed with upgrade patterns).
-
Deterministic: Given the same input state and transaction, it always produces the same output state. Critical for network consensus.
-
Trustless Execution: Parties do not need to trust each other; they trust the code and the decentralized network.
-
"If-Then" Logic: Encodes business logic:
IF (condition) THEN (action).
Platform-Specific Implementations
Bitcoin Script (See Section III)
- Limited, transactional. Primarily for securing fund transfers (P2PKH, P2SH, multi-sig). Not Turing-complete. No state storage between transactions beyond UTXOs.
Ethereum Smart Contracts
-
High-Level Languages: Solidity (most popular, JS-like), Vyper (security-focused, Python-like).
-
Ethereum Virtual Machine (EVM): A global, sandboxed, deterministic virtual machine that executes contract bytecode on every Ethereum node.
-
Gas: Unit of computation. Every EVM operation costs gas. Prevents infinite loops (DoS). Users pay
gasPrice * gasUsedin ETH. -
Deployment & Interaction: Contract code is compiled to bytecode. Deployment is a special transaction with
to: null. Interaction is via transactions calling specific functions (changing state) or calls (read-only, no gas cost for caller).
Hyperledger Fabric Smart Contracts (Chaincode)
-
Writing Chaincode: Implement the
Chaincodeinterface in Go, Java, or JavaScript (Node.js). -
Key Interface Methods:
-
Init(): Called once during instantiation/upgrade. For initial setup. -
Invoke(): Called for every transaction proposal. Parses function name & args, dispatches to appropriate business logic function.
-
-
Process Flow (CRITICAL):
-
Proposal: Client application sends a transaction proposal (function + args) to endorsing peers.
-
Endorsement: Endorsing peers simulate the transaction (using their copy of the world state), execute chaincode, and produce a read-write set (keys read, new values). They sign the proposal response (endorsement).
-
Ordering: Client submits endorsed transaction to the ordering service (Raft, Kafka, etc.). Ordering service orders transactions into blocks and delivers them to all committing peers.
-
Validation & Commit: Committing peers validate the transaction (check endorsements meet policy, read-set unchanged). If valid, they atomically update the world state and append the transaction to the blockchain ledger.
-
[!TIP] Exam Focus: Contrast Bitcoin Script (simple, UTXO-based) vs. Ethereum (account-based, Turing-complete, gas) vs. Fabric (executable logic, channel-based, endorsement policy). Be able to describe the Fabric execution flow (Proposal → Endorsement → Ordering → Validation).
V. BLOCKCHAIN TYPES & ARCHITECTURES
| Feature | Public Blockchain | Private Blockchain | Consortium Blockchain |
|---|---|---|---|
| Access Control | Permissionless (anyone). | Permissioned (single entity). | Permissioned (pre-selected group). |
| Consensus | PoW, PoS (resource-intensive). | Often centralized/trusted (Raft). | BFT variants (PBFT, Raft). |
| Performance | Low TPS, high latency. | High TPS, low latency. | Moderate-High TPS. |
| Use Case | Cryptocurrencies, public DAOs. | Internal enterprise DB replacement. | Industry consortia (finance, supply chain). |
| Trust Model | Trustless (cryptography + game theory). | Trusted (known operator). | Semi-trusted (known members). |
| Examples | Bitcoin, Ethereum. | Single-company chain. | Hyperledger Fabric, R3 Corda. |
Design Issues for Permissioned Blockchains
-
Identity Management & MSP: Must have a robust Membership Service Provider (MSP) to issue, validate, and manage X.509 certificates for all participants. Foundation for access control.
-
Privacy & Confidentiality: Need to hide transaction details from non-participants. Solutions: Channels (Fabric - sub-networks), Private Data Collections (Fabric - off-ledger data with hash on-ledger), zero-knowledge proofs.
-
Scalability & Throughput: Can optimize by choosing efficient consensus (Raft, PBFT), using channels for parallelism, and tuning block size/frequency.
-
Governance & Policy Enforcement: Must define clear rules for: membership changes, smart contract upgrades, endorsement policies (which peers must sign), and dispute resolution. Often encoded in channel configuration.
VI. ENTERPRISE BLOCKCHAIN PLATFORMS (DEEP DIVE)
Hyperledger Fabric
-
Architecture (Modular & Channel-Based):
-
Peers: Host chaincode & ledger. Types: Endorsing Peers (simulate tx), Committing Peers (validate/commit). Can be both.
-
Ordering Service: Orders transactions into blocks (consensus). Does not validate transactions. Implements Raft, Kafka, or Solo.
-
Channels: Private subnets of communication between specific peers and orderers. Ledger data is isolated per channel.
-
Membership Service: Manages identities via MSP.
-
Chaincode: Smart contracts.
-
-
Key Components:
-
Ledger: Comprises World State (current value of all keys, in LevelDB/CouchDB) and Blockchain (immutable log of all transactions).
-
Private Data Collections: Allows subsets of organizations to store data privately (off-ledger), with only a hash on the shared ledger for integrity.
-
Endorsement Policies: Defines which peers (by org) must endorse a transaction for it to be valid (e.g., "Org1 AND Org2", "Org1 OR Org2").
-
-
Identities & Policies: Based on X.509 certificates issued by a Certificate Authority (CA) under an MSP. Attribute-Based Access Control (ABAC) can be used for fine-grained chaincode function access.
-
Industry Use Cases:
-
Supply Chain Traceability: Track provenance of goods (food, pharmaceuticals) across multiple orgs with privacy (e.g., only relevant parties see price).
-
Trade Finance: Digitize Letters of Credit, automate payments upon shipment verification.
-
Healthcare Records: Share patient data across hospitals/insurers with patient consent, maintaining audit trail.
-
Ripple (XRP Ledger)
-
Purpose: High-speed, low-cost cross-border payments & settlement network for banks and payment providers.
-
Consensus Protocol: Ripple Protocol Consensus Algorithm (RPCA).
-
Unique Node List (UNL): Each server (validator) maintains a list of other trusted validators (its UNL). Consensus is reached only among nodes in a server's UNL.
-
Federated Consensus: For a transaction to be validated, it must be approved by a supermajority (e.g., 80%) of the UNL. No mining. Finality in ~3-5 seconds.
-
-
Features: Native digital asset XRP used as bridge currency. High Throughput (1500+ TPS), Low Latency, Low Cost.
R3 Corda
-
Design Philosophy: "Not a blockchain" – a distributed ledger designed for privacy-first inter-institutional agreements. No global broadcast of all data.
-
Architecture:
-
Nodes: Represent legal entities (banks, insurers). Each node has a vault (database of states).
-
States: Represent on-ledger facts (e.g.,
Cash,IOU,Loan). Immutable once created. -
Contracts: Define the rules (constraints) for evolving a state (using JVM languages). Enforced during transaction notarization.
-
Flows: The "smart contract" logic for how to agree on a transaction between nodes (e.g.,
IssueCashFlow,SettlePaymentFlow). Encapsulate the communication protocol. -
Notaries: Unique nodes that provide uniqueness consensus (prevent double-spend) and optionally timestamping. They do not see transaction content.
-
-
Consensus: Two-layer:
-
Validity Consensus: Achieved via contract code (all parties must agree the transaction is valid).
-
Uniqueness Consensus: Provided by the Notary (ensures no double-spend of a state).
-
-
Use Case: Inter-Institutional Financial Agreements: Syndicated loans, trade finance, insurance claims, derivatives. Focus on confidentiality and legal enforceability.
[!TIP] Exam Focus: Be able to compare Fabric (channel-based, endorsement), Ripple (UNL, fast payments), and Corda (notary, state/contract/flow, privacy). Know Fabric's endorsement policy and Corda's two-layer consensus.
VII. BLOCKCHAIN APPLICATIONS & USE CASES
Financial Services
Cross-Border Payments
-
Traditional Process: Relies on correspondent banking. Multiple intermediary banks, each adding fees, delays (2-5 days), and opacity. Requires nostro/vostro accounts.
-
Blockchain Solution (e.g., Ripple):
-
Direct P2P Settlement: Using a digital asset (XRP) as a bridge currency, banks can settle directly without pre-funded accounts.
-
Speed: Seconds vs. days.
-
Cost: Drastically reduced fees (no multiple intermediaries).
-
Transparency & Tracking: Real-time status of payment across the network.
-
Reduced Capital Requirements: No need to hold large reserves in foreign accounts.
-
Supply Chain Finance
-
Traditional: Invoice financing is slow, paper-based, and risky. Banks rely on trust in large buyers, leading to high costs for SMEs.
-
Blockchain Improvement:
-
Immutable Record of Trade: All events (PO, shipment, invoice) are recorded on a permissioned ledger shared by buyer, seller, supplier, bank.
-
Automated Invoice Financing: Smart contracts can automatically trigger payment or financing when verifiable events occur (e.g., "Bill of Lading received").
-
Improved Trust & Liquidity: Banks can verify the authenticity of invoices and underlying trade, reducing fraud risk and lowering financing costs for SMEs. Reduces discrepancies in documents.
-
Mortgage Process
-
Traditional: Paper-heavy, involves multiple parties (lender, borrower, title company, appraiser, insurer). Slow (30-60 days), prone to fraud, manual verification.
-
Blockchain-Enabled:
-
Digitized Assets: The promissory note and mortgage deed are created as digital tokens (smart contracts) on a permissioned blockchain.
-
Shared, Immutable Ledger: All parties (lender, servicer, investor, regulator) access the same verified data (income, appraisal, title).
-
Smart Contract Automation: Automates workflows: triggers appraisal upon application, releases funds upon closing conditions met, automates payment distribution to investors.
-
Audit Trail & Reduced Fraud: Every action is timestamped and signed. Prevents duplicate selling of loans (as in 2008 crisis).
-
Secondary Market: Tokenized mortgages can be traded more easily on a blockchain-based platform.
- Result: Reduced processing time (to days), lower costs, enhanced transparency, reduced fraud.
-
Identity Management
-
Self-Sovereign Identity (SSI): Users create and control their own digital identity without relying on a central authority.
-
Components:
-
Decentralized Identifiers (DIDs): Unique identifiers (e.g.,
did:example:123456) that are resolvable to a DID Document (contains public keys, service endpoints). -
Verifiable Credentials (VCs): Digitally signed claims (e.g., "Driving License", "Degree") issued by an authority (government, university).
-
-
Blockchain's Role:
-
Immutable Registry: Acts as a decentralized key-value store for DID Documents (public keys) and schema definitions.
-
Consent Management: Users grant/revoke permission to share specific VCs with verifiers via a wallet.
-
Reduced Identity Theft: No central database to hack. Users present zero-knowledge proofs (e.g., prove age > 21 without revealing birthdate).
-
Portability: Identity is not tied to a single service provider.
-
Trade Finance & Letters of Credit
-
Traditional LC Process: Highly manual, paper-based (up to 30+ pages), involves banks, buyer, seller, shipper. Slow (5-10 days), error-prone, high cost.
-
Blockchain Solution (e.g., we.trade, Marco Polo):
-
Digitized Bill of Lading: The key document of title becomes a digital token on a blockchain.
-
LC as a Smart Contract: The LC terms are encoded. Events (shipment departure, arrival, document submission) are recorded on-chain.
-
Automated Payment: Upon automatic verification of compliant documents (via smart contract rules), payment is triggered to the seller.
-
Benefits: Reduces processing time to <24 hours, cuts costs by 50%+, eliminates discrepancies, provides real-time visibility to all parties.
-
[!TIP] Exam Focus: For use case questions, structure your answer: 1. Traditional Pain Points, 2. How Blockchain Addresses Them (specific tech: smart contracts, immutability, tokens), 3. Quantifiable Benefits (time, cost, risk). Mortgage, Cross-Border, and Supply Chain Finance are highest frequency.