CST428 Blockchain Technologies - Solved Papers

Answer Key - CST428 Blockchain Technologies

Answer Key - CST428 Blockchain Technologies

Answer Key - CST428 Blockchain Technologies

Examination: September 2025
Course Code: CST428
Course Name: Blockchain Technologies
Total Marks: 100
Duration: 3 Hours
Modules Covered: All (1-5)
QP Code: 0400CST428042503


PART A

Answer all questions, each carries 3 marks

Question 1: What is the significance of "Merkle root" stored in the block header? (3 marks)

The Merkle root is a cryptographic hash that represents a summary of all transactions in a block, stored in the block header.

Significance:

  1. Integrity Verification: The Merkle root allows efficient verification that all transactions in the block are valid and unmodified without downloading the entire block.

  2. Efficient Transaction Verification: Using Merkle proofs, users can verify if a specific transaction is included in a block by checking only a small number of hashes (logarithmic complexity O(log n)) instead of all transactions.

  3. Block Linking: The Merkle root in the block header ensures that any change to any transaction in the block will change the Merkle root, which in turn changes the block hash, breaking the blockchain chain and making tampering evident.

  4. Space Efficiency: Light clients (SPV - Simplified Payment Verification) can verify transactions by downloading only block headers (which contain the Merkle root) rather than full blocks, saving storage space.


Question 2: List out the desirable properties for a cryptographic hash function. (3 marks)

A cryptographic hash function must possess the following essential properties:

Key Properties:

  1. Deterministic: The same input always produces the same hash output.

  2. Pre-image Resistance (One-way): Given a hash value h, it should be computationally infeasible to find any input x such that H(x) = h. This ensures the function cannot be reversed.

  3. Second Pre-image Resistance (Weak Collision Resistance): Given an input x₁, it should be computationally infeasible to find a different input x₂ such that H(x₁) = H(x₂).

  4. Collision Resistance (Strong Collision Resistance): It should be computationally infeasible to find any two different inputs x₁ and x₂ such that H(x₁) = H(x₂).

  5. Avalanche Effect: A small change in input (even one bit) should produce a significantly different hash output (approximately 50% of bits should change).

  6. Fast Computation: The hash function should be efficient to compute for any input.


Question 3: Depict the generic structure of a block in blockchain. (3 marks)

A blockchain block has a generic structure consisting of a block header and a block body.

Generic Block Structure:

┌─────────────────────────────────────────┐
│           BLOCK HEADER                  │
├─────────────────────────────────────────┤
│  • Block Version                        │
│  • Previous Block Hash                  │
│  • Merkle Root (Transaction Hash Tree)  │
│  • Timestamp                            │
│  • Difficulty Target / Nonce            │
│  • Block Height / Block Number          │
└─────────────────────────────────────────┘
┌─────────────────────────────────────────┐
│           BLOCK BODY                    │
├─────────────────────────────────────────┤
│  • Transaction Counter                  │
│  • Transaction List:                    │
│    - Transaction 1                      │
│    - Transaction 2                      │
│    - Transaction 3                      │
│    - ...                                │
│    - Transaction N                      │
└─────────────────────────────────────────┘

Key Components:

  • Previous Block Hash: Links the current block to the previous block, creating the chain
  • Merkle Root: Hash of all transactions in the block
  • Timestamp: When the block was created
  • Nonce/Difficulty: Used in mining for Proof of Work consensus
  • Transactions: The actual data/transactions stored in the block

Question 4: Describe how full ecosystem decentralization is possible in blockchain. (3 marks)

Full ecosystem decentralization in blockchain refers to distributing control across all layers of the blockchain system rather than just the consensus layer.

How Full Ecosystem Decentralization is Achieved:

  1. Technical Decentralization:

    • Distributed Network: No central server; peer-to-peer network of nodes worldwide
    • Consensus Mechanism: Decision-making distributed across validators/miners (PoW, PoS)
    • Data Storage: Blockchain data replicated across all full nodes
  2. Political/Governance Decentralization:

    • Decision Making: Protocol changes require community consensus
    • No Single Authority: No individual or organization controls the network
    • DAOs: Decentralized Autonomous Organizations enable community governance
  3. Logical/Architectural Decentralization:

    • Application Layer: DApps run on decentralized infrastructure
    • Storage Layer: Distributed file systems (IPFS, Swarm)
    • Identity Layer: Self-sovereign identity systems
    • Oracle Layer: Decentralized oracles for external data
  4. Economic Decentralization:

    • Token Distribution: Cryptocurrency distributed among participants
    • Mining/Staking: Economic incentives spread across network participants

Result: The entire ecosystem operates without central control, ensuring resilience, censorship resistance, and true peer-to-peer operation.


Question 5: Explain the terms Genesis block and coinbase transaction. (3 marks)

Genesis Block:

The Genesis Block is the very first block (Block 0) in a blockchain, serving as the foundation of the entire chain.

Characteristics:

  • Has no previous block hash (or references a null/zero hash)
  • Hardcoded into the blockchain protocol
  • Cannot be changed without recreating the entire blockchain
  • In Bitcoin, created on January 3, 2009, by Satoshi Nakamoto
  • Contains a special message (e.g., Bitcoin's genesis block contains: "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks")

Coinbase Transaction:

A Coinbase Transaction is the first transaction in every block that creates new cryptocurrency as a reward for the miner who successfully mines the block.

Characteristics:

  • Has no inputs (creates coins from nothing)
  • Rewards the miner with newly minted coins (block reward)
  • Includes transaction fees collected from all transactions in the block
  • In Bitcoin, the block reward started at 50 BTC and halves approximately every 4 years
  • Contains arbitrary data field that miners can use to include messages
  • Must mature (100 blocks in Bitcoin) before the reward can be spent

Example: In Bitcoin, if the current block reward is 6.25 BTC and transaction fees total 0.5 BTC, the coinbase transaction creates 6.75 BTC for the miner.


Question 6: What is "hash rate" in Bitcoin? How does it vary with respect to time? (3 marks)

Hash Rate:

Hash rate is the measure of computational power being used in Bitcoin mining, representing the number of hash calculations performed per second by miners attempting to find a valid block hash.

Definition & Units:

  • Measured in hashes per second (H/s)
  • Common units: KH/s (kilo), MH/s (mega), GH/s (giga), TH/s (tera), PH/s (peta), EH/s (exa)
  • Indicates the total mining power of the entire Bitcoin network

How Hash Rate Varies with Time:

  1. Generally Increasing Trend: Bitcoin's network hash rate has shown exponential growth since 2009 due to:

    • More miners joining the network
    • Development of specialized mining hardware (CPUs → GPUs → FPGAs → ASICs)
    • Increased efficiency of mining equipment
  2. Short-term Fluctuations: Hash rate can vary due to:

    • Mining profitability changes (Bitcoin price fluctuations)
    • Mining difficulty adjustments (every 2016 blocks, ~2 weeks)
    • Seasonal factors (electricity costs, weather affecting cooling)
    • Regulatory changes affecting mining operations
    • Entry/exit of large mining farms
  3. Difficulty Adjustment Mechanism: Bitcoin adjusts mining difficulty every 2016 blocks to maintain an average block time of 10 minutes, regardless of hash rate changes.

Significance: Higher hash rate means greater network security and more resistance to 51% attacks.


Question 7: What is a Decentralized Autonomous Organization (DAO)? (3 marks)

A Decentralized Autonomous Organization (DAO) is an organization that operates through smart contracts on a blockchain, with rules and decision-making encoded in code rather than controlled by a central authority.

Key Characteristics:

  1. Decentralized Governance: No central leadership; decisions made collectively by token holders through voting mechanisms.

  2. Autonomous Operation: Smart contracts automatically execute decisions and rules without human intervention once deployed.

  3. Transparent Rules: All rules, transactions, and decisions are recorded on the blockchain and visible to all members.

  4. Token-Based Membership: Ownership and voting rights typically represented by tokens; voting power often proportional to token holdings.

How DAOs Work:

  • Members propose changes or actions
  • Token holders vote on proposals
  • Smart contracts automatically execute approved proposals
  • Treasury and funds managed collectively through smart contracts

Examples:

  • Investment DAOs (pooling funds for collective investment decisions)
  • Protocol DAOs (governing DeFi protocols like MakerDAO, Uniswap)
  • Social DAOs (community-driven organizations)

Benefits: Eliminates corruption, ensures transparency, enables global collaboration, and removes single points of failure.


Question 8: Give any two use cases where blockchain and AI can be combined. (3 marks)

Blockchain and Artificial Intelligence (AI) can be synergistically combined in various applications. Here are two significant use cases:

Use Case 1: Decentralized AI Model Training and Data Marketplace

Application:

  • Blockchain provides a decentralized marketplace where data owners can securely share training data with AI developers
  • Smart contracts ensure fair compensation for data providers
  • AI models can be trained on distributed datasets without compromising privacy

Benefits:

  • Data Provenance: Blockchain tracks data origin and quality
  • Privacy: Federated learning allows AI training without exposing raw data
  • Fair Compensation: Automated payments via smart contracts for data contributions
  • Trust: Immutable records of data usage and model versions

Example: Healthcare organizations can contribute medical data for AI training while maintaining patient privacy and receiving compensation through blockchain-based tokens.

Use Case 2: AI-Powered Smart Contract Auditing and Fraud Detection

Application:

  • AI algorithms analyze blockchain transactions and smart contract code to detect anomalies, fraud, and security vulnerabilities
  • Machine learning models identify patterns in blockchain data for risk assessment
  • AI enhances blockchain security by predicting potential attacks

Benefits:

  • Automated Security: AI continuously monitors for suspicious activities
  • Smart Contract Verification: AI detects vulnerabilities and bugs in contract code
  • Fraud Prevention: Real-time detection of fraudulent transactions
  • Predictive Analytics: AI forecasts network threats and congestion

Example: AI systems can analyze Ethereum smart contracts before deployment to identify potential vulnerabilities (e.g., reentrancy attacks) and blockchain transaction patterns to detect money laundering activities.


Question 9: Distinguish between 'mainnet', 'testnet' and 'privatenet' in Ethereum blockchain. (3 marks)

Ethereum blockchain networks can be categorized into three types based on their purpose and accessibility:

Feature Mainnet Testnet Privatenet
Purpose Production network for real transactions Testing environment for developers Private development/enterprise use
Real Value Uses real ETH with actual monetary value Uses test ETH with no real value May use custom tokens with no external value
Accessibility Public, anyone can join Public, anyone can join Private, restricted access
Use Case Real DApps, live smart contracts, actual transactions Testing smart contracts before mainnet deployment Enterprise applications, private consortiums
Examples Ethereum Mainnet (Chain ID: 1) Sepolia, Goerli, Rinkeby Hyperledger Besu, Quorum, private Geth instances
Cost Real gas fees in ETH Free test ETH from faucets Configurable, often minimal or free
Security High, full network consensus Moderate, similar to mainnet Controlled by network administrators

Key Distinctions:

  • Mainnet: Production environment where real assets are at stake
  • Testnet: Sandbox for developers to experiment without financial risk; mimics mainnet behavior
  • Privatenet: Isolated network for specific organizations; full control over consensus, permissions, and participants

Developer Workflow: Typically develop on privatenet → test on testnet → deploy to mainnet.


Question 10: Jordan has to pay Taylor 1 ETH. An ETH transfer requires 21,000 units of gas. The base fee is 10 gwei and Jordan also includes a tip of 2 gwei. What will be the gas fee for this transaction? How much ETH will be deducted from Jordan's account? (3 marks)

Given:

  • Amount to transfer: 1 ETH
  • Gas units required: 21,000
  • Base fee: 10 gwei
  • Priority fee (tip): 2 gwei

Step 1: Calculate Total Gas Price

Total Gas Price = Base Fee + Priority Fee (Tip)
Total Gas Price = 10 gwei + 2 gwei = 12 gwei

Step 2: Calculate Transaction Fee (Gas Fee)

Transaction Fee = Gas Units × Total Gas Price
Transaction Fee = 21,000 × 12 gwei
Transaction Fee = 252,000 gwei

Convert to ETH:

  • 1 ETH = 10⁹ gwei (1 billion gwei)
  • Transaction Fee = 252,000 / 1,000,000,000 ETH
  • Transaction Fee = 0.000252 ETH

Step 3: Calculate Total Amount Deducted

Total Deducted = Transfer Amount + Transaction Fee
Total Deducted = 1 ETH + 0.000252 ETH
Total Deducted = 1.000252 ETH

Answer:

  • Gas Fee: 252,000 gwei or 0.000252 ETH
  • Total ETH Deducted from Jordan's Account: 1.000252 ETH

Breakdown:

  • Taylor receives: 1 ETH
  • Network fee (burned + tip): 0.000252 ETH
  • Jordan pays: 1.000252 ETH total

PART B

Answer any one full question from each module, each carries 14 marks

Module I - Fundamentals of Cryptography — #### Question 11

Question 11

(a) Explain the RSA key generation algorithm. Also show how RSA generates public and private keys from the values P = 17 and Q = 11. (7 marks)

RSA Key Generation Algorithm:

RSA (Rivest-Shamir-Adleman) is an asymmetric cryptographic algorithm that uses a pair of keys: a public key for encryption and a private key for decryption.

Algorithm Steps:

  1. Select two large prime numbers: Choose two distinct large prime numbers p and q
  2. Compute n: Calculate n = p × q (modulus for both keys)
  3. Compute φ(n): Calculate Euler's totient function φ(n) = (p-1) × (q-1)
  4. Choose public exponent e: Select e such that:
    • 1 < e < φ(n)
    • gcd(e, φ(n)) = 1 (e is coprime to φ(n))
    • Commonly used values: 3, 17, 65537
  5. Compute private exponent d: Calculate d such that:
    • d × e ≡ 1 (mod φ(n))
    • d is the modular multiplicative inverse of e modulo φ(n)
  6. Form keys:
    • Public Key: (e, n)
    • Private Key: (d, n)

Numerical Example with P = 17 and Q = 11:

Given:

  • p = 17
  • q = 11

Step 1: Compute n

n = p × q = 17 × 11 = 187

Step 2: Compute φ(n)

φ(n) = (p - 1) × (q - 1)
φ(n) = (17 - 1) × (11 - 1)
φ(n) = 16 × 10 = 160

Step 3: Choose e (public exponent)

We need to choose e such that gcd(e, 160) = 1

Let's choose e = 7

Verify: gcd(7, 160) = 1 ✓ (7 is coprime to 160)

Step 4: Compute d (private exponent)

We need to find d such that: d × e ≡ 1 (mod φ(n))

d × 7 ≡ 1 (mod 160)

Using Extended Euclidean Algorithm:

160 = 22 × 7 + 6
7 = 1 × 6 + 1
6 = 6 × 1 + 0

Back substitution:
1 = 7 - 1 × 6
1 = 7 - 1 × (160 - 22 × 7)
1 = 7 - 160 + 22 × 7
1 = 23 × 7 - 160

Therefore: d = 23

Verification: (23 × 7) mod 160 = 161 mod 160 = 1 ✓

Generated Keys:

  • Public Key: (e, n) = (7, 187)

    • Used for encryption
    • Can be shared publicly
  • Private Key: (d, n) = (23, 187)

    • Used for decryption
    • Must be kept secret

Encryption: C = M^e mod n = M^7 mod 187
Decryption: M = C^d mod n = C^23 mod 187


(b) Illustrate the digital signature generation and verification process. (7 marks)

Digital Signature:

A digital signature is a cryptographic mechanism that provides authentication, integrity, and non-repudiation for digital messages or documents. It uses asymmetric cryptography where the sender signs with their private key and the receiver verifies with the sender's public key.

Digital Signature Process:

flowchart TD
    A[Original Message] --> B[Hash Function]
    B --> C[Message Digest/Hash]
    D[Sender's Private Key] --> E[Signature Algorithm]
    C --> E
    E --> F[Digital Signature]
    F --> G[Attach Signature to Message]
    A --> G
    G --> H[Signed Message]

    H --> I[Receiver Extracts Message & Signature]
    I --> J[Hash Original Message]
    I --> K[Decrypt Signature with Sender's Public Key]
    L[Sender's Public Key] --> K
    J --> M[Compare Hash Values]
    K --> M
    M --> N{Hashes Match?}
    N -->|Yes| O[Signature Valid - Message Authentic]
    N -->|No| P[Signature Invalid - Message Tampered]

Digital Signature Generation Process:

Step 1: Create Message Digest

  • Sender creates a message M
  • Apply cryptographic hash function to message: H(M)
  • This produces a fixed-size message digest (e.g., SHA-256 produces 256 bits)

Step 2: Sign the Digest

  • Sender encrypts the message digest using their private key
  • Signature = Encrypt(H(M), Private Key_sender)
  • This creates the digital signature

Step 3: Transmit

  • Send both the original message M and the signature to the receiver
  • Message package: {M, Signature}

Digital Signature Verification Process:

Step 4: Receive Signed Message

  • Receiver obtains the message M and the signature

Step 5: Decrypt Signature

  • Receiver decrypts the signature using sender's public key
  • Decrypted Digest = Decrypt(Signature, Public Key_sender)

Step 6: Compute Fresh Hash

  • Receiver independently computes hash of received message
  • Fresh Digest = H(M)

Step 7: Compare Digests

  • Compare Decrypted Digest with Fresh Digest
  • If Decrypted Digest == Fresh Digest → Signature is VALID
  • If Decrypted Digest ≠ Fresh Digest → Signature is INVALID

Example with RSA Digital Signature:

Scenario: Alice wants to send a signed message to Bob

Alice's Keys:

  • Private Key: (d, n) = (23, 187)
  • Public Key: (e, n) = (7, 187)

Signing Process:

  1. Message: M = "TRANSFER 100 BTC"
  2. Hash: h = H(M) = 65 (example hash value)
  3. Sign: Signature = h^d mod n = 65^23 mod 187 = 120
  4. Send: {M, Signature = 120}

Verification Process (Bob):

  1. Receive: Message M and Signature = 120
  2. Decrypt Signature: h' = 120^e mod n = 120^7 mod 187 = 65
  3. Compute Hash: h = H(M) = 65
  4. Compare: h' (65) == h (65) ✓
  5. Result: Signature is VALID, message is authentic

Security Properties:

  1. Authentication: Proves the message came from the claimed sender
  2. Integrity: Ensures message hasn't been altered
  3. Non-repudiation: Sender cannot deny sending the message
  4. Unforgeable: Only the private key holder can create valid signatures

Applications in Blockchain:

  • Transaction signing in Bitcoin/Ethereum
  • Block validation
  • Smart contract deployment
  • Wallet authentication

Question 12

(a) Explain with a neat block diagram, the steps involved in AES algorithm. (7 marks)

AES (Advanced Encryption Standard):

AES is a symmetric block cipher that encrypts data in fixed-size blocks of 128 bits using keys of 128, 192, or 256 bits. It is the most widely used encryption algorithm today, adopted as a standard by NIST in 2001.

AES Algorithm Overview:

Key Parameters:

  • Block Size: 128 bits (16 bytes) - fixed
  • Key Sizes: 128 bits (10 rounds), 192 bits (12 rounds), or 256 bits (14 rounds)
  • State: 4×4 matrix of bytes (16 bytes total)

AES Encryption Process:

flowchart TD
    A[Plaintext 128 bits] --> B[Convert to 4x4 State Matrix]
    B --> C[Add Round Key - Initial]
    D[Key Expansion] --> C
    C --> E{Round Loop}
    E --> F[SubBytes Substitution]
    F --> G[ShiftRows Permutation]
    G --> H[MixColumns Diffusion]
    H --> I[AddRoundKey]
    I --> J{Last Round?}
    J -->|No| E
    J -->|Yes| K[Final Round: SubBytes]
    K --> L[Final Round: ShiftRows]
    L --> M[Final Round: AddRoundKey]
    M --> N[Convert State to Ciphertext]
    N --> O[Ciphertext 128 bits]

AES Encryption Steps (Detailed):

Step 0: Key Expansion

  • Generate round keys from the original cipher key
  • For AES-128: Generate 11 round keys (128 bits each) from original 128-bit key
  • Uses Rijndael key schedule algorithm

Step 1: Initial Round (Before Main Rounds)

AddRoundKey:

  • XOR the state matrix with the first round key
  • State ⊕ RoundKey[0]

Step 2: Main Rounds (Repeat 9, 11, or 13 times depending on key size)

For each round, perform four transformations:

a) SubBytes (Substitution):

  • Non-linear substitution step
  • Each byte in the state is replaced using an S-box (substitution box)
  • Provides confusion (obscures relationship between plaintext and ciphertext)
  • S-box is based on multiplicative inverse in GF(2^8)
Example: If state byte = 0x53, S-box[0x53] = 0xED

b) ShiftRows (Permutation):

  • Transposition step for diffusion
  • Rows of the state matrix are cyclically shifted left
    • Row 0: No shift
    • Row 1: Shift 1 byte left
    • Row 2: Shift 2 bytes left
    • Row 3: Shift 3 bytes left
Before:        After:
[a0 a1 a2 a3]  [a0 a1 a2 a3]
[b0 b1 b2 b3]  [b1 b2 b3 b0]
[c0 c1 c2 c3]  [c2 c3 c0 c1]
[d0 d1 d2 d3]  [d3 d0 d1 d2]

c) MixColumns (Diffusion):

  • Each column of the state is multiplied with a fixed polynomial
  • Operates on columns independently
  • Provides diffusion (spreads influence of each bit)
  • Uses matrix multiplication in GF(2^8)
  • Note: Skipped in the final round
Each column multiplied by matrix:
[02 03 01 01]
[01 02 03 01]
[01 01 02 03]
[03 01 01 02]

d) AddRoundKey:

  • XOR state with current round key
  • State ⊕ RoundKey[i]

Step 3: Final Round (Round 10 for AES-128)

  • SubBytes
  • ShiftRows
  • AddRoundKey (with final round key)
  • Note: MixColumns is omitted in the final round

Step 4: Output Ciphertext

  • Convert the final state matrix back to 128-bit ciphertext

AES State Matrix Representation:

Plaintext (128 bits) arranged in 4×4 byte matrix:

[b0  b4  b8  b12]
[b1  b5  b9  b13]
[b2  b6  b10 b14]
[b3  b7  b11 b15]

AES Decryption:

Decryption is the reverse process using inverse transformations:

  • InvSubBytes (using inverse S-box)
  • InvShiftRows (shift right instead of left)
  • InvMixColumns (using inverse matrix)
  • AddRoundKey (same operation, XOR is its own inverse)

Security Features:

  • Resistant to known cryptanalytic attacks
  • No practical attacks faster than brute force
  • Fast in both hardware and software
  • Used in SSL/TLS, VPNs, file encryption, blockchain

(b) Demonstrate the design of SHA-256 cryptographic hash function and its applications. (7 marks)

SHA-256 (Secure Hash Algorithm 256-bit):

SHA-256 is a cryptographic hash function from the SHA-2 family, designed by the NSA and published by NIST in 2001. It produces a 256-bit (32-byte) hash value from input of any size.

SHA-256 Design and Architecture:

Input/Output Specifications:

  • Input: Message of any length (up to 2^64 - 1 bits)
  • Output: 256-bit hash value (64 hexadecimal characters)
  • Block Size: 512 bits (64 bytes)
  • Word Size: 32 bits

SHA-256 Algorithm Steps:

flowchart TD
    A[Input Message] --> B[Padding Message]
    B --> C[Append Length 64 bits]
    C --> D[Divide into 512-bit blocks]
    D --> E[Initialize Hash Values H0-H7]
    E --> F[Process Each 512-bit Block]
    F --> G[Message Schedule W0 to W63]
    G --> H[Compression Function 64 rounds]
    H --> I[Update Hash Values]
    I --> J{More Blocks?}
    J -->|Yes| F
    J -->|No| K[Concatenate H0 to H7]
    K --> L[Final 256-bit Hash Output]

Step 1: Message Padding

  • Append bit '1' to the message
  • Append zeros until message length ≡ 448 (mod 512)
  • Ensures that after adding 64-bit length, total is multiple of 512 bits

Example:

Original message: "abc" = 24 bits
After padding: 24 + 1 + 423 zeros = 448 bits

Step 2: Append Length

  • Append original message length as 64-bit big-endian integer
  • Total message now multiple of 512 bits

Step 3: Initialize Hash Values (H0 to H7)

Eight 32-bit hash values initialized with first 32 bits of fractional parts of square roots of first 8 primes:

H0 = 0x6a09e667
H1 = 0xbb67ae85
H2 = 0x3c6ef372
H3 = 0xa54ff53a
H4 = 0x510e527f
H5 = 0x9b05688c
H6 = 0x1f83d9ab
H7 = 0x5be0cd19

Step 4: Process Each 512-bit Message Block

For each 512-bit block:

4a) Message Schedule (Prepare 64 words W[0] to W[63]):

  • First 16 words (W[0] to W[15]): Directly from the 512-bit message block
  • Remaining 48 words (W[16] to W[63]): Generated using:
W[t] = σ1(W[t-2]) + W[t-7] + σ0(W[t-15]) + W[t-16]

where:
σ0(x) = ROTR^7(x) ⊕ ROTR^18(x) ⊕ SHR^3(x)
σ1(x) = ROTR^17(x) ⊕ ROTR^19(x) ⊕ SHR^10(x)

4b) Initialize Working Variables:

a = H0, b = H1, c = H2, d = H3
e = H4, f = H5, g = H6, h = H7

4c) Compression Function (64 Rounds):

For t = 0 to 63:

T1 = h + Σ1(e) + Ch(e,f,g) + K[t] + W[t]
T2 = Σ0(a) + Maj(a,b,c)

h = g
g = f
f = e
e = d + T1
d = c
c = b
b = a
a = T1 + T2

Logical Functions:

Ch(x,y,z) = (x ∧ y) ⊕ (¬x ∧ z)    // Choose
Maj(x,y,z) = (x ∧ y) ⊕ (x ∧ z) ⊕ (y ∧ z)    // Majority

Σ0(x) = ROTR^2(x) ⊕ ROTR^13(x) ⊕ ROTR^22(x)
Σ1(x) = ROTR^6(x) ⊕ ROTR^11(x) ⊕ ROTR^25(x)

Constants K[t]: 64 constants representing first 32 bits of fractional parts of cube roots of first 64 primes

4d) Update Hash Values:

H0 = H0 + a
H1 = H1 + b
H2 = H2 + c
H3 = H3 + d
H4 = H4 + e
H5 = H5 + f
H6 = H6 + g
H7 = H7 + h

Step 5: Produce Final Hash

Hash = H0 || H1 || H2 || H3 || H4 || H5 || H6 || H7

(Concatenation of eight 32-bit values = 256 bits)

Example:

Input: "abc"
Output: ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad

Applications of SHA-256:

  1. Bitcoin and Blockchain:

    • Mining: Proof-of-Work consensus (finding hash below target difficulty)
    • Block hashing: Each block header is hashed with SHA-256 (applied twice)
    • Transaction IDs: Unique identifier for transactions
    • Merkle tree construction: Building transaction Merkle trees
  2. Digital Signatures:

    • Message digest creation before signing with RSA/ECDSA
    • Ensures integrity of signed documents
  3. Password Storage:

    • Hashing passwords before storage (with salt)
    • One-way function prevents password recovery from hash
  4. Data Integrity Verification:

    • File integrity checking (checksums)
    • Software distribution verification
    • Digital forensics
  5. SSL/TLS Certificates:

    • Certificate fingerprinting
    • Secure web communications
  6. Cryptocurrency Addresses:

    • Bitcoin address generation (along with RIPEMD-160)
    • Ethereum uses Keccak-256, but SHA-256 used in some crypto operations
  7. Merkle Trees:

    • Efficient verification of data integrity in distributed systems
    • Used in Git, BitTorrent, blockchain

Security Properties:

  • Pre-image resistance: Cannot find input from hash
  • Collision resistance: Computationally infeasible to find two inputs with same hash
  • Avalanche effect: Small input change causes significant hash change
  • Deterministic: Same input always produces same hash

Module II - Fundamentals of Blockchain Technology — #### Question 13

Question 13

(a) Explain different types of blockchain based on technical and business usage perspective. (7 marks)

Blockchains can be categorized into different types based on access control, participation, and intended use. From technical and business perspectives, there are four main types:

1. Public Blockchain (Permissionless)

Technical Characteristics:

  • Open access: Anyone can join, read, write, and participate
  • Fully decentralized: No central authority
  • Transparent: All transactions publicly visible
  • Consensus: PoW, PoS, or other decentralized mechanisms
  • High security through cryptography and consensus

Business Use Cases:

  • Cryptocurrency networks (Bitcoin, Ethereum)
  • Public record keeping
  • Crowdfunding platforms
  • Decentralized applications (DApps)
  • Public voting systems

Advantages:

  • Complete transparency and trust through decentralization
  • Censorship-resistant
  • No single point of failure

Disadvantages:

  • Slow transaction speed
  • High energy consumption (especially PoW)
  • Limited scalability
  • No privacy for sensitive business data

Examples: Bitcoin, Ethereum, Litecoin


2. Private Blockchain (Permissioned)

Technical Characteristics:

  • Restricted access: Only invited/authorized participants
  • Controlled by single organization or consortium
  • Selective transparency: Data visible only to permitted participants
  • Consensus: Simplified mechanisms (may not need PoW/PoS)
  • Centralized or semi-centralized control

Business Use Cases:

  • Internal organizational processes
  • Supply chain management within company
  • Internal auditing and compliance
  • Asset management
  • Private record keeping

Advantages:

  • High transaction speed
  • Energy efficient
  • Better privacy and confidentiality
  • Scalable for specific use cases
  • Regulatory compliance easier

Disadvantages:

  • Less trustless (requires trusting the controlling entity)
  • Partially centralized
  • Limited decentralization benefits
  • Potential for censorship

Examples: Hyperledger Fabric (in private mode), R3 Corda, Quorum (private mode)


3. Consortium/Federated Blockchain (Hybrid)

Technical Characteristics:

  • Semi-decentralized: Controlled by a group of organizations
  • Pre-selected nodes: Only authorized nodes validate transactions
  • Restricted read/write access: May be public or restricted
  • Consensus: Decided by consortium members (PBFT, voting-based)
  • Balanced approach between public and private

Business Use Cases:

  • Banking and financial consortiums
  • Cross-organizational supply chains
  • Healthcare data sharing among hospitals
  • Research collaborations
  • Industry-specific networks (trade finance, shipping)

Advantages:

  • Better scalability than public blockchains
  • More decentralized than private blockchains
  • Faster transaction processing
  • Shared control reduces single point of failure
  • Cost-effective for participating organizations

Disadvantages:

  • Less transparent than public blockchains
  • Coordination overhead among consortium members
  • Potential conflicts of interest
  • Setup complexity

Examples: R3 (Banking consortium), Energy Web Chain, IBM Food Trust


4. Hybrid Blockchain

Technical Characteristics:

  • Combination of public and private elements
  • Flexible access control: Some data public, some private
  • Customizable permissions
  • Controlled transparency: Organizations choose what to make public
  • Dual-layer architecture

Business Use Cases:

  • Real estate transactions (public ownership, private details)
  • Healthcare (public health data, private patient records)
  • Retail (public product tracking, private supplier information)
  • Government services (public records, private citizen data)

Advantages:

  • Flexibility: Best of both worlds
  • Controlled data disclosure
  • Better scalability than pure public blockchains
  • Privacy for sensitive data with public verifiability

Disadvantages:

  • Implementation complexity
  • Requires careful design
  • Maintenance overhead

Examples: Dragonchain, XinFin


Comparison Table:

Feature Public Private Consortium Hybrid
Access Open to all Restricted Selected group Mixed
Decentralization Fully decentralized Centralized Semi-decentralized Mixed
Speed Slow Fast Moderate-Fast Moderate
Transparency Full Limited Selective Customizable
Security Very High Moderate High High
Energy Use High (PoW) Low Low-Moderate Moderate
Typical Users General public Single organization Industry groups Mixed entities

Selection Criteria for Businesses:

  • Choose Public: When maximum transparency, trustlessness, and censorship resistance are needed
  • Choose Private: When privacy, control, and efficiency within an organization are priorities
  • Choose Consortium: When multiple organizations need to collaborate with shared governance
  • Choose Hybrid: When both transparency and privacy are required for different data types

(b) Explain how a blockchain accumulates blocks, starting from transaction initiation. (7 marks)

The process of accumulating blocks in a blockchain involves several steps from transaction creation to block addition. Here's a detailed explanation:

Blockchain Block Accumulation Process:

flowchart TD
    A[User Initiates Transaction] --> B[Transaction Created & Signed]
    B --> C[Transaction Broadcast to Network]
    C --> D[Transaction Enters Mempool]
    D --> E[Miners/Validators Select Transactions]
    E --> F[Create Transaction Merkle Tree]
    F --> G[Construct Block Header]
    G --> H[Consensus Process Mining/Validation]
    H --> I{Valid Block Found?}
    I -->|No| H
    I -->|Yes| J[Broadcast New Block]
    J --> K[Nodes Verify Block]
    K --> L{Block Valid?}
    L -->|No| M[Reject Block]
    L -->|Yes| N[Add Block to Local Chain]
    N --> O[Update Blockchain State]
    O --> P[Block Confirmed]
    P --> Q[Wait for Subsequent Blocks]
    Q --> R[Transaction Finalized]

Detailed Step-by-Step Process:

Phase 1: Transaction Initiation

Step 1: Transaction Creation

  • User creates a transaction using wallet software
  • Transaction includes:
    • Sender's address
    • Receiver's address
    • Amount/data to transfer
    • Transaction fee
    • Timestamp

Step 2: Transaction Signing

  • User signs transaction with their private key using digital signature (ECDSA in Bitcoin/Ethereum)
  • This proves ownership and authorizes the transaction
  • Signature ensures transaction cannot be modified

Step 3: Transaction Broadcast

  • Signed transaction is broadcast to the peer-to-peer network
  • Each node receives and validates the transaction
  • Nodes check:
    • Valid signature
    • Sufficient balance
    • Correct format
    • No double-spending

Phase 2: Transaction Pool (Mempool)

Step 4: Mempool Collection

  • Valid transactions enter the mempool (memory pool)
  • Mempool is temporary storage for unconfirmed transactions
  • Each node maintains its own mempool
  • Transactions wait here until included in a block
  • Miners/validators select transactions from mempool based on:
    • Transaction fees (higher fees = higher priority)
    • Transaction size
    • Age of transaction

Phase 3: Block Construction

Step 5: Transaction Selection

  • Miners/validators select a set of transactions from mempool
  • Goal: Maximize transaction fees while staying within block size limit
  • Typical strategies:
    • Fee-based prioritization
    • Optimal packing algorithms

Step 6: Build Merkle Tree

  • Selected transactions are organized into a Merkle tree
  • Merkle tree root calculated through pairwise hashing
  • Merkle root stored in block header
  • Provides efficient verification of transaction inclusion

Step 7: Create Block Header
Block header contains:

  • Version: Block version number
  • Previous Block Hash: Hash of the previous block (creates the chain)
  • Merkle Root: Root hash of all transactions
  • Timestamp: Current time
  • Difficulty Target: Required difficulty for mining (PoW)
  • Nonce: Number used once (for PoW mining)

Step 8: Create Coinbase Transaction

  • First transaction in the block
  • Creates new coins as block reward for miner
  • Includes transaction fees from all transactions in the block

Phase 4: Consensus (Mining/Validation)

Step 9: Achieve Consensus

For Proof of Work (PoW):

  • Miner attempts to find a nonce such that:
    Hash(Block Header) < Target Difficulty
  • Requires billions of hash computations
  • First miner to find valid nonce wins
  • Computationally intensive (10 minutes average for Bitcoin)

For Proof of Stake (PoS):

  • Validator is selected based on stake
  • Validator proposes and signs the block
  • Other validators attest to block validity
  • Much faster and energy-efficient

Phase 5: Block Propagation

Step 10: Broadcast New Block

  • Winning miner/validator broadcasts the newly created block to the network
  • Block propagates through the P2P network
  • Each node receives the block

Step 11: Block Verification
Receiving nodes verify:

  • Valid proof of work/stake
  • All transactions are valid
  • Merkle root matches transactions
  • Previous block hash is correct
  • Block follows consensus rules
  • No double-spending

Phase 6: Block Addition

Step 12: Add to Blockchain

  • If valid, node adds block to its local copy of blockchain
  • Block is linked to previous block via previous block hash
  • This creates the "chain" in blockchain

Step 13: Update State

  • Update account balances
  • Update UTXO set (for Bitcoin) or account state (for Ethereum)
  • Remove included transactions from mempool
  • Blockchain height increases by 1

Step 14: Confirmation

  • First confirmation: Block is added to chain
  • Additional confirmations: Subsequent blocks are added on top
  • More confirmations = higher security
    • Bitcoin: 6 confirmations recommended (~1 hour)
    • Ethereum: 12-35 confirmations recommended

Phase 7: Finalization

Step 15: Transaction Finality

  • After sufficient confirmations, transaction is considered final
  • Probability of reversal becomes negligible
  • Transaction is permanently recorded in blockchain

Handling Conflicts (Forks):

When two miners find blocks simultaneously:

  • Temporary fork occurs
  • Network splits temporarily
  • Nodes follow longest chain rule
  • Next block determines which chain continues
  • Orphaned blocks are discarded

Key Properties Ensuring Integrity:

  1. Immutability: Changing past blocks requires recomputing all subsequent blocks
  2. Transparency: All nodes can verify all blocks and transactions
  3. Decentralization: No single entity controls block creation
  4. Consensus: All honest nodes agree on blockchain state

Question 14

(a) Describe how decentralization of computing or processing power is achieved by a blockchain. (7 marks)

Decentralization of Computing/Processing Power in Blockchain:

Blockchain achieves decentralization of computing and processing power by distributing computational tasks across a network of independent nodes, eliminating the need for a central authority or server. Here's how this is accomplished:

1. Distributed Peer-to-Peer Network Architecture

Network Structure:

graph TD
    A[Node 1] --- B[Node 2]
    A --- C[Node 3]
    A --- D[Node 4]
    B --- C
    B --- E[Node 5]
    C --- D
    C --- F[Node 6]
    D --- E
    E --- F
    F --- A
    style A fill:#90EE90
    style B fill:#90EE90
    style C fill:#90EE90
    style D fill:#90EE90
    style E fill:#90EE90
    style F fill:#90EE90

Characteristics:

  • No central server; all nodes are equal peers
  • Each node independently stores a copy of the blockchain
  • Nodes communicate directly with each other
  • No single point of failure or control
  • Network remains functional even if nodes join or leave

Computational Distribution:

  • Transaction validation distributed across all nodes
  • Each node independently verifies transactions
  • No reliance on a single processing unit
  • Parallel processing by thousands of nodes

2. Distributed Ledger Technology (DLT)

How It Works:

  • Every participating node maintains a complete copy of the blockchain
  • All nodes have the same information (eventually consistent)
  • When a new transaction occurs:
    • Broadcast to all nodes
    • Each node independently validates
    • Each node updates its local copy

Benefits:

  • Redundancy: Data survives even if majority of nodes fail
  • Transparency: Everyone can verify the ledger
  • No Central Database: No single entity controls the data
  • Fault Tolerance: System continues operating with failed nodes

Processing Distribution:

  • Read operations: Any node can serve data (distributed load)
  • Write operations: Distributed through consensus mechanism
  • Validation: All nodes participate in verification

3. Consensus Mechanisms (Decentralized Agreement)

Blockchain uses consensus protocols to achieve agreement on blockchain state without central coordinator:

Proof of Work (PoW):

  • Distribution Method:

    • Thousands of miners compete to solve cryptographic puzzles
    • Mining power distributed globally
    • Any miner can win the right to add next block
    • Processing power comes from independent miners
  • Decentralization Achieved:

    • No single miner controls more than 50% of hash power (in healthy network)
    • Geographic distribution across continents
    • Economic incentives prevent centralization
    • Anyone can join as a miner

Proof of Stake (PoS):

  • Distribution Method:

    • Validators selected based on staked cryptocurrency
    • Multiple validators participate in each consensus round
    • Random selection prevents predictability
    • Slashing mechanisms punish malicious behavior
  • Decentralization Achieved:

    • Lower barriers to entry (no expensive mining equipment)
    • Thousands of independent validators
    • Delegated staking distributes power further

Other Mechanisms:

  • PBFT: Multiple validators in committee
  • DPoS: Delegated validators elected by token holders
  • Raft/Paxos: Multiple nodes participate in voting

4. Distributed Transaction Processing

Transaction Lifecycle Distribution:

a) Transaction Creation:

  • Users create transactions on their local wallets
  • No central server processes user requests

b) Transaction Validation:

  • Every node validates:
    • Digital signatures
    • Account balances
    • Transaction format
    • Anti-double-spending checks
  • Validation distributed across thousands of nodes

c) Transaction Inclusion:

  • Miners/validators compete to include transactions in blocks
  • No single entity decides which transactions are processed
  • Market-based fee system determines priority

d) State Updates:

  • All nodes independently update their state
  • Deterministic execution ensures consistency
  • No central database to update

5. Distributed Mining/Validation Power

Mining Distribution (PoW):

  • Geographic Distribution:

    • Miners located across different countries
    • Different time zones ensure 24/7 operation
    • Regulatory diversity prevents single-jurisdiction control
  • Economic Distribution:

    • Multiple mining pools compete
    • Individual miners can join different pools
    • Pool hopping prevents single pool dominance
  • Hardware Distribution:

    • ASICs, GPUs distributed among participants
    • Total hash rate = sum of all individual miners
    • No single supercomputer; distributed computing power

Validation Distribution (PoS):

  • Stake distributed among many holders
  • Validator selection algorithms ensure randomness
  • Minimum stake requirements prevent centralization
  • Maximum validator limits prevent concentration

6. Data Storage and Redundancy

Full Nodes:

  • Store complete blockchain history
  • Independently verify all blocks and transactions
  • Thousands of full nodes globally
  • Each node = independent copy of entire database

Storage Distribution:

  • Blockchain size distributed across all full nodes
  • No central storage facility
  • Data loss requires all nodes to fail simultaneously
  • Geographic distribution protects against regional failures

Access Pattern:

  • Read access from nearest node
  • No central database bottleneck
  • Distributed query processing

7. Network Resilience Through Decentralization

Fault Tolerance:

  • Byzantine fault tolerance: System tolerates up to 1/3 malicious nodes (PBFT)
  • PoW: Tolerates < 50% malicious hash power
  • Node failures don't affect network operation
  • Self-healing network automatically routes around failures

Censorship Resistance:

  • No single entity can block transactions
  • Miners/validators are independent
  • Alternative nodes always available
  • Global distribution prevents government censorship

Attack Resistance:

  • 51% attack requires majority of computing power
  • Cost of attack exceeds potential gain (economic security)
  • Distributed nature makes coordination difficult
  • Detection and response distributed across network

8. Governance Decentralization

Decision Making:

  • Protocol changes require community consensus
  • No central authority dictates rules
  • Different stakeholders participate:
    • Developers propose improvements
    • Miners/validators signal support
    • Users choose which version to run
  • Fork-based governance (soft forks, hard forks)

Examples:

  • Bitcoin Improvement Proposals (BIPs)
  • Ethereum Improvement Proposals (EIPs)
  • Community voting on DAOs

Real-World Example: Bitcoin Network

Current Decentralization:

  • ~15,000+ full nodes worldwide
  • Mining pools across multiple countries
  • Hash rate: ~400 EH/s distributed globally
  • No single entity controls >20% hash rate
  • Processing capacity: Collective power of all miners
  • Anyone can become a node or miner

Processing Distribution:

  • Transaction validation: All full nodes
  • Block creation: Competitive mining
  • Network propagation: P2P gossip protocol
  • Storage: Thousands of independent nodes

Benefits of Decentralized Computing:

  1. Reliability: No downtime from single server failure
  2. Security: Attack requires compromising majority of network
  3. Trust: No need to trust central authority
  4. Transparency: All processing verifiable by anyone
  5. Scalability: Can add more nodes to increase capacity
  6. Censorship Resistance: No central control point
  7. Democratic: Equal participation opportunity

(b) What is consensus mechanism in blockchain? List and explain any four types of consensus mechanisms. (7 marks)

Consensus Mechanism in Blockchain:

A consensus mechanism is a fault-tolerant protocol used in blockchain networks to achieve agreement on a single data value or a single state of the network among distributed nodes or processes. It ensures all participants in the blockchain network agree on the current state of the distributed ledger.

Purpose of Consensus:

  • Ensure all nodes have the same copy of the blockchain
  • Prevent double-spending
  • Maintain integrity and security
  • Enable trustless operation (no need to trust other participants)
  • Determine which node gets to add the next block
  • Protect against malicious actors

Key Requirements:

  • Agreement: All honest nodes decide on the same value
  • Termination: All honest nodes eventually reach a decision
  • Validity: The agreed value must be proposed by at least one honest node
  • Fault Tolerance: System functions despite node failures or malicious actors

Four Major Types of Consensus Mechanisms:

1. Proof of Work (PoW)

Concept:
Miners compete to solve complex computational puzzles to earn the right to add the next block. The first miner to solve the puzzle broadcasts the solution, and other nodes verify and accept the block.

How It Works:

flowchart TD
    A[Transactions in Mempool] --> B[Miner Collects Transactions]
    B --> C[Create Block with Header]
    C --> D[Find Nonce: Hash Block Header]
    D --> E{Hash < Target?}
    E -->|No| F[Increment Nonce]
    F --> D
    E -->|Yes| G[Valid Block Found!]
    G --> H[Broadcast Block to Network]
    H --> I[Other Nodes Verify]
    I --> J{Valid?}
    J -->|Yes| K[Add Block to Chain]
    J -->|No| L[Reject Block]
    K --> M[Miner Receives Reward]

Process:

  1. Miners gather transactions from mempool
  2. Create candidate block with block header
  3. Search for nonce value such that:
    SHA-256(SHA-256(Block Header)) < Target
  4. Requires trying billions of nonce values
  5. First miner to find valid nonce wins
  6. Broadcasts block to network
  7. Other nodes verify and add to their chain
  8. Winner receives block reward + transaction fees

Key Parameters:

  • Difficulty: Adjusted periodically to maintain average block time
  • Hash Rate: Total computational power in network
  • Block Time: Bitcoin ~10 minutes, Ethereum ~12-14 seconds

Advantages:

  • Proven security (Bitcoin since 2009)
  • Highly decentralized
  • Simple to verify
  • Attack requires >50% of network hash power (very expensive)

Disadvantages:

  • Extremely energy-intensive
  • Slow transaction finality
  • Requires specialized hardware (ASICs)
  • Scalability limitations
  • Environmental concerns

Examples: Bitcoin, Ethereum (before merge), Litecoin, Bitcoin Cash


2. Proof of Stake (PoS)

Concept:
Validators are selected to create new blocks based on the amount of cryptocurrency they hold and are willing to "stake" (lock up) as collateral. Selection is typically random but weighted by stake size.

How It Works:

flowchart TD
    A[Validators Stake Cryptocurrency] --> B[Validator Selection Algorithm]
    B --> C[Selected Validator Proposes Block]
    C --> D[Other Validators Attest]
    D --> E{Sufficient Attestations?}
    E -->|Yes| F[Block Added to Chain]
    E -->|No| G[Block Rejected]
    F --> H[Validator Receives Rewards]
    H --> I[Distribute Transaction Fees]
    G --> J[Slashing Penalty if Malicious]

Process:

  1. Staking: Validators lock up cryptocurrency as stake
  2. Selection: Algorithm selects validator based on:
    • Stake amount
    • Coin age (how long coins have been staked)
    • Randomization factor
  3. Block Proposal: Selected validator creates and proposes block
  4. Attestation: Other validators verify and attest to block
  5. Finalization: Block added after sufficient attestations
  6. Rewards: Validator receives transaction fees and possibly new coins
  7. Slashing: Malicious validators lose staked funds

Selection Methods:

  • Random Selection: Weighted by stake size
  • Coin Age: Longer staking period = higher chance
  • Hybrid: Combination of factors

Security:

  • Malicious behavior results in slashed stake (economic penalty)
  • Must own significant portion of total supply to attack (expensive)
  • "Nothing at Stake" problem solved through slashing and checkpoints

Advantages:

  • Energy-efficient (99.95% less energy than PoW)
  • Faster block confirmation
  • Lower barriers to entry (no expensive hardware)
  • Economic incentives align with network security
  • More scalable than PoW

Disadvantages:

  • "Rich get richer" (large stakeholders earn more)
  • Initial distribution challenge
  • Less battle-tested than PoW
  • Requires solution to "nothing at stake" problem
  • Potential centralization if stake concentrates

Variants:

  • Pure PoS: Simple stake-based selection
  • Delegated PoS (DPoS): Token holders vote for delegates
  • Leased PoS: Users can lease their stake to validators

Examples: Ethereum 2.0, Cardano, Polkadot, Tezos


3. Practical Byzantine Fault Tolerance (PBFT)

Concept:
A consensus algorithm designed to work in asynchronous systems and tolerate Byzantine faults (malicious nodes). It uses a voting mechanism among a fixed set of validators to reach consensus through multiple rounds of communication.

How It Works:

sequenceDiagram
    participant C as Client
    participant P as Primary
    participant R1 as Replica 1
    participant R2 as Replica 2
    participant R3 as Replica 3

    C->>P: Request
    P->>P: Assign Sequence Number
    P->>R1: Pre-Prepare
    P->>R2: Pre-Prepare
    P->>R3: Pre-Prepare
    R1->>R2: Prepare
    R1->>R3: Prepare
    R2->>R1: Prepare
    R2->>R3: Prepare
    R3->>R1: Prepare
    R3->>R2: Prepare
    R1->>R2: Commit
    R1->>R3: Commit
    R2->>R1: Commit
    R2->>R3: Commit
    R3->>R1: Commit
    R3->>R2: Commit
    R1->>C: Reply
    R2->>C: Reply
    R3->>C: Reply

Process Phases:

Phase 1: Pre-Prepare

  • Client sends request to primary node
  • Primary assigns sequence number
  • Primary broadcasts PRE-PREPARE message to all replicas
  • Message contains: view number, sequence number, request

Phase 2: Prepare

  • Each replica validates PRE-PREPARE
  • If valid, broadcasts PREPARE message to all other replicas
  • Replica waits for 2f+1 matching PREPARE messages (f = max faulty nodes)
  • This ensures agreement on request ordering

Phase 3: Commit

  • After receiving 2f+1 PREPARE messages, replica broadcasts COMMIT
  • Replica waits for 2f+1 COMMIT messages
  • This ensures all honest nodes will execute the request

Phase 4: Reply

  • Replica executes the request
  • Sends REPLY to client
  • Client waits for f+1 matching replies
  • Ensures at least one honest node confirmed

Byzantine Fault Tolerance:

  • Can tolerate up to f Byzantine (malicious) nodes
  • Total nodes required: n ≥ 3f + 1
  • Example: To tolerate 1 faulty node, need 4 total nodes
  • To tolerate 10 faulty nodes, need 31 total nodes

Key Properties:

  • Safety: All honest nodes agree on the same order
  • Liveness: Clients eventually receive replies
  • Deterministic: No randomness involved
  • View Changes: Primary can be replaced if unresponsive

Advantages:

  • Low latency (milliseconds)
  • High throughput
  • Finality is deterministic (no probabilistic confirmation)
  • Energy-efficient
  • No mining or staking required

Disadvantages:

  • Limited scalability (communication overhead O(n²))
  • Requires known set of validators
  • Not suitable for open, permissionless networks
  • View-change protocol can be complex
  • Poor performance with large numbers of nodes

Examples: Hyperledger Fabric, Zilliqa, NEO


4. Delegated Proof of Stake (DPoS)

Concept:
Token holders vote to elect a limited number of delegates (also called witnesses or block producers) who are responsible for validating transactions and creating blocks. It's a democratic approach to consensus with elected representatives.

How It Works:

flowchart TD
    A[Token Holders] --> B[Vote for Delegates]
    B --> C[Top N Delegates Elected]
    C --> D[Elected Delegates Take Turns]
    D --> E[Delegate Creates Block]
    E --> F[Other Delegates Verify]
    F --> G{Block Valid?}
    G -->|Yes| H[Add to Blockchain]
    G -->|No| I[Reject Block]
    H --> J[Delegate Receives Reward]
    J --> K{Performance Good?}
    K -->|Yes| L[Delegate Reelected]
    K -->|No| M[Vote Out Delegate]
    M --> B

Process:

Phase 1: Voting

  • Token holders use their tokens to vote for delegates
  • Voting power proportional to token holdings
  • Can vote for multiple delegates
  • Can change votes at any time

Phase 2: Delegate Selection

  • Top N delegates with most votes are elected (typically 21-101)
  • Example: EOS has 21 block producers
  • Standby delegates wait as backups

Phase 3: Block Production

  • Elected delegates take turns producing blocks in a round-robin fashion
  • Each delegate gets a time slot (e.g., 3 seconds)
  • If delegate misses their slot, skipped
  • Predictable block production schedule

Phase 4: Validation

  • Other delegates validate the block
  • Requires majority approval (typically >2/3)
  • Quick finality due to small validator set

Phase 5: Rewards and Accountability

  • Block producers receive transaction fees and block rewards
  • Rewards often shared with voters
  • Poor-performing delegates voted out
  • Continuous monitoring by community

Delegation Features:

  • Stake-weighted voting: More tokens = more voting power
  • Liquid democracy: Can change vote anytime
  • Proxy voting: Can delegate voting power to others
  • Transparency: All votes publicly visible

Security Model:

  • Delegates have reputation at stake
  • Economic incentives align with network health
  • Quick replacement of malicious delegates
  • Token holders act as continuous audit

Advantages:

  • Very high throughput (thousands of TPS)
  • Fast block confirmation (~1-3 seconds)
  • Energy efficient
  • Democratic governance
  • Scalable
  • Low transaction fees

Disadvantages:

  • More centralized (limited number of delegates)
  • Whales can dominate voting
  • Potential for collusion among delegates
  • Voter apathy
  • Less Byzantine fault tolerant than PBFT
  • Trust required in elected delegates

Variants:

  • Leased Proof of Stake (LPoS): Similar but different terminology
  • Bonded Proof of Stake: Delegates must bond tokens

Examples: EOS, TRON, Lisk, BitShares, Steem


Comparison Table:

Feature PoW PoS PBFT DPoS
Energy Use Very High Low Very Low Very Low
Speed Slow (minutes) Moderate (seconds) Fast (milliseconds) Very Fast (seconds)
Scalability Limited Moderate Limited High
Decentralization High Moderate Low Moderate
Security Model Computational Economic Voting Delegated Economic
Entry Barrier High (hardware) Moderate (stake) Permission required Moderate (voting)
Finality Probabilistic Probabilistic/Absolute Absolute Near-absolute
Best For Public, permissionless Public blockchains Consortium Scalable public chains

Module III - Consensus Algorithms and Bitcoin — #### Question 15

Question 15

(a) Explain how Paxos protocol can be used to achieve consensus in crash fault tolerance. (7 marks)

Paxos Protocol:

Paxos is a family of consensus protocols designed for achieving agreement among distributed processes in a crash fault-tolerant (CFT) system. It handles node crashes and message delays but assumes nodes are honest (non-Byzantine). Developed by Leslie Lamport in 1998, it forms the foundation for many distributed systems.

Types of Nodes in Paxos:

  1. Proposers: Suggest values to be agreed upon
  2. Acceptors: Vote on proposed values
  3. Learners: Learn which value was chosen
  4. Client: Initiates requests

(Note: A single process can play multiple roles)

Paxos Basic Algorithm (Single Decree):

sequenceDiagram
    participant P as Proposer
    participant A1 as Acceptor 1
    participant A2 as Acceptor 2
    participant A3 as Acceptor 3
    participant L as Learner

    Note over P,A3: Phase 1a: Prepare
    P->>A1: Prepare(n)
    P->>A2: Prepare(n)
    P->>A3: Prepare(n)

    Note over P,A3: Phase 1b: Promise
    A1->>P: Promise(n, null)
    A2->>P: Promise(n, null)
    A3->>P: Promise(n, null)

    Note over P,A3: Phase 2a: Accept Request
    P->>A1: Accept(n, value)
    P->>A2: Accept(n, value)
    P->>A3: Accept(n, value)

    Note over P,A3: Phase 2b: Accepted
    A1->>L: Accepted(n, value)
    A2->>L: Accepted(n, value)
    A3->>L: Accepted(n, value)

    Note over L: Value Chosen!

Paxos Algorithm Phases:

Phase 1: Prepare Phase (Leader Election)

Step 1a - Prepare Request:

  • Proposer selects a unique proposal number n (higher than any it has used before)
  • Sends PREPARE(n) request to a majority (quorum) of acceptors
  • Proposal numbers must be unique and totally ordered

Step 1b - Promise Response:

  • Each acceptor receives PREPARE(n)
  • If n is higher than any proposal number the acceptor has seen:
    • Promises not to accept any proposals numbered less than n
    • Responds with PROMISE(n, v_accepted, n_accepted) where:
      • v_accepted: highest-numbered proposal value it has accepted (if any)
      • n_accepted: number of that proposal
    • If it has not accepted any proposal, responds with PROMISE(n, null, null)
  • If n is lower than a previously promised number:
    • Rejects the request or sends NACK

Proposer's Action after Phase 1:

  • Wait for responses from a majority of acceptors
  • If majority responds with promises:
    • If any acceptor returned a previously accepted value, proposer must use the value from the promise with the highest n_accepted
    • If no acceptor has accepted a value, proposer can choose any value
  • Proceed to Phase 2

Phase 2: Accept Phase (Value Agreement)

Step 2a - Accept Request:

  • Proposer sends ACCEPT(n, v) to acceptors where:
    • n: proposal number from phase 1
    • v: value selected based on phase 1 responses
  • Sends to same or larger quorum

Step 2b - Accepted Response:

  • Each acceptor receives ACCEPT(n, v)
  • If acceptor has not promised to a higher-numbered proposal:
    • Accepts the proposal
    • Records (n, v) as accepted value
    • Responds with ACCEPTED(n, v)
  • Otherwise:
    • Rejects (or ignores) the request

Learner Phase:

  • Learners receive ACCEPTED messages
  • When a learner observes that a majority of acceptors have accepted the same (n, v):
    • The value v is considered chosen
    • Consensus achieved!
    • Learners can use this value

Example Execution:

Scenario: Three acceptors (A1, A2, A3) need to agree on a value

Phase 1:

Proposer chooses n=1, sends PREPARE(1) to A1, A2, A3
A1 responds: PROMISE(1, null, null) [never accepted anything]
A2 responds: PROMISE(1, null, null)
A3 responds: PROMISE(1, null, null)
Majority received (3/3) ✓

Phase 2:

Proposer selects value = "X", sends ACCEPT(1, "X") to all
A1 accepts: ACCEPTED(1, "X")
A2 accepts: ACCEPTED(1, "X")
A3 accepts: ACCEPTED(1, "X")
Majority accepted (3/3) ✓
Value "X" is chosen!

Crash Fault Tolerance in Paxos:

Handling Node Crashes:

  1. Acceptor Crashes:

    • Paxos requires only a majority (quorum) to proceed
    • With N acceptors, can tolerate up to ⌊N/2⌋ crashes
    • Example: 5 acceptors can tolerate 2 failures (need 3 for majority)
    • System continues to function as long as majority is alive
  2. Proposer Crashes:

    • Another proposer can take over
    • New proposer starts with higher proposal number
    • Phase 1 will discover any previously accepted values
    • Ensures safety even if original proposer crashed mid-protocol
  3. Learner Crashes:

    • Doesn't affect consensus
    • When learner recovers, it can query acceptors for chosen value

Message Loss/Delay:

  • Proposer uses timeouts
  • If no response within timeout, retry with higher proposal number
  • Eventually, a proposal will succeed if enough nodes are alive

Safety Guarantees:

  1. Agreement: All non-faulty nodes agree on the same value
  2. Validity: Only proposed values can be chosen
  3. Termination: Eventually a value is chosen (if majority remains operational)
  4. Consistency: Once a value is chosen, it cannot change

Liveness Considerations:

  • Paxos guarantees safety always
  • Liveness (progress) guaranteed only if:
    • Majority of acceptors are non-faulty
    • Network eventually becomes reliable
    • No dueling proposers (can be solved with leader election)

Multi-Paxos (For Multiple Decisions):

For practical systems requiring multiple consensus rounds:

  • Elect a leader (using Paxos phase 1)
  • Leader proposes all subsequent values (skip phase 1)
  • More efficient for sequences of decisions
  • Used in systems like Google Chubby, Apache ZooKeeper

Advantages of Paxos:

  • Provably correct consensus algorithm
  • Tolerates crash failures effectively
  • No reliance on timing assumptions (works in asynchronous networks)
  • Forms basis for many production systems

Disadvantages:

  • Complex to understand and implement correctly
  • Requires 2 rounds of messages (prepare + accept)
  • Does not handle Byzantine (malicious) faults
  • Can have liveness issues with competing proposers

Applications:

  • Distributed databases (leader election, log replication)
  • Coordination services (ZooKeeper, Chubby)
  • Replicated state machines
  • Blockchain consortium networks (adapted versions)

(b) What is a blockchain wallet? Describe any four types of wallets. (7 marks)

Blockchain Wallet:

A blockchain wallet is a software program or hardware device that stores cryptographic keys (private and public keys) used to interact with a blockchain. It allows users to send, receive, and manage cryptocurrencies and digital assets.

Important Note: Wallets don't actually store cryptocurrencies. The cryptocurrency exists on the blockchain. Wallets store the private keys that prove ownership and provide access to these assets on the blockchain.

Key Components:

  1. Private Key: Secret key that proves ownership; used to sign transactions
  2. Public Key: Derived from private key; used to generate addresses
  3. Address: Public identifier where others can send cryptocurrency (like an account number)
  4. Backup/Recovery Phrase: 12-24 word mnemonic phrase to recover wallet

Functions of a Wallet:

  • Generate and store private/public key pairs
  • Create and sign transactions
  • Display balance and transaction history
  • Receive cryptocurrency (provide address)
  • Send cryptocurrency (create and broadcast transactions)

Four Types of Blockchain Wallets:

1. Hardware Wallets (Cold Storage)

Description:
Physical devices specifically designed to store private keys offline. They look like USB drives and provide the highest level of security for long-term storage of cryptocurrencies.

How It Works:

  • Private keys are generated and stored on the hardware device
  • Keys never leave the device, even when signing transactions
  • Device has a secure element (tamper-proof chip)
  • Transactions are signed inside the device
  • User confirms transactions using physical buttons on the device

Features:

  • Offline Storage: Private keys never exposed to internet-connected devices
  • Secure Chip: Military-grade security
  • Backup: Recovery seed phrase provided during setup
  • Multi-currency Support: Support for multiple cryptocurrencies
  • PIN Protection: Requires PIN to access
  • Physical Confirmation: Button press required to confirm transactions

Security Level: ⭐⭐⭐⭐⭐ (Highest)

Advantages:

  • Most secure option for storing large amounts
  • Protected from online hacks and malware
  • Immune to computer viruses
  • Can be used on compromised computers safely
  • Recovery possible with seed phrase

Disadvantages:

  • Costs money ($50-$200+)
  • Can be physically lost or damaged
  • Less convenient for frequent transactions
  • Requires safe physical storage
  • Learning curve for non-technical users

Examples:

  • Ledger Nano S/X
  • Trezor One/Model T
  • KeepKey
  • BitBox02

Best For: Long-term storage of significant cryptocurrency holdings, investors prioritizing security


2. Software Wallets (Hot Wallets)

Description:
Applications or programs installed on computers or smartphones. They provide convenience for daily transactions while maintaining reasonable security.

Subtypes:

a) Desktop Wallets:

  • Installed on personal computers
  • Private keys stored on computer hard drive
  • Examples: Electrum, Exodus, Bitcoin Core

b) Mobile Wallets:

  • Smartphone apps
  • Convenient for everyday transactions and in-store payments
  • Examples: Trust Wallet, Coinbase Wallet, MetaMask Mobile

c) Web Wallets:

  • Accessed through web browsers
  • Keys may be stored on user's device or provider's servers
  • Examples: MetaMask (browser extension), MyEtherWallet

How It Works:

  • Software generates and stores private keys
  • Keys encrypted with user password
  • Connected to internet for transaction broadcasting
  • Can scan QR codes for easy payments
  • Syncs with blockchain to show balance

Features:

  • Accessibility: Easy access from device
  • User Interface: Friendly GUI for managing assets
  • Transaction Speed: Quick sending and receiving
  • Multi-currency: Many support multiple blockchains
  • Integration: Can connect to DApps and DeFi protocols
  • Backup: Seed phrase or file backup

Security Level: ⭐⭐⭐ (Moderate)

Advantages:

  • Free to use
  • Convenient for frequent transactions
  • Easy to set up and use
  • Good for smaller amounts
  • Quick access to funds
  • Feature-rich (exchange integration, DApp browsing)

Disadvantages:

  • Vulnerable to malware and hacking (if device compromised)
  • Private keys on internet-connected device
  • Depends on device security
  • Risk of loss if device fails (without backup)

Best For: Daily transactions, smaller amounts, DApp interactions, beginners


3. Paper Wallets (Cold Storage)

Description:
Physical documents containing printed or written private and public keys, often as QR codes. Represents the most basic form of cold storage.

How It Works:

  • Private and public keys generated offline
  • Printed on paper (usually with QR codes)
  • Stored physically in safe location
  • To spend: Import private key into software wallet
  • Funds sent by scanning public key QR code

Structure:

┌──────────────────────────────┐
│      PAPER WALLET            │
├──────────────────────────────┤
│  Public Address (Receive):   │
│  [QR CODE]                   │
│  1A1zP1eP5QGefi2DMPTfTL...   │
├──────────────────────────────┤
│  Private Key (Spend):        │
│  [QR CODE]                   │
│  5Kb8kLf9zgWQnogidDA76MzP... │
└──────────────────────────────┘

Features:

  • Completely Offline: No electronic storage
  • Simple: No technology required
  • Permanent: Physical document
  • One-time Use: Best practice to sweep entire balance when spending

Security Level: ⭐⭐⭐⭐ (High, if stored properly)

Advantages:

  • Completely immune to online hacking
  • No hardware or software needed
  • Free to create
  • Can be created offline
  • Perfect for gifting cryptocurrency

Disadvantages:

  • Can be physically damaged (water, fire, fading)
  • Can be lost or stolen
  • Difficult to spend from (must import to software wallet)
  • Not suitable for frequent transactions
  • Quality of print matters (ink can fade)
  • Must be created securely (offline computer)
  • Risk if printer has memory or network connection

Creation Best Practices:

  • Use offline computer
  • Generate keys using trusted software
  • Use high-quality paper and ink
  • Make multiple copies
  • Store in waterproof, fireproof location
  • Consider lamination

Best For: Long-term storage, gifts, cold storage, backup


4. Custodial Wallets (Exchange Wallets)

Description:
Wallets where a third-party service (like a cryptocurrency exchange) controls and manages the private keys on behalf of the user. User accesses via username/password.

How It Works:

  • Exchange or service holds private keys
  • User logs in with credentials (username/password/2FA)
  • Transactions initiated through exchange interface
  • Exchange manages blockchain interactions
  • Similar to traditional banking model

Examples:

  • Coinbase
  • Binance
  • Kraken
  • Gemini
  • Crypto.com

Features:

  • Account-Based: Access via login credentials
  • Recovery: Password reset options
  • Integrated Trading: Buy/sell/trade directly
  • Fiat On-ramps: Purchase crypto with fiat currency
  • Insurance: Some exchanges insure deposits
  • Customer Support: Help desk available

Security Level: ⭐⭐ (Depends on provider)

Advantages:

  • User-friendly for beginners
  • No need to manage private keys
  • Account recovery options (forgot password)
  • Integrated trading and exchange features
  • Customer support available
  • Often insured (depending on exchange)
  • Convenient for trading

Disadvantages:

  • Not your keys, not your coins: User doesn't control funds
  • Exchange can freeze or restrict account
  • Centralization risk (exchange can be hacked)
  • Privacy concerns (KYC/AML requirements)
  • Counterparty risk (exchange bankruptcy)
  • Must trust third party
  • Transaction fees can be higher

Major Risk Example:

  • Mt. Gox collapse (2014): $450M lost
  • QuadrigaCX scandal (2019): $190M inaccessible
  • FTX collapse (2022): Billions lost

Best For: Beginners, active traders, those prioritizing convenience over control, users comfortable with third-party trust


Comparison Table:

Feature Hardware Wallet Software Wallet Paper Wallet Custodial Wallet
Private Key Control User User User Exchange
Security Highest Moderate High Depends on provider
Cost $50-200+ Free Free Free
Convenience Moderate High Low Highest
Internet Connection Offline Online Offline Online
Ease of Use Moderate High Low Very High
Best For Long-term storage Daily use Long-term backup Trading, beginners
Recovery Seed phrase Seed phrase Physical copy Password reset

Wallet Selection Guide:

Choose Hardware Wallet if:

  • Storing large amounts long-term
  • Security is top priority
  • Can afford the device cost

Choose Software Wallet if:

  • Need frequent access
  • Interacting with DApps/DeFi
  • Comfortable managing own keys
  • Storing moderate amounts

Choose Paper Wallet if:

  • Want simple cold storage
  • Long-term holding (years)
  • Gifting cryptocurrency
  • Backup solution

Choose Custodial Wallet if:

  • Complete beginner
  • Active trader
  • Prioritize convenience
  • Storing small amounts

Best Practice: Use a combination - hardware wallet for long-term savings, software wallet for daily use, paper wallet for backup.


Question 16

(a) Explain various steps in transaction validation with respect to Bitcoin. (7 marks)

Bitcoin Transaction Validation:

Transaction validation in Bitcoin is a critical process that ensures the integrity and security of the network. When a transaction is broadcast, it undergoes rigorous validation at multiple stages by different participants.

Bitcoin Transaction Structure (Simplified):

Transaction {
  Version: 1
  Input Count: N
  Inputs: [
    {
      Previous TX Hash: abc123...
      Output Index: 0
      ScriptSig: (signature + public key)
      Sequence: 0xffffffff
    }
  ]
  Output Count: M
  Outputs: [
    {
      Value: 0.5 BTC
      ScriptPubKey: (locking script)
    }
  ]
  Locktime: 0
}

Transaction Validation Process:

flowchart TD
    A[Transaction Created & Broadcast] --> B[Individual Node Receives TX]
    B --> C[Syntax Validation]
    C --> D{Valid Syntax?}
    D -->|No| E[Reject Transaction]
    D -->|Yes| F[Semantic Validation]
    F --> G{Passes Semantic Checks?}
    G -->|No| E
    G -->|Yes| H[UTXO Verification]
    H --> I{Inputs Exist & Unspent?}
    I -->|No| E
    I -->|Yes| J[Script Validation]
    J --> K{Scripts Execute Correctly?}
    K -->|No| E
    K -->|Yes| L[Double-Spend Check]
    L --> M{Already Spent?}
    M -->|Yes| E
    M -->|No| N[Add to Mempool]
    N --> O[Miner Selects TX for Block]
    O --> P[Include in Block]
    P --> Q[Block Validation by Network]
    Q --> R[Transaction Confirmed]

Validation Steps:

Step 1: Initial Syntax Validation

When a node receives a transaction, it first checks the basic structure:

Checks:

  • Valid Format: Transaction follows Bitcoin protocol format
  • Size Limits: Transaction size ≤ maximum block size
  • Output Values: No negative amounts, values within valid range (0 < value ≤ 21M BTC)
  • No Null Inputs: At least one input and one output
  • Input Count: Number of inputs matches declared count
  • Output Count: Number of outputs matches declared count

Validation Code (Conceptual):

if transaction_size > MAX_BLOCK_SIZE:
    return INVALID
if any_output_value < 0 or any_output_value > 21000000 * 100000000:
    return INVALID
if input_count == 0 or output_count == 0:
    return INVALID

Result: Transaction with invalid syntax is immediately rejected


Step 2: Semantic Validation

Validates the transaction's semantic properties:

Checks:

a) Coinbase Transaction Special Rules:

  • If coinbase (first TX in block): exactly one input
  • Coinbase input's previous output must be null
  • Coinbase scriptSig must be 2-100 bytes
  • Coinbase maturity: cannot be spent for 100 blocks

b) Transaction Amount Validation:

  • Sum of output values ≤ Sum of input values
  • Difference = transaction fee (given to miner)
  • Fee must be reasonable (prevent dust attacks)

c) Lock Time Validation:

  • Check if transaction can be included based on locktime
  • If locktime = 0: can be included immediately
  • If locktime > 0: compare with current block height or timestamp

Example:

Inputs:  0.8 BTC + 0.3 BTC = 1.1 BTC
Outputs: 0.5 BTC + 0.55 BTC = 1.05 BTC
Fee:     1.1 - 1.05 = 0.05 BTC ✓ (valid, fee goes to miner)

Step 3: UTXO (Unspent Transaction Output) Verification

Bitcoin uses the UTXO model. Each input must reference a valid unspent output.

Checks:

a) Input Existence:

  • Each input references a previous transaction output
  • Referenced transaction must exist in blockchain or mempool
  • Referenced output index must exist in that transaction

b) UTXO Status:

  • Referenced output must be unspent (not already consumed by another transaction)
  • Node checks its UTXO set (database of all unspent outputs)

c) Availability:

  • UTXO must not be spent in any transaction in the mempool
  • UTXO must not be spent in the blockchain

UTXO Set Lookup:

for each input in transaction:
    utxo_key = (previous_tx_hash, output_index)
    if utxo_key not in UTXO_set:
        return INVALID ("Input already spent or doesn't exist")
    utxo = UTXO_set[utxo_key]

Example:

Input references:
  TX: abc123..., Output Index: 0

Check UTXO set:
  TX abc123, Output 0: 0.8 BTC (status: unspent) ✓

Valid input!

Step 4: Cryptographic Signature Verification (Script Validation)

Bitcoin uses scripts for transaction authorization. The most critical validation step.

Script Execution:

Bitcoin uses a stack-based scripting language. Each transaction has:

  • ScriptSig (Unlocking Script): In transaction input, provides signature and public key
  • ScriptPubKey (Locking Script): In previous output, specifies spending conditions

Validation Process:

1. Combine ScriptSig (from new TX input) + ScriptPubKey (from referenced output)
2. Execute combined script
3. If final stack value = TRUE, input is authorized

Standard Transaction (P2PKH - Pay to Public Key Hash):

ScriptPubKey (Locking - in previous output):

OP_DUP OP_HASH160 <PubKeyHash> OP_EQUALVERIFY OP_CHECKSIG

ScriptSig (Unlocking - in new transaction):

<Signature> <PublicKey>

Combined Script Execution:

<Signature> <PublicKey> OP_DUP OP_HASH160 <PubKeyHash> OP_EQUALVERIFY OP_CHECKSIG

Step-by-Step Execution:

  1. Push Signature onto stack: [Signature]
  2. Push Public Key onto stack: [Signature, PublicKey]
  3. OP_DUP: Duplicate top item: [Signature, PublicKey, PublicKey]
  4. OP_HASH160: Hash top item: [Signature, PublicKey, Hash(PublicKey)]
  5. Push PubKeyHash: [Signature, PublicKey, Hash(PublicKey), PubKeyHash]
  6. OP_EQUALVERIFY: Verify top two items equal: [Signature, PublicKey] (if equal, continue; else fail)
  7. OP_CHECKSIG: Verify signature against public key and transaction data
    • If signature valid: Stack = [TRUE]
    • If signature invalid: Stack = [FALSE]

What OP_CHECKSIG Verifies:

  • Signature was created by private key corresponding to public key
  • Signature signs the transaction data (prevents modification)
  • Uses ECDSA (Elliptic Curve Digital Signature Algorithm)

Security Checks:

  • Signature Validity: Cryptographically valid
  • Ownership Proof: Only owner of private key can create valid signature
  • Transaction Integrity: Signature covers transaction details (prevents tampering)
  • Signature Hash Type: Specifies which parts of transaction are signed (SIGHASH_ALL, SIGHASH_SINGLE, etc.)

Step 5: Double-Spend Prevention

Critical check to prevent spending the same UTXO twice:

Checks:

a) Blockchain Check:

  • Verify referenced UTXO hasn't been spent in any confirmed transaction
  • Check blockchain history for the UTXO

b) Mempool Check:

  • Verify no other transaction in mempool spends the same UTXO
  • If conflicting transaction exists:
    • Both cannot be valid
    • Higher fee transaction usually prioritized
    • First-seen rule may apply

Double-Spend Detection:

UTXO: TX abc123, Output 0

Transaction A: Spends abc123:0 → Sends to Alice
Transaction B: Spends abc123:0 → Sends to Bob (different output)

These are conflicting! Only one can be included in blockchain.
Nodes will accept first-seen, or miner chooses based on fees.

Result: Only one transaction spending a UTXO can be confirmed


Step 6: Transaction Fee Validation

Fee Calculation:

Fee = Sum(Input Values) - Sum(Output Values)

Checks:

  • Fee ≥ 0 (implicit check - outputs can't exceed inputs)
  • Fee is reasonable (not absurdly high - warning to user)
  • Fee meets minimum relay threshold (very small fees may not be relayed)
  • Fee rate (satoshis per byte) determines priority

Example:

Inputs:  1.0 BTC
Outputs: 0.995 BTC
Fee:     0.005 BTC (500,000 satoshis)
Transaction Size: 250 bytes
Fee Rate: 500,000 / 250 = 2,000 sat/byte ✓ (very high priority)

Step 7: Mempool Addition

If transaction passes all validation steps:

Actions:

  • Add transaction to node's mempool (memory pool of unconfirmed transactions)
  • Relay transaction to connected peers (gossip protocol)
  • Mark referenced UTXOs as "pending spend" in local memory
  • Transaction awaits inclusion in a block

Mempool Management:

  • Transactions ordered by fee rate (priority)
  • Miners select highest-fee transactions for blocks
  • Conflicting transactions: Keep higher-fee version
  • Mempool size limits: Drop lowest-fee transactions if full

Step 8: Mining and Block Inclusion (Miner Validation)

Miner's Perspective:

  1. Select Transactions:

    • Choose transactions from mempool
    • Optimize for maximum fees within block size limit
    • Re-validate all transactions
  2. Create Block:

    • Include selected transactions
    • Add coinbase transaction (block reward + fees)
    • Calculate Merkle root of all transactions
  3. Validate Block:

    • Ensure total transaction size ≤ block limit
    • Verify all transactions are valid
    • No double-spends within the block

Step 9: Network Block Validation

When a block containing the transaction is mined:

Full Node Validation:

  1. Block Syntax: Valid block structure
  2. Proof of Work: Block hash meets difficulty target
  3. Block Size: Within limits
  4. First Transaction: Valid coinbase
  5. All Transactions: Re-validate every transaction in block
  6. Merkle Root: Matches calculated Merkle root
  7. Previous Block Hash: Valid chain link

Transaction Re-validation in Block:

  • All previous validation steps repeated
  • Must pass even if passed in mempool stage
  • Ensures no double-spend across mempool → block transition

Step 10: Confirmation

Confirmation Process:

  • 1 Confirmation: Transaction included in a block
  • 2-6 Confirmations: Subsequent blocks added on top
  • 6+ Confirmations: Generally considered final (standard for large amounts)

Why Multiple Confirmations:

  • Each additional block makes reorganization exponentially harder
  • 6 blocks ≈ 1 hour ≈ very high confidence
  • Small transactions: 1-3 confirmations sufficient
  • Large transactions: 6+ confirmations recommended

Finality:

  • After 6 confirmations, reversing transaction requires:
    • Recomputing 6 blocks worth of PoW
    • Having >50% of network hash power
    • Economically infeasible for honest miners

Summary of Validation Criteria:

Check Purpose
Syntax Valid format and structure
Semantic Logical correctness (amounts, locktime)
UTXO Existence Inputs reference real outputs
Unspent Status Inputs haven't been spent
Signatures Authorization to spend (ownership proof)
Double-Spend No conflicting transactions
Fees Reasonable transaction fee
Block Inclusion Miner validates before including
Network Consensus All nodes agree on validity
Confirmations Sufficient block depth for finality

Rejection Reasons:

A transaction can be rejected if:

  • Malformed structure
  • Negative or excessive output values
  • Inputs already spent (double-spend)
  • Invalid signatures
  • Non-existent inputs
  • Insufficient fee (may not be relayed)
  • Locktime not yet met

Result: Only valid, authorized, and non-conflicting transactions become part of the Bitcoin blockchain.


(b) Illustrate the working of Practical Byzantine Fault Tolerance (PBFT). (7 marks)

Practical Byzantine Fault Tolerance (PBFT):

PBFT is a consensus algorithm designed by Miguel Castro and Barbara Liskov in 1999 to provide Byzantine fault tolerance in asynchronous distributed systems. It enables a system to reach consensus even when some nodes are malicious or faulty (Byzantine faults).

Byzantine Fault: A node failure where the node behaves arbitrarily - it may lie, send conflicting information, or collude with other malicious nodes.

PBFT Fault Tolerance Guarantee:

To tolerate f Byzantine (faulty) nodes, the system requires:

Total Nodes (n) ≥ 3f + 1

Examples:

  • To tolerate 1 faulty node: need 4 total nodes
  • To tolerate 2 faulty nodes: need 7 total nodes
  • To tolerate 10 faulty nodes: need 31 total nodes

Why 3f+1?

  • Need f+1 nodes to respond (at least one honest)
  • Need 2f+1 nodes for majority (quorum)
  • Total: f (faulty) + 2f+1 (honest majority) = 3f+1

PBFT System Architecture:

Participants:

  1. Client: Initiates requests to the system
  2. Primary (Leader): Coordinates consensus for current view
  3. Replicas (Backups): Participate in consensus, backup the primary
  4. View: Configuration with a designated primary; changes if primary suspected faulty

System Properties:

  • State machine replication
  • All replicas start in the same state
  • Deterministic operations
  • All honest replicas execute operations in the same order

PBFT Consensus Protocol:

sequenceDiagram
    participant C as Client
    participant P as Primary (Replica 0)
    participant R1 as Replica 1
    participant R2 as Replica 2
    participant R3 as Replica 3

    Note over C,R3: REQUEST PHASE
    C->>P: REQUEST ⟨op, timestamp, client_id⟩
    C->>R1: REQUEST
    C->>R2: REQUEST
    C->>R3: REQUEST

    Note over C,R3: PRE-PREPARE PHASE
    P->>P: Assign sequence number n
    P->>R1: PRE-PREPARE ⟨view, n, digest(request)⟩
    P->>R2: PRE-PREPARE
    P->>R3: PRE-PREPARE

    Note over C,R3: PREPARE PHASE
    R1->>R2: PREPARE ⟨view, n, digest, replica_id⟩
    R1->>R3: PREPARE
    R1->>P: PREPARE
    R2->>R1: PREPARE
    R2->>R3: PREPARE
    R2->>P: PREPARE
    R3->>R1: PREPARE
    R3->>R2: PREPARE
    R3->>P: PREPARE
    P->>R1: PREPARE
    P->>R2: PREPARE
    P->>R3: PREPARE

    Note over R1,R3: Each waits for 2f PREPARE (quorum)
    Note over R1: Replica 1: PREPARED state

    Note over C,R3: COMMIT PHASE
    R1->>R2: COMMIT ⟨view, n, digest, replica_id⟩
    R1->>R3: COMMIT
    R1->>P: COMMIT
    R2->>R1: COMMIT
    R2->>R3: COMMIT
    R2->>P: COMMIT
    R3->>R1: COMMIT
    R3->>R2: COMMIT
    R3->>P: COMMIT
    P->>R1: COMMIT
    P->>R2: COMMIT
    P->>R3: COMMIT

    Note over R1,R3: Each waits for 2f+1 COMMIT (quorum)
    Note over R1: Replica 1: COMMITTED state

    Note over C,R3: EXECUTE & REPLY PHASE
    R1->>R1: Execute operation
    R1->>C: REPLY ⟨result, timestamp, view, replica_id⟩
    R2->>C: REPLY
    R3->>C: REPLY
    P->>C: REPLY

    Note over C: Client waits for f+1 matching replies
    Note over C: Operation complete!

PBFT Protocol Phases (Detailed):

Phase 0: REQUEST

Client Action:

  • Client sends request to primary and all replicas
  • Request: ⟨REQUEST, operation, timestamp, client_id⟩_σc
    • operation: The operation to execute
    • timestamp: Client's timestamp (prevents replay attacks)
    • σc: Client's signature

Why broadcast to all?

  • If primary is faulty, replicas can detect it didn't forward request
  • Ensures liveness even with faulty primary

Phase 1: PRE-PREPARE

Primary's Role:

  • Receives REQUEST from client
  • Assigns a sequence number n to the request
  • Broadcasts PRE-PREPARE message to all replicas

PRE-PREPARE Message:

⟨PRE-PREPARE, v, n, d⟩_σp
  • v: Current view number
  • n: Sequence number assigned to request
  • d: Digest (hash) of client's request
  • σp: Primary's signature

Replica's Validation:

Each replica accepts PRE-PREPARE if:

  1. Signature is valid
  2. Current view is v
  3. Hasn't accepted PRE-PREPARE for same view v and sequence n with different digest
  4. Sequence number n is within valid range [h, H] (watermark window)
  5. Digest d matches the request

If valid, replica enters PRE-PREPARED state and multicasts PREPARE.


Phase 2: PREPARE

Purpose: Ensure all non-faulty replicas agree on the order of requests within a view.

Replica Action:

  • After accepting PRE-PREPARE, multicasts PREPARE to all replicas

PREPARE Message:

⟨PREPARE, v, n, d, i⟩_σi
  • v: View number
  • n: Sequence number
  • d: Request digest
  • i: Replica ID
  • σi: Replica's signature

Collecting PREPARE Messages:

Each replica collects PREPARE messages. A replica is in PREPARED state for request when:

  1. Received valid PRE-PREPARE for (v, n, d)
  2. Received 2f matching PREPARE messages from different replicas (including itself)
    • All with same view v, sequence n, digest d
  3. Total: 1 PRE-PREPARE + 2f PREPARE = 2f+1 messages (quorum)

Why 2f+1?

  • In a system with 3f+1 nodes and f faulty nodes
  • 2f+1 ensures at least f+1 honest nodes agree
  • Majority agreement achieved
  • Even if f faulty nodes send conflicting messages

PREPARED state means: The replica knows this request will be ordered as sequence number n in view v across all honest replicas.


Phase 3: COMMIT

Purpose: Ensure requests are committed in the same order across view changes.

Replica Action:

  • After reaching PREPARED state, multicasts COMMIT to all replicas

COMMIT Message:

⟨COMMIT, v, n, d, i⟩_σi
  • Similar structure to PREPARE
  • Indicates replica commits to executing request at sequence n

Collecting COMMIT Messages:

Each replica collects COMMIT messages. A replica is in COMMITTED state when:

  1. Is in PREPARED state for (v, n, d)
  2. Receives 2f+1 matching COMMIT messages from different replicas (including itself)
    • All with same view v, sequence n, digest d

Why another round?

  • Ensures agreement persists across view changes
  • If view changes (primary fails), new primary knows which requests were committed
  • Prevents conflicting commits in different views

COMMITTED state means: The replica is certain that:

  • At least f+1 honest replicas have reached PREPARED state
  • The request will be executed in the same order by all honest replicas
  • Safe to execute the operation

Phase 4: EXECUTE & REPLY

Replica Action:

  • After reaching COMMITTED state
  • Executes the operation (if all previous sequence numbers executed)
  • Updates state
  • Sends REPLY to client

REPLY Message:

⟨REPLY, v, t, c, i, result⟩_σi
  • v: Current view
  • t: Timestamp from request
  • c: Client ID
  • i: Replica ID
  • result: Result of executing operation
  • σi: Replica's signature

Client Action:

  • Waits for f+1 matching REPLY messages
    • Same timestamp t
    • Same result
  • Why f+1? Ensures at least one reply from an honest replica
  • Operation complete!

Example Execution (n=4, f=1):

Setup:

  • 4 replicas: Primary (R0), R1, R2, R3
  • Can tolerate 1 faulty node

Scenario: Client wants to execute operation "TRANSFER $100"

Step 1: REQUEST

Client → All: REQUEST(op="TRANSFER $100", t=1234, client=Alice)

Step 2: PRE-PREPARE

Primary assigns n=5
Primary → R1, R2, R3: PRE-PREPARE(v=0, n=5, d=hash("TRANSFER $100"))

Step 3: PREPARE

R1 → All: PREPARE(v=0, n=5, d=hash(...), i=1)
R2 → All: PREPARE(v=0, n=5, d=hash(...), i=2)
R3 → All: PREPARE(v=0, n=5, d=hash(...), i=3)
Primary → All: PREPARE(v=0, n=5, d=hash(...), i=0)

Each replica receives 2f=2 matching PREPARE messages → PREPARED state ✓

Step 4: COMMIT

All replicas → All: COMMIT(v=0, n=5, d=hash(...), i=...)

Each replica receives 2f+1=3 matching COMMIT messages → COMMITTED state ✓

Step 5: EXECUTE

All replicas execute "TRANSFER $100"
R1 → Client: REPLY(result="Success")
R2 → Client: REPLY(result="Success")
R3 → Client: REPLY(result="Success")
Primary → Client: REPLY(result="Success")

Client receives f+1=2 matching replies → Operation complete! ✓


Handling Faulty Primary (View Change):

If the primary is faulty or suspected (timeout):

View Change Protocol:

  1. Suspicion: Replica suspects primary (timeout, invalid message)
  2. VIEW-CHANGE: Replica broadcasts VIEW-CHANGE message for new view v+1
  3. Quorum: New primary waits for 2f+1 VIEW-CHANGE messages
  4. NEW-VIEW: New primary broadcasts NEW-VIEW message with proof
  5. Resume: System continues with new primary in view v+1

View Change ensures:

  • Progress continues despite faulty primary
  • All committed operations preserved
  • Safety maintained across view changes

Byzantine Fault Scenarios:

Faulty Primary Examples:

  1. Doesn't send PRE-PREPARE: Timeout triggers view change
  2. Sends conflicting PRE-PREPARE: Replicas detect and reject
  3. Assigns wrong sequence number: Violates sequence rules, rejected
  4. Delays messages: Timeout triggers view change

Faulty Replica Examples:

  1. Sends conflicting PREPARE/COMMIT: Other replicas ignore inconsistent messages
  2. Doesn't send messages: Quorum requirements tolerate up to f silent nodes
  3. Sends wrong results: Client waits for f+1 matching replies, ignores outliers

System Resilience:

  • As long as ≥ 2f+1 nodes are honest, consensus achieved
  • Faulty nodes cannot prevent progress
  • Safety always guaranteed

PBFT Properties:

Safety:

  • If an honest replica commits request at sequence n, all honest replicas eventually commit same request at n
  • No two conflicting operations committed at same sequence number

Liveness:

  • System eventually processes all client requests
  • View changes ensure progress despite faulty primary

Complexity:

  • Message complexity: O(n²) - Each node sends message to all others
  • Communication rounds: 5 (Request, Pre-Prepare, Prepare, Commit, Reply)

Advantages of PBFT:

  1. Byzantine Fault Tolerance: Handles malicious nodes
  2. Deterministic Finality: No probabilistic confirmation
  3. Low Latency: Milliseconds to seconds
  4. Energy Efficient: No mining or PoW
  5. Proven Correctness: Mathematically proven safe

Disadvantages:

  1. Scalability: O(n²) communication limits to ~100 nodes
  2. Known Validator Set: Requires permissioned network
  3. View Change Complexity: Complex protocol
  4. High Communication Overhead: Many message rounds

Applications:

  • Hyperledger Fabric (permissioned blockchain)
  • Zilliqa (hybrid approach)
  • Consortium blockchains
  • Distributed databases requiring BFT

Module IV - Smart Contracts and Use Cases — #### Question 17

Question 17

(a) Give the significance of oracle in smart contracts. Elaborate different type of oracles deployed in blockchain. (7 marks)

Oracles in Smart Contracts:

An oracle is a third-party service or agent that provides smart contracts with external information from the outside world. Smart contracts on blockchain are isolated and deterministic - they can only access data stored on the blockchain. Oracles bridge this gap by feeding real-world data to smart contracts.

The Oracle Problem:

Blockchains are designed to be deterministic and isolated:

  • Cannot make HTTP requests
  • Cannot access external APIs
  • Cannot read data from outside the blockchain
  • Need consensus on external data

However, many smart contracts require external data:

  • Price feeds (ETH/USD for DeFi)
  • Weather data (for insurance contracts)
  • Sports scores (for betting contracts)
  • Random numbers (for gaming/NFTs)
  • IoT sensor readings

Oracles solve this by:

  1. Fetching data from external sources
  2. Verifying and validating the data
  3. Submitting data to the blockchain
  4. Making data available to smart contracts

Significance and Importance of Oracles:

1. Enable Real-World Interactions:

  • Smart contracts can react to real-world events
  • Bridges on-chain and off-chain worlds
  • Expands use cases beyond pure on-chain data

2. Data Feed for DeFi:

  • Price oracles critical for DeFi protocols
  • Lending platforms need accurate asset prices
  • DEXs use oracles for price discovery
  • Example: Chainlink provides price feeds for hundreds of assets

3. Trigger Contract Execution:

  • Automated execution based on external conditions
  • Insurance payouts triggered by flight delays
  • Agricultural insurance based on weather data

4. Random Number Generation:

  • Secure randomness for games, NFTs, lotteries
  • Blockchain is deterministic, can't generate true randomness
  • Oracles provide verifiable random functions (VRF)

5. Cross-Chain Communication:

  • Enable interoperability between blockchains
  • Verify events on other chains
  • Bridge protocols rely heavily on oracles

6. Computation Outsourcing:

  • Heavy computations done off-chain
  • Results fed back via oracles
  • Saves gas costs

7. IoT Integration:

  • Connect blockchain to IoT devices
  • Supply chain tracking with RFID/sensors
  • Real-time data from physical devices

Types of Oracles:

1. Software Oracles

Description:
Software oracles interact with online information sources and provide data to smart contracts. They fetch data from websites, servers, databases, and APIs.

Data Sources:

  • Exchange rates and prices
  • Flight information
  • Weather data
  • Public records
  • Sports scores
  • Social media data

How They Work:

External API → Oracle Node → Blockchain Smart Contract

Example Use Cases:

  • DeFi Price Feeds: Fetch ETH/USD price from exchanges
  • Insurance: Get flight delay information from airline APIs
  • Prediction Markets: Fetch event outcomes

Examples:

  • Chainlink nodes fetching price data
  • Band Protocol aggregating API data
  • API3 first-party oracles

Characteristics:

  • Most common type
  • Real-time or near-real-time data
  • Can be centralized (single source) or decentralized (multiple sources)
  • Trust model depends on oracle design

2. Hardware Oracles

Description:
Hardware oracles obtain data from the physical world using sensors and IoT devices. They convert real-world events into digital data that smart contracts can understand.

Data Sources:

  • IoT sensors (temperature, humidity, pressure)
  • RFID tags
  • Barcode scanners
  • GPS trackers
  • Biometric readers
  • Environmental monitors

How They Work:

Physical Sensor → Hardware Oracle → Blockchain → Smart Contract

Example Use Cases:

  • Supply Chain: RFID tags track product location and temperature
    • Pharmaceutical cold chain monitoring
    • Food safety compliance
  • Insurance: Temperature sensors for crop insurance
  • Asset Tracking: GPS trackers for logistics
  • Smart Cities: Environmental sensors for pollution monitoring

Examples:

  • Automotive telematics for car insurance
  • Weather stations for agricultural contracts
  • Smart meters for energy trading

Characteristics:

  • Bridges physical and digital worlds
  • Requires tamper-proof hardware
  • Often used with software oracles for verification
  • Critical for IoT + blockchain integration

Challenges:

  • Hardware can be compromised
  • Need for trusted execution environments (TEE)
  • Maintenance and calibration

3. Inbound Oracles

Description:
Inbound oracles bring external data INTO the blockchain. They fetch off-chain information and deliver it to smart contracts.

Data Flow:

External World → Inbound Oracle → Smart Contract

Functionality:

  • Queries external APIs
  • Aggregates data from multiple sources
  • Validates and formats data
  • Submits data on-chain via transactions

Example Scenarios:

  • Price oracle fetching cryptocurrency prices
  • Weather oracle getting temperature data
  • Sports oracle retrieving game scores
  • Random number oracle generating randomness

Use Cases:

  • DeFi: Price feeds for lending/borrowing
    • Example: Aave uses Chainlink to get asset prices
  • Insurance: Parametric insurance payouts
    • Example: Flight delay insurance checks flight status
  • Gaming: Random number generation for NFT minting
  • Prediction Markets: Final outcome determination

Most Common Type:

  • Majority of oracles are inbound
  • Enables smart contracts to consume external data
  • Essential for conditional logic based on real-world events

4. Outbound Oracles

Description:
Outbound oracles send data FROM the blockchain to the external world. They allow smart contracts to trigger actions in external systems.

Data Flow:

Smart Contract → Outbound Oracle → External System

Functionality:

  • Monitor blockchain for specific events
  • Listen to smart contract emissions
  • Trigger actions in off-chain systems
  • Send HTTP requests, emails, notifications

Example Scenarios:

  • Smart contract triggers bank payment
  • Contract completion sends notification to user
  • Blockchain event updates traditional database
  • Automated email/SMS based on contract state

Use Cases:

  • Payment Systems: Trigger fiat payment after on-chain event
    • Example: Bank transfer initiated by smart contract
  • Notifications: Alert users about contract execution
    • Email/SMS when payment received
  • Database Updates: Update enterprise systems with blockchain data
  • IoT Control: Smart contract unlocks physical door
    • Example: Rental payment triggers smart lock

Examples:

  • Banking integration for cross-border payments
  • Supply chain system updates
  • Enterprise resource planning (ERP) integration

Characteristics:

  • Less common than inbound oracles
  • Critical for blockchain-enterprise integration
  • Bridges Web3 to Web2
  • Enables smart contracts to affect real world

5. Centralized Oracles

Description:
Centralized oracles are controlled and operated by a single entity. One organization provides the data and operates the oracle infrastructure.

Architecture:

  • Single point of data provision
  • One entity responsible for accuracy
  • Direct control by operator

Characteristics:

  • Simple to implement
  • Fast data delivery
  • Low operational cost
  • Complete control by one party

Advantages:

  • Efficiency: Quick deployment and updates
  • Cost-effective: No need for consensus mechanism
  • Simplicity: Easy to integrate
  • Accountability: Clear responsibility

Disadvantages:

  • Single Point of Failure: If oracle fails, smart contract fails
  • Trust Required: Must trust the oracle operator
  • Manipulation Risk: Operator can provide false data
  • Centralization: Defeats blockchain's decentralization

Example:

  • Company A operates oracle feeding its own data
  • Provable (formerly Oraclize) early centralized oracle

Risk:

  • Oracle can become corrupt
  • Data can be manipulated
  • Creates dependency on third party

When to Use:

  • Low-stakes applications
  • When oracle operator is highly trusted
  • Internal/private blockchain applications
  • MVP/prototype development

6. Decentralized Oracles

Description:
Decentralized oracles aggregate data from multiple independent sources to provide consensus on external information. No single entity controls the data.

Architecture:

  • Multiple independent oracle nodes
  • Data aggregation from various sources
  • Consensus mechanism to determine final value
  • Byzantine fault tolerance

How They Work:

  1. Multiple nodes fetch data independently
  2. Each node reports data to smart contract
  3. Aggregation function determines consensus value (median, average, weighted)
  4. Outliers are filtered out
  5. Final value made available to contracts

Data Flow:

API 1 → Oracle Node 1 ↘
API 2 → Oracle Node 2 → Aggregation Contract → Smart Contract
API 3 → Oracle Node 3 ↗

Characteristics:

  • Multiple data sources
  • No single point of failure
  • Resistant to manipulation
  • More expensive (multiple transactions)

Advantages:

  • Reliability: Continues functioning if some nodes fail
  • Security: Difficult to manipulate (need to corrupt many nodes)
  • Trust-minimized: Don't need to trust single entity
  • Accuracy: Consensus filtering removes outliers

Disadvantages:

  • Cost: More expensive (multiple node fees)
  • Complexity: Harder to implement
  • Latency: Takes longer to reach consensus

Examples:

  • Chainlink: Leading decentralized oracle network
    • Multiple node operators
    • Reputation system
    • Off-chain aggregation
  • Band Protocol: Decentralized data oracle
  • DIA: Open-source oracle platform
  • UMA: Optimistic oracle with dispute resolution

Security Mechanisms:

  • Reputation Systems: Track node performance
  • Staking: Nodes stake collateral, slashed if dishonest
  • Aggregation: Statistical methods filter bad data
  • Crypto-Economic Security: Cost to attack > potential gain

Use Cases:

  • High-value DeFi protocols
  • Mission-critical applications
  • Public blockchain applications
  • Any application requiring trust-minimization

7. Contract-Specific vs. General-Purpose Oracles

Contract-Specific Oracles:

  • Custom-built for specific contract/application
  • Tailored data and format
  • Optimized for single use case
  • Example: Custom oracle for specific derivatives contract

General-Purpose Oracles:

  • Serve multiple contracts and applications
  • Standard data formats
  • Reusable infrastructure
  • Example: Chainlink price feeds used by hundreds of protocols

Comparison Table:

Type Data Flow Use Case Trust Model Examples
Software API → Contract Price feeds, data Varies Chainlink, Band
Hardware Sensor → Contract IoT, supply chain TEE/Trust RFID, GPS
Inbound External → Contract Most common Varies Price oracles
Outbound Contract → External Trigger actions Varies Payment systems
Centralized Single source Low stakes Trust operator Company oracles
Decentralized Multiple sources High stakes Distributed Chainlink

Oracle Security Considerations:

  1. Data Source Quality: Ensure reliable data sources
  2. Decentralization: Avoid single point of failure
  3. Cryptographic Verification: Verify data authenticity
  4. Reputation Systems: Track oracle node performance
  5. Economic Incentives: Align incentives with honest behavior
  6. Timeliness: Ensure data is fresh and up-to-date

Future of Oracles:

  • Cross-chain oracles for interoperability
  • AI-powered oracles
  • Decentralized compute oracles
  • Privacy-preserving oracles with zero-knowledge proofs

(b) Explain how blockchain can be applied in health sector. (7 marks)

Blockchain in Healthcare:

The healthcare industry faces significant challenges with data management, privacy, interoperability, and trust. Blockchain technology offers solutions to these problems through decentralization, transparency, security, and immutability.

Key Healthcare Challenges Addressed by Blockchain:

  • Fragmented patient data across providers
  • Lack of interoperability between systems
  • Data breaches and privacy violations
  • Drug counterfeiting and supply chain issues
  • Inefficient claims processing
  • Limited patient control over health data
  • Research data integrity issues

Applications of Blockchain in Healthcare:

1. Electronic Health Records (EHR) Management

Problem:

  • Patient records scattered across multiple providers
  • Lack of unified patient health history
  • Difficult to share records between hospitals
  • Privacy concerns with centralized databases
  • Patients lack control over their data

Blockchain Solution:

Architecture:

Patient → Blockchain (Access Control) → Hospital A
                                      → Hospital B
                                      → Clinic C
                                      → Pharmacy D

How It Works:

  1. Decentralized Storage: Patient records stored on distributed ledger
  2. Patient-Centric Model: Patient owns and controls access to their data
  3. Permissioned Access: Smart contracts manage who can view/update records
  4. Immutable Audit Trail: All access and changes logged permanently
  5. Interoperability: Standardized data format accessible across providers

Implementation:

  • Patient's identity on blockchain (self-sovereign identity)
  • Medical records hash stored on-chain
  • Actual records stored off-chain (IPFS or encrypted cloud)
  • Smart contracts control access permissions
  • Patients grant/revoke access via private keys

Benefits:

  • Unified Health History: Complete view of patient's medical history
  • Patient Empowerment: Patients control who accesses their data
  • Interoperability: Seamless data sharing between providers
  • Privacy: Encrypted data with granular access control
  • Audit Trail: Complete history of who accessed/modified records
  • Emergency Access: Critical info accessible during emergencies

Example Projects:

  • MedRec: MIT project for EHR management
  • Healthchain: Patient-controlled health records
  • Medicalchain: Secure health data exchange platform

Technical Components:

  • IPFS for distributed file storage
  • Ethereum or Hyperledger for permissioned blockchain
  • Smart contracts for access control logic
  • Encryption for data privacy

2. Drug Supply Chain and Anti-Counterfeiting

Problem:

  • Counterfeit drugs: $200B+ global problem
  • Lack of supply chain transparency
  • Difficulty tracking drug provenance
  • Expired/recalled drug circulation
  • Inefficient recalls

Blockchain Solution:

Drug Tracking Process:

Manufacturer → Distributor → Wholesaler → Pharmacy → Patient
     |              |             |            |
     └──────────────┴─────────────┴────────────┴───→ Blockchain Ledger

How It Works:

  1. Drug Registration: Manufacturer registers drug on blockchain with unique ID
  2. Batch Tracking: Each batch gets blockchain identifier
  3. Chain of Custody: Every transfer recorded on blockchain
  4. Verification: QR code/RFID scan at each stage
  5. Patient Verification: Patient can verify drug authenticity before consumption

Smart Contract Logic:

contract DrugSupplyChain {
    struct Drug {
        bytes32 drugId;
        string name;
        address manufacturer;
        uint256 manufactureDate;
        uint256 expiryDate;
        address currentOwner;
        DrugState state;
    }

    enum DrugState { Manufactured, InTransit, AtDistributor, AtPharmacy, Sold }

    mapping(bytes32 => Drug) public drugs;
    mapping(bytes32 => address[]) public drugHistory;

    function registerDrug(...) public onlyManufacturer { }
    function transferDrug(...) public { }
    function verifyDrug(...) public view returns (bool) { }
}

Benefits:

  • Authenticity Verification: Customers verify genuine products
  • Supply Chain Transparency: Complete drug journey visible
  • Recall Efficiency: Rapid identification of affected batches
  • Counterfeit Prevention: Impossible to add fake drugs to chain
  • Regulatory Compliance: Automated compliance verification
  • Temperature Monitoring: IoT sensors record storage conditions

Example Projects:

  • MediLedger: Pharmaceutical supply chain on blockchain
  • Modum.io: Temperature monitoring for pharma logistics
  • Chronicled: FDA compliance for drug tracking

3. Clinical Trials and Research Data Management

Problem:

  • Data manipulation in clinical trials
  • Lack of transparency in trial results
  • Patient recruitment challenges
  • Difficult to verify research integrity
  • Selective publication bias

Blockchain Solution:

How It Works:

  1. Trial Registration: Trial protocols registered on blockchain (immutable)
  2. Data Collection: Patient data encrypted and hashed on blockchain
  3. Timestamping: All data entries timestamped and linked
  4. Smart Contracts: Automated patient consent management
  5. Results Publication: Trial results committed to blockchain

Benefits:

  • Data Integrity: Immutable record prevents tampering
  • Transparency: All trial data and changes visible
  • Patient Consent: Smart contracts enforce consent rules
  • Research Reproducibility: Complete data provenance
  • Participant Recruitment: Blockchain-based patient matching
  • IP Protection: Timestamp proof for research discoveries

Example Use Cases:

  • COVID-19 vaccine trial data on blockchain
  • Decentralized clinical trial platforms
  • Research data sharing among institutions

4. Insurance Claims Processing

Problem:

  • Lengthy claim verification process
  • High administrative costs
  • Fraud and duplicate claims
  • Lack of transparency
  • Inefficient communication between parties

Blockchain Solution:

Claim Processing Flow:

Patient → Treatment → Healthcare Provider
                           ↓
                   Submit Claim to Blockchain
                           ↓
              Smart Contract Verification
                           ↓
        Automated Payout to Provider (if valid)

Smart Contract Automation:

  • Eligibility verification automated
  • Claims validated against policy terms
  • Payments triggered automatically
  • Fraud detection through pattern analysis
  • Real-time settlement

Benefits:

  • Speed: Instant/near-instant claim processing
  • Cost Reduction: Eliminate intermediaries
  • Fraud Prevention: Immutable record prevents duplicate claims
  • Transparency: All parties see claim status
  • Automated Adjudication: Smart contracts enforce policy terms

Example:

  • Health insurance claim:
    • Patient treatment recorded on blockchain
    • Insurance smart contract verifies coverage
    • If conditions met, automatic payment to provider
    • No manual paperwork needed

5. Patient Identity and Credential Verification

Problem:

  • Identity theft in healthcare
  • Fraudulent insurance claims
  • Difficulty verifying medical credentials
  • Fragmented identity systems

Blockchain Solution:

Self-Sovereign Identity (SSI):

  • Patients control digital identity
  • Decentralized identifiers (DIDs)
  • Verifiable credentials for certifications
  • Privacy-preserving authentication

For Medical Professionals:

  • Credential Verification:
    • Medical degrees on blockchain
    • License verification
    • Continuing education credits
    • Work history
  • Benefits:
    • Instant verification by employers
    • Prevents fake credentials
    • Portable professional identity

For Patients:

  • Unique patient identifier across systems
  • Prevents medical identity theft
  • Emergency access to critical info
  • Insurance verification simplified

6. Telemedicine and Remote Patient Monitoring

Blockchain Application:

  • Secure storage of remote consultation records
  • IoT medical device data verification
  • Automated prescription generation
  • Cross-border telemedicine compliance

How It Works:

  • Patient health data from wearables → Blockchain
  • Smart contracts analyze data
  • Automatic alerts to doctors if thresholds exceeded
  • Immutable record of all consultations

7. Medical Equipment and Asset Management

Use Cases:

  • Track medical equipment utilization
  • Maintenance scheduling via smart contracts
  • Equipment sharing between hospitals
  • Preventive maintenance automation

Benefits:

  • Reduced equipment downtime
  • Optimized asset utilization
  • Cost savings through sharing economy
  • Compliance with maintenance regulations

8. Healthcare Payments and Billing

Blockchain Applications:

  • Automated billing based on services rendered
  • Real-time payment settlement
  • Transparent pricing
  • Reduction in billing errors

Smart Contract Example:

IF patient receives service X
AND insurance covers service X
THEN auto-pay provider Y amount
AND update patient's deductible

Technical Architecture for Healthcare Blockchain:

Blockchain Choice:

  • Permissioned Blockchains: Hyperledger Fabric, R3 Corda

    • HIPAA compliance easier
    • Controlled access
    • Better performance
    • Privacy features
  • Public Blockchains: Ethereum (with privacy layers)

    • Greater decentralization
    • More transparent
    • Requires additional privacy solutions

Privacy Solutions:

  • Zero-knowledge proofs for data privacy
  • Off-chain storage with on-chain hashes
  • Encryption layers
  • Permissioned data access

Interoperability Standards:

  • FHIR (Fast Healthcare Interoperability Resources)
  • HL7 standards compliance
  • Standardized data formats

Benefits Summary:

Aspect Benefit
Data Security Encrypted, distributed storage resistant to breaches
Patient Privacy Granular control, consent management
Interoperability Standardized data sharing across systems
Data Integrity Immutable records prevent tampering
Transparency Audit trails for accountability
Cost Efficiency Reduced administrative overhead
Patient Empowerment Ownership of health data

Challenges and Considerations:

  1. Scalability: Large medical datasets require significant storage
  2. Regulatory Compliance: HIPAA, GDPR compliance critical
  3. Adoption: Requires industry-wide coordination
  4. Legacy Systems: Integration with existing infrastructure
  5. Cost: Initial implementation expensive
  6. Technical Expertise: Shortage of blockchain healthcare specialists
  7. Standardization: Need for industry-wide standards

Real-World Examples:

  • Estonia: National health records on blockchain
  • FDA: Tracking pharmaceutical supply chain
  • IBM Watson Health: Healthcare data exchange
  • Guardtime: Health record security

Future Outlook:

  • Integration with AI for predictive healthcare
  • Genomic data management on blockchain
  • Global health data marketplaces
  • Decentralized medical research collaborations

Question 18

(a) What are DApps? Explain the design aspects of DApps. (7 marks)

Decentralized Applications (DApps):

A Decentralized Application (DApp) is an application that runs on a decentralized network (typically blockchain) rather than on centralized servers. DApps combine smart contracts (backend logic) with a user interface (frontend), operating without central control or ownership.

Definition:

A DApp must meet these criteria:

  1. Open Source: Code is publicly available
  2. Decentralized: Runs on blockchain, data stored on distributed ledger
  3. Incentivized: Uses cryptocurrency tokens for validation/rewards
  4. Protocol/Algorithm: Generates tokens and has consensus mechanism

DApp vs Traditional App:

Feature Traditional App DApp
Backend Centralized server Blockchain (smart contracts)
Frontend Web/mobile interface Web/mobile interface
Data Storage Centralized database Distributed ledger + decentralized storage
Control Company/organization No single entity
Downtime Possible (server failure) Virtually zero (distributed)
Censorship Possible Resistant
Trust Required (in operator) Trustless (code is law)
Updates Centralized control Community consensus

Design Aspects of DApps:

1. Architecture Design

Three-Tier DApp Architecture:

┌─────────────────────────────────────┐
│      FRONTEND (Presentation)        │
│   HTML/CSS/JS, React, Vue, etc.     │
│   Connects via Web3.js/Ethers.js    │
└──────────────┬──────────────────────┘
               │
┌──────────────▼──────────────────────┐
│    BLOCKCHAIN LAYER (Backend)       │
│   Smart Contracts (Business Logic)  │
│   Deployed on Ethereum/other chain  │
└──────────────┬──────────────────────┘
               │
┌──────────────▼──────────────────────┐
│    STORAGE LAYER (Data)             │
│   On-chain: State variables         │
│   Off-chain: IPFS, Swarm, Arweave   │
└─────────────────────────────────────┘

Component Breakdown:

a) Frontend (User Interface):

  • Built with traditional web technologies (HTML, CSS, JavaScript)
  • Frameworks: React, Vue.js, Angular
  • Communicates with blockchain via Web3 libraries
  • User-friendly interface for complex blockchain operations

b) Backend (Smart Contracts):

  • Business logic written in Solidity, Vyper, Rust
  • Deployed on blockchain (Ethereum, Solana, etc.)
  • Executes deterministically
  • State stored on blockchain

c) Storage:

  • On-Chain Storage:
    • Critical data and state
    • Expensive (gas costs)
    • Used for essential data only
  • Off-Chain Storage:
    • Large files, media, documents
    • IPFS (InterPlanetary File System)
    • Swarm, Arweave, Filecoin
    • Hash/reference stored on-chain

2. Smart Contract Design

Principles:

a) Modularity:

  • Separate contracts for different functions
  • Library contracts for reusable code
  • Upgradeable contract patterns

b) Security-First:

  • Reentrancy guards
  • Access control mechanisms
  • Input validation
  • Safe math operations (prevent overflow)

c) Gas Optimization:

  • Minimize storage operations
  • Use events for logging
  • Optimize loops and data structures
  • Batch operations where possible

d) Upgradeability:

  • Proxy patterns for contract upgrades
  • Migration strategies
  • Version management

Example Smart Contract Structure:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract DAppBackend {
    // State variables
    address public owner;
    mapping(address => uint256) public balances;

    // Events for frontend listening
    event BalanceUpdated(address indexed user, uint256 newBalance);

    // Modifiers for access control
    modifier onlyOwner() {
        require(msg.sender == owner, "Not authorized");
        _;
    }

    // Constructor
    constructor() {
        owner = msg.sender;
    }

    // Core functions
    function updateBalance(uint256 amount) public {
        balances[msg.sender] += amount;
        emit BalanceUpdated(msg.sender, balances[msg.sender]);
    }
}

3. Frontend Design

Web3 Integration:

Wallet Connection:

// Connect to MetaMask
async function connectWallet() {
    if (window.ethereum) {
        try {
            const accounts = await window.ethereum.request({
                method: 'eth_requestAccounts'
            });
            console.log('Connected:', accounts[0]);
        } catch (error) {
            console.error('User rejected connection');
        }
    } else {
        alert('Please install MetaMask!');
    }
}

Smart Contract Interaction:

// Using ethers.js
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
const contract = new ethers.Contract(contractAddress, abi, signer);

// Read from contract
const balance = await contract.balances(userAddress);

// Write to contract
const tx = await contract.updateBalance(100);
await tx.wait(); // Wait for confirmation

Design Considerations:

  • Responsive UI for mobile/desktop
  • Loading states for blockchain transactions
  • Transaction confirmation feedback
  • Error handling for failed transactions
  • Gas estimation display
  • Network switching support (mainnet/testnet)

4. Data Management Design

On-Chain vs Off-Chain Storage:

On-Chain (Blockchain):

  • Store:
    • Critical state (balances, ownership)
    • References/hashes to off-chain data
    • Transaction history
    • Smart contract logic
  • Expensive: Costs gas for every write
  • Permanent: Immutable once written

Off-Chain (IPFS/Swarm/Arweave):

  • Store:
    • Large files (images, videos)
    • Metadata (JSON files)
    • Documents
    • NFT content
  • Cheap: No gas costs
  • Reference: Hash stored on-chain

Hybrid Approach:

1. Upload file to IPFS
2. Receive IPFS hash: QmX...abc
3. Store hash on blockchain
4. Frontend retrieves file using hash

Example:

contract NFT {
    mapping(uint256 => string) public tokenURIs; // IPFS hashes

    function mint(uint256 tokenId, string memory ipfsHash) public {
        tokenURIs[tokenId] = ipfsHash;
        // Actual image stored on IPFS, hash stored on-chain
    }
}

5. User Experience (UX) Design

Challenges:

  • Transaction delays (block confirmation)
  • Gas fees complexity
  • Wallet management
  • Technical blockchain concepts

Solutions:

a) Transaction Feedback:

  • Show transaction status (pending/confirmed/failed)
  • Estimate confirmation time
  • Provide transaction hash for tracking
  • Fallback options if transaction fails

b) Gas Management:

  • Display estimated gas costs in USD
  • Allow users to adjust gas price
  • Show transaction priority options (slow/medium/fast)
  • Batch transactions to reduce costs

c) Simplified Wallet Integration:

  • One-click wallet connection
  • Support multiple wallets (MetaMask, WalletConnect, Coinbase Wallet)
  • Social recovery options
  • Abstraction of technical details

d) Progressive Disclosure:

  • Hide complex blockchain details
  • Show advanced options for power users
  • Helpful tooltips and guides
  • Onboarding tutorials

6. Security Design

Smart Contract Security:

  • Formal verification
  • Comprehensive testing (unit tests, integration tests)
  • Security audits by third parties
  • Bug bounty programs
  • Gradual rollout with limits

Frontend Security:

  • Verify contract addresses
  • Validate user inputs
  • Protect against phishing
  • Secure key management guidance
  • HTTPS for all communications

Access Control Patterns:

// Role-based access control
contract AccessControlled {
    mapping(address => bool) public admins;

    modifier onlyAdmin() {
        require(admins[msg.sender], "Not admin");
        _;
    }

    function sensitiveFunction() public onlyAdmin {
        // Only admins can call
    }
}

7. Scalability Design

Layer 1 Optimizations:

  • Efficient data structures
  • Minimize storage writes
  • Use events instead of storage where possible
  • Optimize contract size

Layer 2 Solutions:

  • State channels (payment channels)
  • Sidechains (Polygon, Optimism)
  • Rollups (Optimistic, ZK-rollups)
  • Plasma chains

Example Architecture:

Main Chain (Ethereum)
    ↓ Periodic settlements
Layer 2 (Polygon)
    ↓ Faster, cheaper transactions
DApp Frontend

8. Economic Design (Tokenomics)

Token Utility:

  • Governance (voting on proposals)
  • Access (pay to use features)
  • Rewards (incentivize participation)
  • Staking (lock tokens for benefits)

Token Distribution:

  • Team allocation
  • Community rewards
  • Liquidity mining
  • Public sale
  • Treasury reserve

Sustainability:

  • Transaction fees generate revenue
  • Token burning mechanisms
  • Staking rewards balance

9. Governance Design

On-Chain Governance:

  • Proposal system
  • Voting mechanisms
  • Execution of approved changes
  • Transparent decision-making

Example Flow:

1. Community member creates proposal
2. Token holders vote (voting power = tokens held)
3. Proposal passes if >50% vote yes
4. Smart contract automatically executes change

Governance Models:

  • Token-based: 1 token = 1 vote
  • Quadratic voting: Prevents whale dominance
  • Delegated voting: Delegate votes to experts
  • Time-locked voting: Longer locks = more weight

10. Interoperability Design

Cross-Chain Communication:

  • Bridge contracts
  • Oracle integration (Chainlink)
  • Multi-chain deployment
  • Chain-agnostic design

API Integration:

  • The Graph (indexing blockchain data)
  • Moralis (backend infrastructure)
  • Infura/Alchemy (node providers)

Complete DApp Design Workflow:

1. Planning Phase:

  • Define use case and requirements
  • Choose blockchain platform
  • Plan smart contract architecture
  • Design token economics

2. Development Phase:

  • Write and test smart contracts
  • Deploy to testnet
  • Develop frontend
  • Integrate Web3 libraries

3. Testing Phase:

  • Unit tests for contracts
  • Integration testing
  • Security audit
  • User acceptance testing

4. Deployment Phase:

  • Deploy contracts to mainnet
  • Deploy frontend to IPFS/traditional hosting
  • Set up monitoring and analytics

5. Maintenance Phase:

  • Monitor contract interactions
  • Community management
  • Iterative improvements
  • Bug fixes and updates

Example DApp Categories:

1. DeFi:

  • Uniswap (DEX)
  • Aave (Lending)
  • Compound (Borrowing)

2. Gaming:

  • Axie Infinity
  • Decentraland
  • Gods Unchained

3. Social:

  • Steemit (Blogging)
  • Lens Protocol (Social graph)

4. Marketplaces:

  • OpenSea (NFTs)
  • Rarible (NFT marketplace)

Best Practices Summary:

  1. Security First: Audit contracts, test extensively
  2. User-Centric Design: Abstract blockchain complexity
  3. Gas Optimization: Minimize costs for users
  4. Decentralization: Avoid single points of failure
  5. Transparency: Open-source code, clear documentation
  6. Scalability: Plan for growth, use Layer 2
  7. Community: Build engaged user base
  8. Compliance: Consider regulatory requirements

(b) Illustrate with a use case, the application of blockchain technology in finance sector. (7 marks)

Blockchain in Finance: Comprehensive Use Case

Use Case: Cross-Border Remittances and Payments

Problem Statement:

Traditional cross-border money transfers face significant challenges:

  • High fees (5-10% average, $30B+ annually in fees globally)
  • Slow processing (3-5 business days)
  • Multiple intermediaries (correspondent banks)
  • Lack of transparency (hidden fees, exchange rates)
  • Limited access (1.7B unbanked globally)
  • Fraud and errors
  • Settlement risk
  • Currency exchange complexity

Example Traditional Flow:

Sender (USA) 
   → Sending Bank
      → Correspondent Bank 1
         → Correspondent Bank 2
            → Receiving Bank
               → Recipient (Philippines)

Time: 3-5 days
Cost: $25-50 + 3-5% exchange rate markup
Fees split among all intermediaries

Blockchain Solution: Decentralized Remittance Platform

Architecture:

flowchart LR
    A[Sender USA] -->|Deposits USD| B[Blockchain Platform]
    B -->|Smart Contract| C[Stablecoin Conversion]
    C -->|USDC Transfer| D[Blockchain Ledger]
    D -->|Smart Contract| E[Local Currency Conversion]
    E -->|PHP Payout| F[Recipient Philippines]

    G[Liquidity Pools] -.->|Exchange Rate| C
    G -.->|Exchange Rate| E

Components:

  1. User Interface (Web/Mobile App)
  2. Smart Contracts (Transfer Logic)
  3. Stablecoins (Value Transfer)
  4. Blockchain Network (Settlement Layer)
  5. Liquidity Pools (Currency Exchange)
  6. Fiat On/Off Ramps (Local Partners)

Step-by-Step Process:

Phase 1: Sender Initiates Transfer

Step 1: Account Creation and KYC

  • User registers on platform
  • Completes digital KYC verification
  • Identity verified using blockchain-based credentials
  • Wallet automatically created

Step 2: Deposit Funds

  • Sender deposits $100 USD
  • Bank transfer or card payment
  • Funds converted to stablecoin (USDC)
  • Smart contract interaction:
contract RemittancePlatform {
    event FundsDeposited(
        address indexed sender,
        uint256 amount,
        string currency
    );

    function depositFunds(uint256 usdAmount) public {
        // Convert USD to USDC stablecoin
        uint256 usdcAmount = usdAmount * 1e6; // USDC has 6 decimals
        usdc.transferFrom(msg.sender, address(this), usdcAmount);

        emit FundsDeposited(msg.sender, usdcAmount, "USDC");
    }
}

Phase 2: Cross-Border Transfer on Blockchain

Step 3: Initiate Transfer

  • Sender enters recipient details:
    • Recipient wallet address OR phone number
    • Amount to send: $100
    • Destination currency: PHP (Philippine Peso)
  • Platform calculates:
    • Exchange rate: 1 USD = 56 PHP (real-time from oracle)
    • Network fee: $0.50
    • Platform fee: 1% = $1
    • Recipient receives: 5,488 PHP

Step 4: Smart Contract Execution

contract CrossBorderTransfer {
    using Chainlink for AggregatedProxy; // Price oracle

    struct Transfer {
        address sender;
        address recipient;
        uint256 amount;
        string sourceCurrency;
        string destinationCurrency;
        uint256 exchangeRate;
        uint256 timestamp;
        TransferStatus status;
    }

    enum TransferStatus { Pending, Completed, Failed }

    mapping(bytes32 => Transfer) public transfers;

    event TransferInitiated(
        bytes32 indexed transferId,
        address indexed sender,
        address indexed recipient,
        uint256 amount
    );

    event TransferCompleted(
        bytes32 indexed transferId,
        uint256 finalAmount
    );

    function initiateTransfer(
        address recipient,
        uint256 usdcAmount,
        string memory destCurrency
    ) public returns (bytes32) {
        // Generate unique transfer ID
        bytes32 transferId = keccak256(
            abi.encodePacked(msg.sender, recipient, block.timestamp)
        );

        // Get current exchange rate from oracle
        uint256 exchangeRate = getExchangeRate("USD", destCurrency);

        // Calculate fees
        uint256 networkFee = 0.5 * 1e6; // $0.50 in USDC
        uint256 platformFee = (usdcAmount * 100) / 10000; // 1%
        uint256 totalFees = networkFee + platformFee;

        // Amount after fees
        uint256 netAmount = usdcAmount - totalFees;

        // Create transfer record
        transfers[transferId] = Transfer({
            sender: msg.sender,
            recipient: recipient,
            amount: netAmount,
            sourceCurrency: "USDC",
            destinationCurrency: destCurrency,
            exchangeRate: exchangeRate,
            timestamp: block.timestamp,
            status: TransferStatus.Pending
        });

        // Transfer USDC to escrow
        usdc.transferFrom(msg.sender, address(this), usdcAmount);

        emit TransferInitiated(transferId, msg.sender, recipient, netAmount);

        return transferId;
    }

    function completeTransfer(bytes32 transferId) internal {
        Transfer storage t = transfers[transferId];
        require(t.status == TransferStatus.Pending, "Already processed");

        // Convert to destination currency amount
        uint256 finalAmount = (t.amount * t.exchangeRate) / 1e6;

        // Transfer to recipient
        usdc.transfer(t.recipient, t.amount);

        t.status = TransferStatus.Completed;

        emit TransferCompleted(transferId, finalAmount);
    }
}

Step 5: Blockchain Transaction

  • Smart contract executed on Ethereum or Layer 2 (Polygon)
  • Transaction confirmed in ~2 seconds (Polygon) or ~15 seconds (Ethereum)
  • Immutable record created on blockchain
  • Transfer status: Pending → Completed

Phase 3: Recipient Receives Funds

Step 6: Notification

  • Recipient receives instant SMS/app notification
  • Transfer details visible in recipient's app
  • Blockchain explorer link for verification

Step 7: Currency Conversion (if needed)

  • If recipient wants local currency (PHP):
    • Stablecoin converted to PHP via local partner
    • Uses decentralized exchange (DEX) or liquidity pool
    • Smart contract handles conversion
  • If recipient wants USDC:
    • Keeps as stablecoin in wallet
    • Can use for other crypto transactions

Step 8: Withdrawal to Bank Account

  • Recipient chooses withdrawal option
  • Options:
    • Direct bank deposit: Partner bank transfers PHP
    • Cash pickup: Local agent location
    • Mobile money: Transfer to mobile wallet (GCash, PayMaya)
    • Keep as crypto: Hold in wallet for future use

Withdrawal Smart Contract:

function requestWithdrawal(
    bytes32 transferId,
    WithdrawalMethod method,
    string memory bankAccount
) public {
    Transfer storage t = transfers[transferId];
    require(msg.sender == t.recipient, "Not recipient");
    require(t.status == TransferStatus.Completed, "Not ready");

    // Record withdrawal request
    withdrawalRequests[transferId] = WithdrawalRequest({
        method: method,
        bankAccount: bankAccount,
        requestTime: block.timestamp,
        status: WithdrawalStatus.Pending
    });

    // Trigger off-chain process via oracle
    emit WithdrawalRequested(transferId, method);
}

Benefits Demonstrated:

1. Cost Savings:

  • Traditional: $100 send → $90-95 received (5-10% fees)
  • Blockchain: $100 send → $98.50 received (1.5% fees)
  • Savings: $6.50 per $100 (65% cost reduction)

2. Speed:

  • Traditional: 3-5 business days
  • Blockchain: 2 minutes to 1 hour
  • Improvement: 99% faster

3. Transparency:

  • Real-time tracking on blockchain
  • Clear fee breakdown upfront
  • No hidden charges
  • Exchange rate locked at initiation

4. Accessibility:

  • 24/7/365 availability
  • Mobile-first design
  • Serves unbanked (crypto wallet only)
  • Lower minimum amounts ($1 vs $100)

5. Security:

  • Cryptographic security (private keys)
  • Immutable transaction records
  • No intermediary custody risk
  • Smart contract automation (reduces human error)

6. Financial Inclusion:

  • Access for unbanked/underbanked
  • Lower barriers to entry
  • Smartphone = full banking capability
  • Micro-remittances economically viable

Technical Implementation Details:

Blockchain Platform: Polygon (Ethereum Layer 2)

  • Low fees (~$0.01 per transaction)
  • Fast confirmation (2 seconds)
  • Ethereum security
  • EVM compatible

Stablecoin: USDC (USD Coin)

  • Pegged 1:1 to USD
  • Regulated and audited
  • Wide acceptance
  • Low volatility

Price Oracle: Chainlink

  • Reliable exchange rate feeds
  • Decentralized data aggregation
  • Tamper-proof
  • Real-time updates

Storage:

  • Transaction metadata: On-chain (Polygon)
  • User KYC data: Off-chain encrypted database
  • Compliance logs: On-chain hashes

Regulatory Compliance:

KYC/AML:

  • Identity verification at onboarding
  • Transaction monitoring
  • Suspicious activity reporting
  • Sanctions screening

Licensing:

  • Money transmitter licenses
  • Partnership with licensed entities
  • Regulatory compliance per jurisdiction

Data Protection:

  • GDPR compliance
  • Encrypted personal data
  • User consent management

Real-World Example: Stellar (XLM) Remittances

Case Study:

  • Platform: Stellar Network
  • Partners: MoneyGram, Circle
  • Route: USA → Mexico remittances
  • Volume: $1B+ annual
  • Speed: 5 seconds average
  • Cost: <1% fees

Results:

  • 90% cost reduction vs traditional
  • Instant settlement
  • Millions of users served
  • 99.99% uptime

Other Finance Use Cases:

1. Trade Finance:

  • Letter of credit on blockchain
  • Smart contracts automate payment upon delivery
  • Reduces fraud, paperwork
  • Example: we.trade platform

2. Securities Settlement:

  • T+0 settlement (instant vs T+2 traditional)
  • Reduced counterparty risk
  • Example: ASX blockchain settlement system

3. Syndicated Lending:

  • Blockchain-based loan distribution
  • Transparent terms and ownership
  • Automated interest payments
  • Example: HSBC blockchain loan platform

4. Supply Chain Finance:

  • Invoice financing on blockchain
  • Supplier payment acceleration
  • Reduced factoring costs
  • Example: IBM Food Trust

5. Central Bank Digital Currencies (CBDC):

  • Digital versions of fiat currency
  • Programmable money
  • Financial inclusion
  • Example: China's Digital Yuan, Bahamas Sand Dollar

Challenges and Solutions:

Challenge Solution
Regulatory uncertainty Partnership with licensed institutions
Volatility Use stablecoins
User adoption Simple UI, education
Liquidity Deep liquidity pools, market makers
Scalability Layer 2 solutions (Polygon, Optimism)
Interoperability Cross-chain bridges

Future Evolution:

  • Integration with CBDCs
  • AI-powered fraud detection
  • Zero-knowledge privacy
  • Quantum-resistant cryptography
  • Complete automation (no manual steps)

Impact Summary:

Financial Inclusion:

  • 1.7B unbanked gain access
  • Micro-remittances viable
  • Self-custodial wallets

Economic Impact:

  • $30B+ annual fee savings globally
  • Faster access to funds
  • More money reaches recipients
  • Stimulates local economies

Innovation:

  • Programmable money
  • Instant settlement
  • 24/7 global payments
  • Financial innovation unlocked

This use case demonstrates how blockchain transforms finance from a slow, expensive, opaque system to a fast, cheap, transparent ecosystem accessible to everyone globally.


Module V - Ethereum and Solidity — #### Question 19

Question 19

(a) Explain the architecture and components of Ethereum ecosystem. (7 marks)

Ethereum Ecosystem Architecture:

Ethereum is a decentralized, open-source blockchain platform that enables the creation and execution of smart contracts and decentralized applications (DApps). It extends beyond simple cryptocurrency transactions to programmable blockchain functionality.

Overview:

Ethereum can be understood as:

  • World Computer: Globally distributed computing platform
  • Smart Contract Platform: Execute code in decentralized manner
  • Decentralized State Machine: Maintains global state across network
  • Cryptocurrency: ETH as native currency

Ethereum Architecture Layers:

┌────────────────────────────────────────────────┐
│         APPLICATION LAYER                      │
│   DApps, Wallets, DeFi Protocols              │
└────────────────┬───────────────────────────────┘
                 │
┌────────────────▼───────────────────────────────┐
│         EXECUTION LAYER (EVM)                  │
│   Smart Contracts, Accounts, Transactions     │
└────────────────┬───────────────────────────────┘
                 │
┌────────────────▼───────────────────────────────┐
│         CONSENSUS LAYER                        │
│   PoS Validators, Block Production            │
└────────────────┬───────────────────────────────┘
                 │
┌────────────────▼───────────────────────────────┐
│         NETWORK LAYER                          │
│   P2P Communication, Node Discovery           │
└────────────────────────────────────────────────┘

Core Components of Ethereum Ecosystem:

1. Ethereum Virtual Machine (EVM)

Description:
The EVM is the runtime environment for smart contracts in Ethereum. It's a quasi-Turing-complete state machine that executes bytecode.

Characteristics:

  • Deterministic: Same input always produces same output
  • Isolated: Sandboxed environment, no access to network/filesystem
  • Stack-based: 256-bit word size
  • Bytecode execution: Compiles Solidity to bytecode

Function:

  • Executes smart contract code
  • Maintains global state
  • Processes transactions
  • Computes state transitions

EVM Architecture:

┌──────────────────────────────────┐
│   Smart Contract (Solidity)      │
└───────────┬──────────────────────┘
            │ Compile
┌───────────▼──────────────────────┐
│   Bytecode (0x6060604052...)     │
└───────────┬──────────────────────┘
            │ Execute
┌───────────▼──────────────────────┐
│   Ethereum Virtual Machine       │
│   - Stack (1024 depth)           │
│   - Memory (volatile)            │
│   - Storage (persistent)         │
└──────────────────────────────────┘

EVM Components:

  • Stack: 1024-element stack for computation
  • Memory: Volatile byte-array, cleared between transactions
  • Storage: Persistent key-value store (expensive)
  • Program Counter: Tracks execution position
  • Gas: Computational resource metering

2. Accounts

Ethereum has two types of accounts:

A) Externally Owned Accounts (EOA):

Structure:

EOA {
    Address: 20 bytes (0x742d35Cc6634C0532925a...)
    Balance: ETH amount in Wei
    Nonce: Transaction count
}

Characteristics:

  • Controlled by private keys
  • Can initiate transactions
  • No associated code
  • Created by generating key pair
  • Costs nothing to create

Functions:

  • Send ETH to other accounts
  • Deploy smart contracts
  • Call smart contract functions
  • Sign transactions

Example:

Address: 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb
Balance: 2.5 ETH
Nonce: 47 (sent 47 transactions)

B) Contract Accounts:

Structure:

Contract Account {
    Address: 20 bytes
    Balance: ETH amount
    Code: Smart contract bytecode
    Storage: Persistent data (key-value pairs)
    Nonce: Deployed contract count
}

Characteristics:

  • Controlled by code (smart contract)
  • Cannot initiate transactions (passive)
  • Has associated code
  • Created by deploying contract
  • Costs gas to create

Functions:

  • Execute code when called
  • Store data persistently
  • Call other contracts
  • Emit events
  • Hold ETH

Example:

Address: 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb (contract)
Balance: 100 ETH (contract holds funds)
Code Hash: 0xabcdef... (bytecode hash)
Storage: {
    slot[0]: 0x123... (state variable 1)
    slot[1]: 0x456... (state variable 2)
}

3. Transactions

Transaction Structure:

Transaction {
    Nonce: uint64          // Sender's transaction count
    Gas Price: uint256     // Price per gas unit (in Wei)
    Gas Limit: uint256     // Maximum gas allowed
    To: address           // Recipient (20 bytes)
    Value: uint256        // ETH amount (in Wei)
    Data: bytes           // Input data for contract call
    v, r, s: signature    // ECDSA signature components
}

Transaction Types:

1. ETH Transfer:

{
    from: 0xAlice...
    to: 0xBob...
    value: 1 ETH
    data: "" (empty)
}

2. Contract Deployment:

{
    from: 0xAlice...
    to: null (deployment indicator)
    value: 0
    data: <contract bytecode>
}

3. Contract Function Call:

{
    from: 0xAlice...
    to: 0xContract...
    value: 0
    data: <function selector + parameters>
}

Transaction Lifecycle:

1. Create & Sign Transaction
2. Broadcast to Network
3. Enter Mempool
4. Selected by Validator
5. Included in Block
6. Block Validated by Network
7. Transaction Confirmed
8. State Updated

4. Messages (Internal Transactions)

Description:
Messages are internal calls between contracts, not stored directly on blockchain.

Characteristics:

  • Created when contract calls another contract
  • Not externally signed
  • Part of transaction execution
  • Can transfer ETH between contracts

Example:

Contract A calls Contract B:
   Transaction (EOA → A) triggers
   Message (A → B) internally

5. Gas System

Purpose:
Gas prevents infinite loops and measures computational cost.

Gas Components:

a) Gas Limit:

  • Maximum gas willing to spend
  • Set by transaction sender
  • Unused gas refunded

b) Gas Price (Before EIP-1559):

  • Price per gas unit in Gwei
  • Higher price = higher priority

c) Gas Used:

  • Actual gas consumed
  • Depends on operations executed

EIP-1559 Gas Model (Current):

Total Fee = (Base Fee + Priority Fee) × Gas Used

Base Fee: Algorithmically determined, burned
Priority Fee (Tip): Goes to validator
Max Fee: Maximum willing to pay

Example:

Gas Limit: 21,000 units
Base Fee: 30 Gwei
Priority Fee: 2 Gwei
Gas Used: 21,000 units

Total Cost = (30 + 2) × 21,000 = 672,000 Gwei = 0.000672 ETH

Gas Costs for Operations:

Operation               Gas Cost
- Addition (ADD)        3
- Multiplication (MUL)  5
- Storage write (SSTORE) 20,000 (new) / 5,000 (update)
- Storage read (SLOAD)  800
- SHA3 hash             30 + 6 per word
- Transfer ETH          21,000 (basic)
- Deploy contract       32,000 + code size cost

6. Blocks and Blockchain

Block Structure:

Block {
    Header: {
        Parent Hash: Previous block hash
        State Root: Merkle root of state trie
        Transactions Root: Merkle root of transactions
        Receipts Root: Merkle root of receipts
        Difficulty: Mining/staking difficulty
        Number: Block height
        Gas Limit: Maximum gas for block
        Gas Used: Total gas used
        Timestamp: Block creation time
        Extra Data: Arbitrary data
        Mix Hash: PoW verification
        Nonce: PoW nonce
    }
    Transactions: [tx1, tx2, tx3, ...]
    Ommers: [] (uncle blocks, deprecated in PoS)
}

Blockchain Properties:

  • Block time: ~12 seconds (after PoS merge)
  • Block size: Variable, limited by gas limit
  • Gas limit per block: ~30 million
  • Finality: ~15 minutes (2 epochs in PoS)

7. State and State Transitions

Global State:
Ethereum maintains a global state mapping addresses to account states.

State Structure:

State = {
    0xAlice...: {balance: 5 ETH, nonce: 10, code: null, storage: {}}
    0xBob...: {balance: 3 ETH, nonce: 5, code: null, storage: {}}
    0xContract1...: {balance: 100 ETH, nonce: 0, code: 0x60606..., storage: {...}}
}

State Transition:

State_new = Υ(State_old, Transaction)

Υ = State transition function
Executes transaction and produces new state

State Trie (Merkle Patricia Trie):

  • Efficiently stores state
  • Allows cryptographic proofs
  • State root in block header

8. Ethereum Nodes

Node Types:

A) Full Node:

  • Stores complete blockchain
  • Validates all blocks and transactions
  • Can serve data to network
  • ~1TB storage (and growing)

B) Archive Node:

  • Full node + all historical states
  • Can query any historical state
  • ~12TB+ storage
  • Used by block explorers

C) Light Node:

  • Stores only block headers
  • Requests data from full nodes
  • Minimal storage (~1GB)
  • Suitable for mobile devices

D) Validator Node (PoS):

  • Full node + staking functionality
  • Proposes and attests blocks
  • Requires 32 ETH stake
  • Earns staking rewards

9. Ethereum Clients

Execution Layer Clients:

  • Geth (Go Ethereum): Most popular, Go language
  • Nethermind: .NET implementation
  • Besu: Java implementation, enterprise-focused
  • Erigon: Performance-optimized

Consensus Layer Clients (Post-Merge):

  • Prysm: Go implementation
  • Lighthouse: Rust implementation
  • Teku: Java implementation
  • Nimbus: Nim language, resource-efficient

Client Diversity:
Important for network resilience; no single client should dominate.


10. Keys and Addresses

Key Generation:

1. Generate Private Key (256-bit random number)
   Private Key: 0x8f2a55949038a9610f50fb23b5883af3b4ecb3c3bb792cbcefbd1542c692be63

2. Derive Public Key (ECDSA secp256k1)
   Public Key: 0x04bfcab8722991ae774db48f934ca79cfb7dd991229153b9f732ba5334aafcd8e7266e47076996b55a14bf9913ee3145ce0cfc1372ada8ada74bd287450313534a

3. Take Keccak-256 hash of public key
   Hash: 0x2f015c60e0be116b1f0cd534704db9c92118fb6a11f0c530e69c94f32f063aff

4. Take last 20 bytes as address
   Address: 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb

Address Format:

  • 20 bytes (40 hex characters)
  • Prefixed with 0x
  • Checksum encoding (EIP-55) for error detection

11. Ethereum Network

Network Types:

A) Mainnet:

  • Production network
  • Real ETH with value
  • Chain ID: 1

B) Test Networks:

  • Sepolia: Recommended testnet
  • Goerli: Being deprecated
  • Free test ETH from faucets
  • For development and testing

C) Private Networks:

  • Local development (Ganache, Hardhat)
  • Enterprise consortiums

Network Communication:

  • P2P protocol (DevP2P)
  • Discovery protocol (Disc v4/v5)
  • Gossip protocol for transaction/block propagation

12. Ethereum Consensus (Proof of Stake)

Post-Merge Architecture:

Validators:

  • Minimum 32 ETH stake
  • Run validator software
  • Propose and attest blocks
  • Earn rewards

Consensus Process:

1. Slot (12 seconds)
   - One validator proposes block
   - Committee attests

2. Epoch (32 slots = 6.4 minutes)
   - All validators participate once
   - Checkpoint finalization

3. Finality (2 epochs = ~15 minutes)
   - Block becomes finalized
   - Cannot be reverted

Rewards and Penalties:

  • Rewards for correct attestations
  • Slashing for malicious behavior
  • Inactivity penalties for offline

Ethereum Ecosystem Components Diagram:

┌──────────────────────────────────────────┐
│         APPLICATIONS                     │
│  DeFi  │  NFTs  │  Games  │  DAOs       │
└──────────┬───────────────────────────────┘
           │
┌──────────▼───────────────────────────────┐
│         DEVELOPER TOOLS                  │
│  Remix, Hardhat, Truffle, Foundry       │
└──────────┬───────────────────────────────┘
           │
┌──────────▼───────────────────────────────┐
│         WEB3 LIBRARIES                   │
│  web3.js, ethers.js, web3.py            │
└──────────┬───────────────────────────────┘
           │
┌──────────▼───────────────────────────────┐
│         JSON-RPC API                     │
└──────────┬───────────────────────────────┘
           │
┌──────────▼───────────────────────────────┐
│         ETHEREUM NODES                   │
│  Geth, Nethermind, Besu, Erigon         │
└──────────┬───────────────────────────────┘
           │
┌──────────▼───────────────────────────────┐
│         ETHEREUM BLOCKCHAIN              │
│  Blocks, Transactions, State            │
└──────────────────────────────────────────┘

Summary:

Ethereum ecosystem is a complex, layered architecture comprising:

  • EVM for smart contract execution
  • Two account types (EOA and Contract)
  • Robust transaction model
  • Efficient gas system
  • Decentralized consensus (PoS)
  • Diverse client implementations
  • Global state management
  • P2P network infrastructure

This architecture enables a trustless, decentralized platform for programmable money and applications.


(b) Write a smart contract in solidity for simple voting system. (7 marks)

Simple Voting System Smart Contract in Solidity

Requirements:

  • Chairperson can add voters
  • Each voter can vote once
  • Voters can delegate their vote
  • Track proposals and votes
  • Determine winning proposal

Complete Solidity Smart Contract:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/**
 * @title SimpleVoting
 * @dev Implements voting process with delegation
 */
contract SimpleVoting {

    // ============ State Variables ============

    /// @dev Structure to represent a Voter
    struct Voter {
        uint256 weight;        // Accumulated voting weight (1 + delegated votes)
        bool voted;            // True if person has already voted
        address delegate;      // Person delegated to
        uint256 vote;          // Index of voted proposal
    }

    /// @dev Structure to represent a Proposal
    struct Proposal {
        string name;           // Proposal name (up to 32 bytes)
        uint256 voteCount;     // Number of accumulated votes
    }

    /// @dev Chairperson who deploys the contract
    address public chairperson;

    /// @dev Mapping of voter addresses to Voter struct
    mapping(address => Voter) public voters;

    /// @dev Array of Proposal structs
    Proposal[] public proposals;

    // ============ Events ============

    /// @dev Emitted when a new voter is given right to vote
    event VoterAuthorized(address indexed voter);

    /// @dev Emitted when a vote is cast
    event VoteCast(address indexed voter, uint256 indexed proposalIndex);

    /// @dev Emitted when a vote is delegated
    event VoteDelegated(address indexed from, address indexed to);

    // ============ Modifiers ============

    /// @dev Restrict function to chairperson only
    modifier onlyChairperson() {
        require(
            msg.sender == chairperson,
            "Only chairperson can perform this action"
        );
        _;
    }

    // ============ Constructor ============

    /**
     * @dev Constructor - Creates a new voting contract
     * @param proposalNames Array of proposal names
     */
    constructor(string[] memory proposalNames) {
        chairperson = msg.sender;
        voters[chairperson].weight = 1;

        // Add each proposal to the proposals array
        for (uint256 i = 0; i < proposalNames.length; i++) {
            proposals.push(Proposal({
                name: proposalNames[i],
                voteCount: 0
            }));
        }
    }

    // ============ Functions ============

    /**
     * @dev Give voting right to a voter
     * @param voter Address of the voter
     * 
     * Requirements:
     * - Only chairperson can call
     * - Voter must not have voted already
     */
    function giveRightToVote(address voter) public onlyChairperson {
        require(
            !voters[voter].voted,
            "The voter already voted"
        );
        require(
            voters[voter].weight == 0,
            "Voter already has voting rights"
        );

        voters[voter].weight = 1;

        emit VoterAuthorized(voter);
    }

    /**
     * @dev Delegate your vote to another voter
     * @param to Address to delegate vote to
     * 
     * Requirements:
     * - Sender must not have voted
     * - Cannot delegate to self
     * - Cannot delegate to someone who already voted
     */
    function delegate(address to) public {
        Voter storage sender = voters[msg.sender];

        require(sender.weight != 0, "You have no right to vote");
        require(!sender.voted, "You already voted");
        require(to != msg.sender, "Self-delegation is not allowed");

        // Forward delegation chain
        // If 'to' also delegated, follow the chain
        while (voters[to].delegate != address(0)) {
            to = voters[to].delegate;

            // Prevent loops in delegation
            require(to != msg.sender, "Found loop in delegation");
        }

        Voter storage delegate_ = voters[to];

        // Delegatee must have voting rights
        require(delegate_.weight >= 1, "Delegate has no voting rights");

        // Mark sender as voted (delegated)
        sender.voted = true;
        sender.delegate = to;

        if (delegate_.voted) {
            // If delegate already voted, directly add to vote count
            proposals[delegate_.vote].voteCount += sender.weight;
        } else {
            // If delegate hasn't voted, add to their weight
            delegate_.weight += sender.weight;
        }

        emit VoteDelegated(msg.sender, to);
    }

    /**
     * @dev Cast your vote to a proposal
     * @param proposalIndex Index of proposal in proposals array
     * 
     * Requirements:
     * - Sender must not have voted
     * - Sender must have voting rights
     * - Proposal index must be valid
     */
    function vote(uint256 proposalIndex) public {
        Voter storage sender = voters[msg.sender];

        require(sender.weight != 0, "Has no right to vote");
        require(!sender.voted, "Already voted");
        require(proposalIndex < proposals.length, "Invalid proposal index");

        sender.voted = true;
        sender.vote = proposalIndex;

        // Add voter's weight to proposal's vote count
        proposals[proposalIndex].voteCount += sender.weight;

        emit VoteCast(msg.sender, proposalIndex);
    }

    /**
     * @dev Compute the winning proposal index
     * @return winningProposal_ Index of winning proposal
     * 
     * Note: In case of tie, returns first winning proposal
     */
    function winningProposal() public view returns (uint256 winningProposal_) {
        uint256 winningVoteCount = 0;

        for (uint256 p = 0; p < proposals.length; p++) {
            if (proposals[p].voteCount > winningVoteCount) {
                winningVoteCount = proposals[p].voteCount;
                winningProposal_ = p;
            }
        }
    }

    /**
     * @dev Get the name of the winning proposal
     * @return winnerName_ Name of winning proposal
     */
    function winnerName() public view returns (string memory winnerName_) {
        winnerName_ = proposals[winningProposal()].name;
    }

    /**
     * @dev Get total number of proposals
     * @return count Number of proposals
     */
    function getProposalCount() public view returns (uint256 count) {
        return proposals.length;
    }

    /**
     * @dev Get proposal details
     * @param index Index of proposal
     * @return name Proposal name
     * @return voteCount Current vote count
     */
    function getProposal(uint256 index) 
        public 
        view 
        returns (string memory name, uint256 voteCount) 
    {
        require(index < proposals.length, "Invalid proposal index");
        Proposal memory proposal = proposals[index];
        return (proposal.name, proposal.voteCount);
    }

    /**
     * @dev Check if an address has voted
     * @param voter Address to check
     * @return hasVoted True if voter has voted
     */
    function hasVoted(address voter) public view returns (bool hasVoted) {
        return voters[voter].voted;
    }

    /**
     * @dev Get voter details
     * @param voter Address of voter
     * @return weight Voting weight
     * @return voted Whether voted
     * @return delegate_ Delegate address
     * @return vote Voted proposal index
     */
    function getVoter(address voter) 
        public 
        view 
        returns (
            uint256 weight,
            bool voted,
            address delegate_,
            uint256 vote
        ) 
    {
        Voter memory v = voters[voter];
        return (v.weight, v.voted, v.delegate, v.vote);
    }
}

Usage Example:

1. Deployment:

// Deploy with proposal names
const proposals = ["Proposal A", "Proposal B", "Proposal C"];
const voting = await SimpleVoting.deploy(proposals);

2. Chairperson gives voting rights:

await voting.giveRightToVote("0xVoter1Address");
await voting.giveRightToVote("0xVoter2Address");
await voting.giveRightToVote("0xVoter3Address");

3. Voters cast votes:

// Voter 1 votes for Proposal A (index 0)
await voting.connect(voter1).vote(0);

// Voter 2 delegates to Voter 3
await voting.connect(voter2).delegate("0xVoter3Address");

// Voter 3 votes for Proposal B (index 1)
// This vote counts for both Voter 3 and Voter 2 (delegated)
await voting.connect(voter3).vote(1);

4. Check results:

const winnerIndex = await voting.winningProposal();
const winnerName = await voting.winnerName();
console.log(`Winner: ${winnerName} (Index: ${winnerIndex})`);

Key Features Explained:

1. Structs:

  • Voter: Stores voter information (weight, voted status, delegate, vote choice)
  • Proposal: Stores proposal information (name, vote count)

2. State Variables:

  • chairperson: Address of contract deployer (only one who can authorize voters)
  • voters: Mapping from address to Voter struct
  • proposals: Dynamic array of proposals

3. Access Control:

  • onlyChairperson modifier restricts certain functions
  • Only chairperson can give voting rights

4. Vote Delegation:

  • Voters can delegate their vote to others
  • Delegation chains are supported (A→B→C)
  • Loop prevention ensures no circular delegation
  • Delegated weight accumulates

5. Events:

  • VoterAuthorized: Logs when voter gets rights
  • VoteCast: Logs when vote is cast
  • VoteDelegated: Logs when vote is delegated

6. View Functions:

  • winningProposal(): Returns index of winning proposal
  • winnerName(): Returns name of winning proposal
  • getProposal(): Get details of specific proposal
  • hasVoted(): Check if address has voted

Security Considerations:

  1. Reentrancy: Not applicable (no external calls)
  2. Integer Overflow: Solidity 0.8.0+ has built-in overflow checks
  3. Access Control: Only chairperson can authorize voters
  4. Input Validation: Checks for valid proposal index
  5. Delegation Loops: Prevented by loop detection
  6. Double Voting: Prevented by voted flag

Gas Optimization:

  1. Storage vs Memory: Uses storage for state, memory for temporary
  2. View Functions: Pure/view functions cost no gas when called externally
  3. Events: Cheaper than storing data on-chain
  4. Batch Operations: Consider adding batch authorization

Possible Enhancements:

  1. Time-based Voting:
uint256 public votingDeadline;

modifier beforeDeadline() {
    require(block.timestamp < votingDeadline, "Voting ended");
    _;
}
  1. Weighted Voting:
function giveRightToVote(address voter, uint256 weight) public onlyChairperson {
    voters[voter].weight = weight;
}
  1. Vote Withdrawal:
function withdrawVote() public {
    Voter storage sender = voters[msg.sender];
    require(sender.voted, "Haven't voted yet");
    require(sender.delegate == address(0), "Cannot withdraw delegated vote");

    proposals[sender.vote].voteCount -= sender.weight;
    sender.voted = false;
}
  1. Quorum Requirement:
uint256 public quorum = 50; // 50% minimum participation

function isQuorumReached() public view returns (bool) {
    uint256 totalVotes = 0;
    for (uint256 i = 0; i < proposals.length; i++) {
        totalVotes += proposals[i].voteCount;
    }
    return totalVotes >= (totalVoterWeight * quorum) / 100;
}

This smart contract provides a complete, functional voting system with delegation capabilities, demonstrating core Solidity concepts and blockchain voting mechanisms.


Question 20

(a) Explain the data types and functions used in solidity language. (7 marks)

Data Types in Solidity:

Solidity is a statically-typed language, meaning variable types must be specified at compile-time.


1. Value Types

A) Boolean (bool):

Represents true or false values.

bool public isActive = true;
bool public hasVoted = false;

// Operators: !, &&, ||, ==, !=
if (!hasVoted && isActive) {
    // Execute code
}

B) Integers:

Unsigned Integers (uint):

  • Range: 0 to 2^n - 1
  • Sizes: uint8, uint16, uint32, ..., uint256
  • uint is alias for uint256
uint256 public totalSupply = 1000000;
uint8 public decimals = 18;
uint public count; // defaults to uint256

// Arithmetic operators: +, -, *, /, %, **
uint result = 10 + 5;  // 15
uint power = 2 ** 8;   // 256

Signed Integers (int):

  • Range: -2^(n-1) to 2^(n-1) - 1
  • Sizes: int8, int16, ..., int256
int256 public temperature = -10;
int public balance; // defaults to int256

C) Address:

Holds 20-byte Ethereum address.

address public owner = 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb;
address payable public wallet; // Can receive ETH

// Address members:
owner.balance;           // Get ETH balance (uint256)
wallet.transfer(1 ether); // Send ETH
wallet.send(1 ether);    // Send ETH (returns bool)
wallet.call{value: 1 ether}(""); // Low-level call

D) Fixed-size Byte Arrays:

bytes1 public b1 = 0xFF;
bytes2 public b2 = 0xFFFF;
bytes32 public hash;

// bytes1 to bytes32 available
// Operators: comparisons (==, !=, <, >, <=, >=), &, |, ^, ~

E) Enums:

User-defined types with finite set of values.

enum Status { Pending, Active, Completed, Cancelled }

Status public currentStatus = Status.Pending;

function setStatus(Status _status) public {
    currentStatus = _status;
}

function isCompleted() public view returns (bool) {
    return currentStatus == Status.Completed;
}

F) Fixed Point Numbers:

Currently experimental and not fully supported.

// fixed / ufixed (planned, not yet available)
// fixed128x18 public price; // 128 bits, 18 decimal places

2. Reference Types

A) Arrays:

Fixed-size Arrays:

uint[5] public fixedArray = [1, 2, 3, 4, 5];
address[10] public addresses;

Dynamic Arrays:

uint[] public dynamicArray;
string[] public names;

function addElement(uint value) public {
    dynamicArray.push(value);  // Add element
}

function removeLastElement() public {
    dynamicArray.pop();  // Remove last element
}

function getLength() public view returns (uint) {
    return dynamicArray.length;
}

function getElement(uint index) public view returns (uint) {
    return dynamicArray[index];
}

Bytes (Dynamic):

bytes public data;

function setData(bytes memory _data) public {
    data = _data;
}

Array Members:

  • length: Number of elements
  • push(): Add element to end
  • pop(): Remove last element

B) Strings:

string public name = "Token Name";
string public symbol = "TKN";

// Strings are expensive to manipulate
// No built-in string manipulation
// Use bytes for manipulation
function compareStrings(string memory a, string memory b) 
    public 
    pure 
    returns (bool) 
{
    return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b));
}

C) Structs:

Custom data structures grouping multiple variables.

struct User {
    string name;
    uint256 age;
    address wallet;
    bool isActive;
}

User public admin;
User[] public users; // Array of structs

function addUser(string memory _name, uint256 _age, address _wallet) public {
    User memory newUser = User({
        name: _name,
        age: _age,
        wallet: _wallet,
        isActive: true
    });

    users.push(newUser);
}

// Alternative syntax:
function addUserAlt(string memory _name, uint256 _age, address _wallet) public {
    users.push(User(_name, _age, _wallet, true));
}

D) Mappings:

Hash tables / dictionaries for key-value pairs.

mapping(address => uint256) public balances;
mapping(address => mapping(address => uint256)) public allowances;

// Nested mapping
mapping(uint => mapping(address => bool)) public voted;

function setBalance(address user, uint256 amount) public {
    balances[user] = amount;
}

function getBalance(address user) public view returns (uint256) {
    return balances[user]; // Returns 0 if not set
}

// Mapping characteristics:
// - All keys exist by default (return default value)
// - Cannot iterate over mappings
// - Cannot get length of mapping
// - Keys are not stored, only hash

3. Special Data Locations

A) Storage:

  • Persistent data stored on blockchain
  • Expensive (costs gas)
  • State variables
uint256 public storageVar; // Stored permanently

function updateStorage(uint256 value) public {
    storageVar = value; // Writes to blockchain
}

B) Memory:

  • Temporary data during function execution
  • Cleared after function returns
  • Cheaper than storage
function processData() public pure {
    uint256 memory tempVar = 100; // Exists only in function
    uint[] memory tempArray = new uint[](10);
}

C) Calldata:

  • Read-only, temporary data for function parameters
  • Cheaper than memory
  • Available for external functions
function processArray(uint[] calldata data) external {
    // data is read-only
    // Cannot modify data
}

Storage vs Memory vs Calldata:

contract DataLocations {
    uint[] public storageArray; // Storage

    function example(uint[] calldata calldataArray) external {
        uint[] memory memoryArray = new uint[](5); // Memory

        storageArray = calldataArray; // Copies calldata to storage
        memoryArray = storageArray; // Copies storage to memory
    }
}

Functions in Solidity:

1. Function Visibility:

A) Public:

  • Callable internally and externally
  • Creates getter for state variables
function publicFunction() public returns (uint) {
    return 42;
}

B) External:

  • Only callable from outside contract
  • More gas-efficient for large data
function externalFunction() external returns (uint) {
    return 42;
}

// Can be called internally using this:
function callExternal() public {
    this.externalFunction();
}

C) Internal:

  • Only callable within contract and derived contracts
  • Default for state variables
function internalFunction() internal returns (uint) {
    return 42;
}

D) Private:

  • Only callable within current contract
  • Not visible to derived contracts
function privateFunction() private returns (uint) {
    return 42;
}

2. Function State Mutability:

A) View:

  • Reads state but doesn't modify
  • No gas cost when called externally
function getBalance(address user) public view returns (uint256) {
    return balances[user]; // Only reads state
}

B) Pure:

  • Doesn't read or modify state
  • Only uses function parameters
function add(uint a, uint b) public pure returns (uint) {
    return a + b; // No state access
}

C) Payable:

  • Can receive ETH
function deposit() public payable {
    balances[msg.sender] += msg.value;
}

function getContractBalance() public view returns (uint) {
    return address(this).balance;
}

D) Non-payable (default):

  • Cannot receive ETH
  • Will revert if ETH sent
function regularFunction() public {
    // Cannot receive ETH
}

3. Function Modifiers:

Custom requirements for functions.

address public owner;

modifier onlyOwner() {
    require(msg.sender == owner, "Not authorized");
    _; // Execute function body here
}

modifier validAmount(uint amount) {
    require(amount > 0, "Amount must be positive");
    _;
}

function restrictedFunction() public onlyOwner validAmount(msg.value) {
    // Only owner can call
    // msg.value must be > 0
}

4. Function Return Values:

Single Return:

function getName() public view returns (string memory) {
    return "Alice";
}

Multiple Returns:

function getUser() public view returns (string memory name, uint age, address wallet) {
    return ("Alice", 25, 0x123...);
}

// Named returns (automatically initialized):
function getUserNamed() public view returns (string memory name, uint age) {
    name = "Bob";
    age = 30;
    // Implicit return of name and age
}

// Destructuring returns:
(string memory userName, uint userAge) = getUser();

5. Function Overloading:

Same function name, different parameters.

function add(uint a, uint b) public pure returns (uint) {
    return a + b;
}

function add(uint a, uint b, uint c) public pure returns (uint) {
    return a + b + c;
}

6. Special Functions:

A) Constructor:

  • Executed once during deployment
  • Initializes contract state
constructor(uint256 initialSupply) {
    totalSupply = initialSupply;
    balances[msg.sender] = initialSupply;
}

B) Receive:

  • Handles plain ETH transfers (no data)
receive() external payable {
    // Called when ETH sent without function call
}

C) Fallback:

  • Called when no function matches
  • Can receive ETH if payable
fallback() external payable {
    // Called when function doesn't exist
}

7. Global Variables and Functions:

Block/Transaction Properties:

block.timestamp;     // Current block timestamp
block.number;        // Current block number
block.difficulty;    // Current block difficulty
block.gaslimit;      // Current block gas limit

msg.sender;          // Address of caller
msg.value;           // ETH sent (in wei)
msg.data;            // Complete calldata
msg.sig;             // Function signature (first 4 bytes)

tx.gasprice;         // Transaction gas price
tx.origin;           // Original sender (entire call chain)

Address Methods:

address.balance;                    // ETH balance
address.code;                       // Contract code
address.codehash;                   // Hash of contract code

payableAddress.transfer(amount);    // Send ETH (reverts on failure)
payableAddress.send(amount);        // Send ETH (returns bool)
address.call{value: amount}(data);  // Low-level call
address.delegatecall(data);         // Delegatecall
address.staticcall(data);           // Static call

Cryptographic Functions:

keccak256(abi.encodePacked(data));  // Hash function
sha256(data);                        // SHA-256 hash
ripemd160(data);                     // RIPEMD-160 hash
ecrecover(hash, v, r, s);           // Recover signer address

Contract-related:

address(this);               // Current contract address
address(this).balance;       // Contract ETH balance
selfdestruct(payable(addr)); // Destroy contract, send ETH

Complete Example Demonstrating All Concepts:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract DataTypesAndFunctions {

    // === Value Types ===
    bool public isActive = true;
    uint256 public count = 0;
    int256 public balance = -100;
    address public owner;
    bytes32 public hash;

    enum Status { Pending, Active, Completed }
    Status public status = Status.Pending;

    // === Reference Types ===
    uint[] public numbers;
    string public name = "Example";

    struct User {
        string name;
        uint256 age;
    }

    User[] public users;
    mapping(address => uint256) public balances;

    // === Constructor ===
    constructor() {
        owner = msg.sender;
    }

    // === Modifiers ===
    modifier onlyOwner() {
        require(msg.sender == owner, "Not owner");
        _;
    }

    // === Pure Function ===
    function add(uint a, uint b) public pure returns (uint) {
        return a + b;
    }

    // === View Function ===
    function getCount() public view returns (uint) {
        return count;
    }

    // === State-changing Function ===
    function incrementCount() public {
        count++;
    }

    // === Payable Function ===
    function deposit() public payable {
        balances[msg.sender] += msg.value;
    }

    // === External Function with Calldata ===
    function processData(uint[] calldata data) external pure returns (uint) {
        uint sum = 0;
        for (uint i = 0; i < data.length; i++) {
            sum += data[i];
        }
        return sum;
    }

    // === Internal Function ===
    function _internalHelper() internal pure returns (uint) {
        return 42;
    }

    // === Function with Multiple Returns ===
    function getUserInfo() public view returns (string memory, uint) {
        return (name, count);
    }

    // === Receive ETH ===
    receive() external payable {
        balances[msg.sender] += msg.value;
    }

    // === Fallback ===
    fallback() external payable {
        // Handle unknown function calls
    }
}

This comprehensive overview covers all major data types and function types in Solidity, providing a solid foundation for smart contract development.


(b) Explain how transactions are processed in Ethereum. Also explain the concept of gas and how does it affect the transaction processing? (7 marks)

Transaction Processing in Ethereum:

Transactions are the fundamental way users interact with the Ethereum blockchain, whether transferring ETH or executing smart contract functions.


Transaction Structure:

Transaction {
    // Core fields
    nonce: uint64              // Sender's transaction count
    gasPrice: uint256          // Price per gas unit (legacy)
    gasLimit: uint256          // Maximum gas allowed
    to: address                // Recipient address
    value: uint256             // ETH amount in Wei
    data: bytes                // Input data for contracts

    // EIP-1559 fields (current)
    maxFeePerGas: uint256      // Maximum total fee per gas
    maxPriorityFeePerGas: uint256  // Max tip for validator

    // Signature (ECDSA)
    v: uint8                   // Recovery ID
    r: uint256                 // Signature component
    s: uint256                 // Signature component
}

Transaction Lifecycle:

1. Transaction Creation
2. Transaction Signing
3. Broadcasting to Network
4. Mempool Entry
5. Validator Selection
6. Block Inclusion
7. Execution
8. State Update
9. Receipt Generation
10. Block Confirmation

Step-by-Step Transaction Processing:

Step 1: Transaction Creation

User creates transaction using wallet or dApp:

// Using ethers.js
const tx = {
    to: "0xRecipientAddress",
    value: ethers.utils.parseEther("1.0"), // 1 ETH
    gasLimit: 21000,
    maxFeePerGas: ethers.utils.parseUnits("50", "gwei"),
    maxPriorityFeePerGas: ethers.utils.parseUnits("2", "gwei"),
    nonce: await provider.getTransactionCount(senderAddress),
    data: "0x" // Empty for ETH transfer
};

Transaction Types:

Type 0 (Legacy):

to: 0x123...
value: 1 ETH
gasPrice: 50 Gwei
gasLimit: 21000
data: 0x

Type 2 (EIP-1559):

to: 0x123...
value: 1 ETH
maxFeePerGas: 50 Gwei
maxPriorityFeePerGas: 2 Gwei
gasLimit: 21000
data: 0x

Step 2: Transaction Signing

// Sign with private key
const signedTx = await wallet.signTransaction(tx);

// Signature components (v, r, s) added
// Creates cryptographic proof of authorization

ECDSA Signature:

  • Uses secp256k1 elliptic curve
  • Proves transaction authorized by private key owner
  • Signature can be verified using public key

Step 3: Broadcasting

const txHash = await provider.sendTransaction(signedTx);
console.log("Transaction Hash:", txHash);
  • Transaction broadcast to network via RPC nodes
  • Propagated through P2P gossip protocol
  • Reaches multiple nodes within seconds

Step 4: Mempool (Memory Pool)

Mempool
├── High Priority Transactions (high fees)
├── Medium Priority Transactions
└── Low Priority Transactions (low fees)

Mempool Characteristics:

  • Temporary storage for pending transactions
  • Each node maintains own mempool
  • Validators select from mempool for blocks
  • Transactions ordered by gas price (priority)

Transaction States:

Pending → Included in Block → Confirmed
         ↓
     Dropped (if low fee or nonce conflict)

Step 5: Validator Selection (Proof of Stake)

Validator Process:

1. Validator selected for next slot (~12 seconds)
2. Validator retrieves transactions from mempool
3. Orders by priority fee (tip)
4. Fills block up to gas limit
5. Executes transactions
6. Proposes block to network

Selection Criteria:

  • Maximum profit (highest fee transactions)
  • Block gas limit constraint
  • Transaction validity

Step 6: Transaction Execution

Execution Steps:

a) Validation:

Check:
- Nonce is correct (sequential)
- Sender has sufficient balance (value + gas fees)
- Gas limit >= intrinsic gas
- Signature is valid
- Gas price acceptable

b) Gas Deduction (Intrinsic Gas):

Intrinsic Gas = 21,000 (base) + calldata cost

Calldata Cost:
- Zero bytes: 4 gas each
- Non-zero bytes: 16 gas each

Example:

Transaction with 100 bytes calldata (50 zero, 50 non-zero):
Intrinsic = 21,000 + (50 × 4) + (50 × 16)
          = 21,000 + 200 + 800
          = 22,000 gas

c) Value Transfer:

If to is EOA:
    Balance[to] += value
    Balance[from] -= value

d) Contract Execution (if to is contract):

1. Load contract code
2. Initialize EVM
3. Execute bytecode
4. Update contract storage
5. Emit events
6. Return result

EVM Execution:

EVM {
    Stack: []
    Memory: []
    Storage: Contract's persistent storage
    Program Counter: 0
    Gas Remaining: gasLimit - intrinsicGas
}

Execute operations until:
- STOP/RETURN encountered
- Gas runs out → REVERT
- Error occurs → REVERT

Step 7: State Update

Global State Transition:
State[blockN+1] = EVM(State[blockN], Transaction)

Updates:
- Account balances
- Contract storage
- Nonce increments

Step 8: Receipt Generation

Transaction Receipt {
    status: 1 (success) or 0 (failure)
    blockNumber: uint256
    blockHash: bytes32
    transactionIndex: uint256
    from: address
    to: address
    gasUsed: uint256
    cumulativeGasUsed: uint256
    contractAddress: address (if deployment)
    logs: Event[] (emitted events)
    logsBloom: bytes256
}

Step 9: Block Finalization

Block {
    Header {
        stateRoot: Hash of new state
        transactionsRoot: Hash of all transactions
        receiptsRoot: Hash of all receipts
    }
    Transactions: [tx1, tx2, ...]
}

Step 10: Confirmation

Confirmations:
1st confirmation: Included in block
2nd confirmation: Next block added
...
12+ confirmations: Very low reversion probability
64+ confirmations: Finalized (cannot revert)

Gas Concept and Mechanics:

What is Gas?

Gas is Ethereum's unit of computational work. It serves two purposes:

  1. Meter computation: Measure work performed
  2. Prevent spam: Economic cost for operations

Why Gas Exists:

Problem without Gas:

// Infinite loop would halt network
while(true) {
    // This would run forever
}

Solution with Gas:

  • Each operation costs gas
  • Gas limit caps total computation
  • Infinite loops run out of gas and revert
  • Network protected from DOS attacks

Gas Components (EIP-1559 Model):

1. Gas Limit:

  • Maximum gas willing to spend
  • Set by user
  • Must be ≥ gas used
  • Unused gas refunded

2. Base Fee:

  • Minimum fee per gas
  • Algorithmically determined by network
  • Burned (removed from circulation)
  • Adjusts based on block fullness

3. Priority Fee (Tip):

  • Extra payment to validator
  • Incentivizes inclusion
  • Goes directly to validator
  • User sets maximum

4. Max Fee Per Gas:

  • Maximum total willing to pay
  • max Fee = Base Fee + Priority Fee
  • User won't pay more than this

Calculation:

Actual Fee Per Gas = min(maxFeePerGas, baseFee + maxPriorityFeePerGas)

If baseFee = 30 Gwei and maxPriorityFeePerGas = 2 Gwei:
    If maxFeePerGas = 50 Gwei:
        Actual = min(50, 30 + 2) = 32 Gwei

Total Cost = gasUsed × actualFeePerGas
Burned = gasUsed × baseFee
Validator Receives = gasUsed × priorityFee
Refund = (gasLimit - gasUsed) × actualFeePerGas

Gas Costs for Operations:

Operation Gas Cost Example
Addition (ADD) 3 a + b
Multiplication (MUL) 5 a * b
Division (DIV) 5 a / b
Comparison (LT, GT, EQ) 3 a < b
Jump (JUMP) 8 goto label
Storage Read (SLOAD) 800 Read variable
Storage Write (SSTORE) 20,000 / 5,000 Write variable
SHA3 Hash 30 + 6/word keccak256()
Create Contract 32,000 Deploy
CALL (to account) 700 Call function
Transfer ETH 9,000 Send ETH
LOG 375 + data cost Emit event

Example Transaction Gas Usage:

Simple ETH Transfer:

Operation                  Gas Cost
--------------------------------
Intrinsic Gas              21,000
Total                      21,000 gas

If gasPrice = 50 Gwei:
Cost = 21,000 × 50 = 1,050,000 Gwei = 0.00105 ETH

Contract Function Call:

Operation                  Gas Cost
--------------------------------
Intrinsic Gas              21,000
Calldata (100 bytes)       1,600
Function execution         5,000
Storage write (SSTORE)     20,000
Event emission (LOG)       1,000
Total                      48,600 gas

Cost = 48,600 × 50 Gwei = 0.00243 ETH

Complex DeFi Transaction:

Swap on Uniswap:          ~150,000 gas
Add liquidity:            ~200,000 gas
NFT mint:                 ~100,000 gas
Contract deployment:      ~500,000+ gas

How Gas Affects Transaction Processing:

1. Transaction Prioritization:

High Gas Price → Higher Priority → Faster Inclusion
Low Gas Price → Lower Priority → Slower (or never included)

Mempool Ordering:

Priority Queue:
1. TX #123: 100 Gwei (included first)
2. TX #456: 75 Gwei
3. TX #789: 50 Gwei
4. TX #012: 25 Gwei (may not be included)

2. Block Space Allocation:

Block Gas Limit: 30,000,000 gas

Validator fills block:
- TX1: 100,000 gas (fee: 50 Gwei)
- TX2: 200,000 gas (fee: 48 Gwei)
- TX3: 150,000 gas (fee: 45 Gwei)
- ...
- Until gas limit reached

3. Transaction Success/Failure:

Gas Too Low:

gasLimit = 20,000
Required = 50,000
Result: Transaction rejected before execution

Out of Gas During Execution:

gasLimit = 40,000
Execution uses 50,000 gas after 40,000 steps
Result:
- Transaction reverted
- State changes rolled back
- Gas fee still charged (40,000 gas)
- User loses gas fee

Successful Execution:

gasLimit = 100,000
gasUsed = 50,000
Result:
- Transaction succeeds
- State updated
- Charged for 50,000 gas
- Refunded 50,000 gas

4. Network Congestion:

Low Congestion:

Base Fee: 10 Gwei
Block Utilization: 40%
Fast confirmation: 1-2 blocks

High Congestion:

Base Fee: 200 Gwei
Block Utilization: 100%
Slow confirmation: 10+ blocks
Many transactions pending

Base Fee Adjustment:

If block > 50% full: Base fee increases
If block < 50% full: Base fee decreases

Max increase: 12.5% per block
Max decrease: 12.5% per block

5. Economic Impact:

User Perspective:

Low gas price → Cheap but slow
High gas price → Expensive but fast

User must balance cost vs urgency

Validator Perspective:

Select transactions maximizing profit:
Total Profit = Σ(gasUsed × priorityFee)

Validators prefer high-fee transactions

6. Gas Optimization:

Unoptimized:

// Expensive: Multiple storage writes
for (uint i = 0; i < 100; i++) {
    myArray.push(i);  // 20,000 gas each
}
// Total: 2,000,000 gas

Optimized:

// Cheaper: Memory operations
uint[] memory tempArray = new uint[](100);
for (uint i = 0; i < 100; i++) {
    tempArray[i] = i;  // Memory is cheap
}
myArray = tempArray;  // One storage write
// Total: ~50,000 gas

Gas Refund Mechanism:

Operations that Refund Gas:

- Delete storage: 15,000 gas refund (was 24,000)
- Set storage to zero: 4,800 gas refund

Maximum Refund = gasUsed / 5 (20%)

Example:

gasUsed = 100,000
Deleted storage: 30,000 refund
Maximum refund allowed: 100,000 / 5 = 20,000
Actual refund: min(30,000, 20,000) = 20,000

Transaction Processing Example:

Scenario: Alice sends 1 ETH to Bob

Transaction:
{
    from: Alice (0xAA...AA)
    to: Bob (0xBB...BB)
    value: 1 ETH
    gasLimit: 21,000
    maxFeePerGas: 50 Gwei
    maxPriorityFeePerGas: 2 Gwei
    baseFee: 30 Gwei (network determined)
}

Processing:
1. Validate: Alice has ≥ 1.00063 ETH (1 ETH + max gas fee)
2. Deduct max possible: 1 + (21,000 × 50 / 10^9) = 1.00105 ETH

3. Execute:
   - Check nonce ✓
   - Transfer 1 ETH: Alice → Bob ✓
   - Gas used: 21,000

4. Calculate actual fee:
   actualFee = min(50, 30 + 2) = 32 Gwei per gas
   totalFee = 21,000 × 32 = 672,000 Gwei = 0.000672 ETH

   Burned: 21,000 × 30 = 630,000 Gwei = 0.00063 ETH
   Tip: 21,000 × 2 = 42,000 Gwei = 0.000042 ETH

5. Final balances:
   Alice: Original - 1.000672 ETH
   Bob: Original + 1 ETH
   Validator: +0.000042 ETH
   Burned: 0.00063 ETH (removed from supply)

6. Refund to Alice:
   Unused gas × actualFee = 0 × 32 = 0 (all gas used)

Gas Optimization Best Practices:

  1. Use memory instead of storage where possible
  2. Batch operations to reduce transaction count
  3. Use events instead of storage for historical data
  4. Pack storage variables efficiently
  5. Use short-circuit evaluation
  6. Avoid loops with dynamic length
  7. Use libraries for reusable code
  8. Delete unused storage for refunds

Impact Summary:

Gas directly affects:

  • Transaction cost: More gas = higher fees
  • Execution limits: Gas limit caps computation
  • Inclusion speed: Higher gas price = faster confirmation
  • Network efficiency: Prevents spam and DOS
  • Economic security: Makes attacks expensive
  • User experience: Balance cost vs speed
  • Contract design: Must optimize for gas efficiency

End of Answer Key


Summary

This comprehensive answer key covers all questions from the CST428 Blockchain Technologies September 2025 examination:

Part A: 10 questions (3 marks each) covering:

  • Merkle roots, hash functions, block structure
  • Decentralization, genesis blocks, coinbase transactions
  • Hash rate, DAOs, blockchain & AI
  • Ethereum networks, gas calculations

Part B: 10 questions (14 marks each) covering:

  • Module I: RSA cryptography, digital signatures, AES, SHA-256
  • Module II: Blockchain types, block accumulation, decentralization, consensus mechanisms
  • Module III: Paxos protocol, blockchain wallets, Bitcoin transaction validation, PBFT
  • Module IV: Oracles, DApps, blockchain in healthcare and finance
  • Module V: Ethereum architecture, Solidity voting contract, transaction processing, gas mechanics

Total marks: 100
All answers include diagrams, examples, code, and comprehensive explanations scaled to marks allocation.