Answer Key - CST428 Blockchain Technologies
Answer Key - CST428 Blockchain Technologies
Examination: April 2025
Course Code: CST428
Course Name: Blockchain Technologies
Total Marks: 100
Duration: 3 Hours
Modules Covered: All (1-5)
QP Code: 0400CST428042501
PART A
Answer all questions, each carries 3 marks
Question 1: Mention the properties and applications of digital signatures. (3 marks)
Properties of Digital Signatures:
- Authentication: A digital signature verifies the identity of the sender, confirming that the message was created and sent by the claimed sender.
- Integrity: Any alteration to the message after signing invalidates the signature, ensuring the content has not been tampered with.
- Non-repudiation: The signer cannot deny having signed the document, as the signature is uniquely tied to their private key.
Applications of Digital Signatures:
- Financial Transactions: Used in online banking and cryptocurrency transactions to authorize and validate transfers.
- Software Distribution: Software publishers sign code to verify authenticity and ensure it has not been modified by malicious actors.
- Legal Documents: Digital contracts, agreements, and government filings use digital signatures for legally binding authentication.
Question 2: Distinguish between symmetric and asymmetric cryptography. (3 marks)
| Feature | Symmetric Cryptography | Asymmetric Cryptography |
|---|---|---|
| Keys Used | Single shared secret key for both encryption and decryption | Two keys: a public key for encryption and a private key for decryption |
| Speed | Faster due to simpler mathematical operations | Slower due to complex computations (modular exponentiation, elliptic curves) |
| Key Distribution | Key exchange is a challenge; both parties must securely share the secret key beforehand | No secure channel needed for key exchange; public key can be openly distributed |
| Examples | AES, DES, 3DES, Blowfish | RSA, ECC, Diffie-Hellman, ElGamal |
| Use Case | Bulk data encryption, file encryption | Digital signatures, key exchange, authentication |
Question 3: What is the significance of Genesis block in the blockchain? (3 marks)
The Genesis block (also called Block 0 or Block 1) is the very first block in a blockchain. Its significance includes:
-
Foundation of the Chain: It serves as the starting point of the entire blockchain. Every subsequent block traces its lineage back to the Genesis block through the chain of previous block hashes.
-
No Previous Hash: Unlike all other blocks, the Genesis block has no reference to a previous block hash (typically set to zero or null), making it unique in the chain structure.
-
Hardcoded in Software: The Genesis block is hardcoded into the blockchain software and cannot be altered. It establishes the initial state and parameters of the network.
-
Network Identity: It defines the identity of the blockchain network. Nodes use the Genesis block to verify they are on the correct chain; any mismatch means a different network.
-
Trust Anchor: It acts as the root of trust for the entire system. The immutability and validity of all blocks ultimately depend on the integrity of the Genesis block.
Question 4: What are Merkle trees? How can Merkle tree increase the security of blockchain? (3 marks)
Merkle Tree Definition:
A Merkle tree (or hash tree) is a binary tree data structure in which every leaf node contains the cryptographic hash of a data block (transaction), and every non-leaf node contains the hash of the concatenation of its child nodes. The topmost hash is called the Merkle root, which represents a single hash summary of all transactions in a block.
How Merkle Trees Increase Blockchain Security:
-
Tamper Detection: If any single transaction is modified, its hash changes, which cascades upward through the tree, changing the Merkle root. This makes any unauthorized modification immediately detectable.
-
Efficient Verification (SPV): Lightweight nodes can verify that a specific transaction is included in a block using a Merkle proof (a small set of hashes) without downloading the entire block, enabling Simplified Payment Verification.
-
Data Integrity: The Merkle root stored in the block header provides a compact fingerprint of all transactions. Any inconsistency between the transactions and the root proves data corruption or tampering.
Question 5: What is a wallet? Explain its types. (3 marks)
Definition:
A cryptocurrency wallet is a software program or physical device that stores the public and private keys required to interact with a blockchain network. It allows users to send, receive, and manage their digital assets while maintaining control over their cryptographic credentials.
Types of Wallets:
-
Hot Wallets (Online): Connected to the internet; convenient for frequent transactions but more vulnerable to hacking.
- Desktop wallets: Installed on a PC (e.g., Electrum)
- Mobile wallets: Smartphone apps (e.g., Trust Wallet)
- Web wallets: Browser-based (e.g., MetaMask)
-
Cold Wallets (Offline): Not connected to the internet; highly secure for long-term storage.
- Hardware wallets: Physical devices that store keys offline (e.g., Ledger, Trezor)
- Paper wallets: Printed QR codes of public/private keys on paper
-
Custodial vs Non-Custodial:
- Custodial: A third party holds the private keys (e.g., exchange wallets like Coinbase)
- Non-Custodial: User has full control of private keys
Question 6: Explain how the RAFT consensus algorithm operates to achieve agreement among peers in a blockchain. (3 marks)
RAFT Consensus Algorithm:
RAFT is a consensus algorithm designed for crash fault tolerance in distributed systems. It achieves agreement through leader election and log replication.
Working:
-
Node Roles: Each node exists in one of three states:
- Leader: Handles all client requests and replicates log entries to followers
- Follower: Passive nodes that respond to requests from the leader
- Candidate: A follower that initiates an election when it suspects leader failure
-
Leader Election:
- Nodes start as followers. If a follower receives no heartbeat from a leader within a random timeout period, it becomes a candidate.
- The candidate increments its term number and requests votes from other nodes.
- A node wins the election if it receives votes from a majority (quorum). It then becomes the leader.
- The randomized timeouts prevent split votes.
-
Log Replication:
- The leader receives client requests, appends them to its log, and sends AppendEntries RPCs to all followers.
- Once a majority of followers acknowledge the entry, the leader commits it and notifies followers to apply it.
-
Safety: RAFT guarantees that committed entries are durable and consistent across all nodes, ensuring agreement even if some nodes crash and recover.
Question 7: Define smart contracts and mention its relevant properties. (3 marks)
Definition:
A smart contract is a self-executing program stored on a blockchain that automatically enforces and executes the terms of an agreement when predetermined conditions are met. It eliminates the need for intermediaries by encoding business logic into immutable code that runs on a decentralized network (e.g., Ethereum).
Properties of Smart Contracts:
- Immutability: Once deployed on the blockchain, the contract code cannot be modified, ensuring the rules remain unchanged.
- Deterministic: Given the same input, a smart contract always produces the same output across all nodes.
- Self-executing: Automatically executes actions when triggering conditions are satisfied without human intervention.
- Transparency: The code is visible and verifiable by all participants on the network.
- Trustless: Parties do not need to trust each other; they only need to trust the code and the underlying blockchain.
- Distributed: The contract is replicated and executed across all nodes in the network, eliminating single points of failure.
Question 8: Enumerate benefits and limitations of using blockchain technology. (3 marks)
Benefits:
- Decentralization: Eliminates single points of failure and reduces dependence on central authorities.
- Immutability: Once data is recorded, it cannot be altered or deleted, ensuring a tamper-proof audit trail.
- Transparency: All participants can view and verify transactions, increasing trust and accountability.
- Security: Cryptographic hashing and consensus mechanisms make the network highly resistant to attacks.
- Reduced Intermediaries: Peer-to-peer transactions reduce costs and processing time by eliminating middlemen.
Limitations:
- Scalability: Limited transaction throughput compared to centralized systems (e.g., Bitcoin processes ~7 TPS vs Visa's ~24,000 TPS).
- Energy Consumption: Proof-of-Work based blockchains consume massive computational energy.
- Immutability (double-edged): Errors or fraudulent transactions cannot be easily reversed once confirmed.
- Storage: Every node stores a copy of the entire blockchain, leading to significant storage requirements over time.
- Regulatory Uncertainty: Lack of clear legal frameworks across jurisdictions creates adoption challenges.
Question 9: Illustrate the concept of inheritance in Solidity language. (3 marks)
Concept of Inheritance:
Inheritance in Solidity allows a contract (child/derived) to inherit state variables, functions, and modifiers from another contract (parent/base). This promotes code reuse and modularity. Solidity supports single and multiple inheritance using the is keyword.
- Single Inheritance: A child contract inherits from one parent.
- Multiple Inheritance: A child contract inherits from multiple parents (Solidity uses C3 linearization to resolve conflicts).
- Function Overriding: Child contracts can override parent functions using the
overridekeyword (parent must mark themvirtual).
Example:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Base contract
contract Animal {
string public name;
constructor(string memory _name) {
name = _name;
}
function speak() public pure virtual returns (string memory) {
return "...";
}
}
// Derived contract inheriting from Animal
contract Dog is Animal {
constructor(string memory _name) Animal(_name) {}
// Overriding the parent function
function speak() public pure override returns (string memory) {
return "Woof!";
}
}
In this example, Dog inherits the name variable and constructor pattern from Animal, and overrides the speak() function with its own implementation.
Question 10: Explain the role of the Ethereum Virtual Machine in the Ethereum network. (3 marks)
Role of the Ethereum Virtual Machine (EVM):
The EVM is the runtime environment for smart contract execution in Ethereum. It acts as a decentralized computation engine that processes and validates all state changes on the network.
Key Roles:
-
Smart Contract Execution: The EVM executes bytecode compiled from high-level languages (Solidity, Vyper). Every node runs the EVM to independently execute and verify contract operations.
-
Sandboxed Environment: The EVM provides complete isolation — smart contracts cannot access the file system, network, or other processes. This ensures security and prevents malicious code from affecting the host system.
-
State Management: The EVM manages the global state of Ethereum, including account balances, contract storage, and code. Every transaction results in a deterministic state transition.
-
Gas Mechanism: The EVM meters computation using "gas." Each opcode has a predefined gas cost, preventing infinite loops and allocating network resources fairly. Users pay gas fees to compensate miners/validators.
-
Platform Independence: The EVM serves as an abstraction layer, enabling smart contracts to run identically on any hardware or operating system, ensuring consistency across all nodes.
-
Turing Completeness: The EVM can execute any computable logic (bounded by gas limits), making it capable of running arbitrarily complex programs.
PART B
Answer any one full question from each module, each carries 14 marks
Module I - Fundamentals of Cryptography — #### Question 11
Question 11
(a) Perform encryption and decryption using RSA Public Key cryptographic technique for p=7; q=11, e=13; M=5. Illustrate the public key and private key generation. (7 marks)
RSA Key Generation, Encryption, and Decryption
Public and Private Keys:
- Public Key: Consists of (e, n) — shared openly. Used by anyone to encrypt messages sent to the key owner.
- Private Key: Consists of (d, n) — kept secret. Used by the owner to decrypt messages encrypted with their public key.
Step-by-Step RSA Calculation:
Step 1: Compute n
n = p × q = 7 × 11 = 77
Step 2: Compute Euler's Totient φ(n)
φ(n) = (p - 1)(q - 1) = 6 × 10 = 60
Step 3: Verify e is valid
gcd(e, φ(n)) = gcd(13, 60) = 1 ✓
Since gcd is 1, e=13 is a valid public exponent (coprime with φ(n)).
Step 4: Compute private key d
Find d such that d × e ≡ 1 mod φ(n):
d × 13 ≡ 1 mod 60
Using Extended Euclidean Algorithm:
60 = 4 × 13 + 8
13 = 1 × 8 + 5
8 = 1 × 5 + 3
5 = 1 × 3 + 2
3 = 1 × 2 + 1
Back-substitution:
1 = 3 - 1×2
1 = 3 - 1×(5 - 1×3) = 2×3 - 5
1 = 2×(8 - 5) - 5 = 2×8 - 3×5
1 = 2×8 - 3×(13 - 8) = 5×8 - 3×13
1 = 5×(60 - 4×13) - 3×13 = 5×60 - 23×13
Therefore: -23 × 13 ≡ 1 mod 60
d = -23 mod 60 = 37
Verification: 37 × 13 = 481 = 8 × 60 + 1 ≡ 1 mod 60 ✓
Generated Keys:
Public Key: (e, n) = (13, 77)
Private Key: (d, n) = (37, 77)
Step 5: Encryption
Plaintext M = 5
Ciphertext C = M^e mod n = 5^13 mod 77
Computing 5^13 mod 77 using repeated squaring:
5^1 = 5
5^2 = 25
5^4 = 25^2 = 625 mod 77 = 625 - 8×77 = 625 - 616 = 9
5^8 = 9^2 = 81 mod 77 = 4
5^13 = 5^8 × 5^4 × 5^1 = 4 × 9 × 5 = 180 mod 77 = 180 - 2×77 = 26
C = 26
Step 6: Decryption
Ciphertext C = 26
Plaintext M = C^d mod n = 26^37 mod 77
Computing 26^37 mod 77 using repeated squaring:
26^1 = 26
26^2 = 676 mod 77 = 676 - 8×77 = 676 - 616 = 60
26^4 = 60^2 = 3600 mod 77 = 3600 - 46×77 = 3600 - 3542 = 58
26^8 = 58^2 = 3364 mod 77 = 3364 - 43×77 = 3364 - 3311 = 53
26^16 = 53^2 = 2809 mod 77 = 2809 - 36×77 = 2809 - 2772 = 37
26^32 = 37^2 = 1369 mod 77 = 1369 - 17×77 = 1369 - 1309 = 60
26^37 = 26^32 × 26^4 × 26^1 = 60 × 58 × 26 mod 77
60 × 58 = 3480 mod 77 = 3480 - 45×77 = 3480 - 3465 = 15
15 × 26 = 390 mod 77 = 390 - 5×77 = 390 - 385 = 5
M = 5 ✓ (Original plaintext recovered)
(b) Depict the working of Advanced Encryption Standard (AES) with a neat diagram explaining each round of operations. (7 marks)
Advanced Encryption Standard (AES)
AES is a symmetric block cipher that encrypts 128-bit blocks of data. It supports key sizes of 128, 192, or 256 bits with 10, 12, or 14 rounds respectively.
AES Structure Diagram:
┌─────────────────────────────────┐
│ Plaintext (128-bit) │
└────────────────┬────────────────┘
│
▼
┌─────────────────────────────────┐
│ Initial Round: AddRoundKey │◄── Round Key 0
└────────────────┬────────────────┘
│
▼
┌─────────────────────────────────┐
│ ┌───────────────────────────┐ │
│ │ 1. SubBytes │ │
│ ├───────────────────────────┤ │
│ │ 2. ShiftRows │ │ Rounds
│ ├───────────────────────────┤ │ 1 to 9
│ │ 3. MixColumns │ │ (repeated)
│ ├───────────────────────────┤ │
│ │ 4. AddRoundKey │◄─┼── Round Key i
│ └───────────────────────────┘ │
└────────────────┬────────────────┘
│
▼
┌─────────────────────────────────┐
│ Final Round (Round 10): │
│ ┌───────────────────────────┐ │
│ │ 1. SubBytes │ │
│ ├───────────────────────────┤ │
│ │ 2. ShiftRows │ │
│ ├───────────────────────────┤ │ (No MixColumns)
│ │ 3. AddRoundKey │◄─┼── Round Key 10
│ └───────────────────────────┘ │
└────────────────┬────────────────┘
│
▼
┌─────────────────────────────────┐
│ Ciphertext (128-bit) │
└─────────────────────────────────┘
Detailed Round Operations:
1. SubBytes (Substitution)
Each byte of the state is replaced with a corresponding entry from a fixed 16×16 lookup table (S-Box). This provides non-linearity and confusion in the cipher.
┌────┬────┬────┬────┐ ┌────┬────┬────┬────┐
│ a0 │ a4 │ a8 │ a12│ │ b0 │ b4 │ b8 │ b12│
│ a1 │ a5 │ a9 │ a13│ ───► │ b1 │ b5 │ b9 │ b13│
│ a2 │ a6 │ a10│ a14│ S-Box │ b2 │ b6 │ b10│ b14│
│ a3 │ a7 │ a11│ a15│ │ b3 │ b7 │ b11│ b15│
└────┴────┴────┴────┘ └────┴────┴────┴────┘
2. ShiftRows (Permutation)
Rows of the state matrix are cyclically shifted left by different offsets:
Row 0: No shift [B0 B4 B8 B12]
Row 1: Shift left 1 [B5 B9 B13 B1 ]
Row 2: Shift left 2 [B10 B14 B2 B6 ]
Row 3: Shift left 3 [B15 B3 B7 B11]
3. MixColumns (Diffusion)
Each column of the state is multiplied by a fixed polynomial matrix in GF(2^8). This mixes the bytes within each column, providing diffusion across columns.
[2 3 1 1] [s0] [s0']
[1 2 3 1] × [s1] = [s1']
[1 1 2 3] [s2] [s2']
[3 1 1 2] [s3] [s3']
4. AddRoundKey (Key Mixing)
Each byte of the state is XORed with the corresponding byte of the round key derived from the key expansion schedule. This is the only step that introduces key material.
Key Expansion: The original cipher key is expanded into a key schedule that produces a unique round key for each round using RotWord, SubWord, and XOR with round constants (Rcon).
Question 12
(a) Explain the working of Elliptic Curve Cryptography algorithm. (7 marks)
Elliptic Curve Cryptography (ECC)
ECC is a public-key cryptographic approach based on the algebraic structure of elliptic curves over finite fields. It offers equivalent security to RSA with significantly smaller key sizes (256-bit ECC ≈ 3072-bit RSA).
Elliptic Curve Equation:
The general form of an elliptic curve over a prime field is:
y² = x³ + ax + b (mod p)
where 4a³ + 27b² ≠ 0 (ensures no singularities)
Elliptic Curve Visualization:
y
│ *
│ * *
│ * *
│ * * P + Q = R
│ * P *
│ * ●──────●─ ─ ─ ─ ─ ● (intersection)
│ * Q * │
├*─────────────*────────┼──── x
│* * │
│ * * * ● R = -R' reflected
│ * * *
│ * *
│ * *
│ * * *
│
Key Operations:
Point Addition (P + Q = R):
Given two points P(x₁, y₁) and Q(x₂, y₂) on the curve:
slope (λ) = (y₂ - y₁) / (x₂ - x₁) mod p
x₃ = λ² - x₁ - x₂ mod p
y₃ = λ(x₁ - x₃) - y₁ mod p
R = (x₃, y₃)
Point Doubling (P + P = 2P):
λ = (3x₁² + a) / (2y₁) mod p
x₃ = λ² - 2x₁ mod p
y₃ = λ(x₁ - x₃) - y₁ mod p
Scalar Multiplication: Computing kP (adding P to itself k times) is efficient, but finding k given P and kP is computationally hard — this is the Elliptic Curve Discrete Logarithm Problem (ECDLP).
ECC Key Generation:
- Choose an elliptic curve E over field Fp with a base point G of order n
- Select private key: d (random integer, 1 < d < n)
- Compute public key: Q = d × G (scalar multiplication)
ECC Encryption (ElGamal variant):
- Sender picks random k, computes C₁ = k × G
- Computes shared secret S = k × Q (recipient's public key)
- Ciphertext: (C₁, C₂) where C₂ = M + S
ECC Decryption:
- Recipient computes S = d × C₁ (using private key d)
- Recovers M = C₂ - S
Security: The hardness of ECDLP ensures that even knowing G and Q = dG, it is computationally infeasible to determine d.
(b) Explain the design of SHA-256 and its compression function deployed in blockchain. (7 marks)
SHA-256 (Secure Hash Algorithm - 256 bit)
SHA-256 produces a fixed 256-bit (32-byte) hash from any input message. It belongs to the SHA-2 family and operates using the Merkle-Damgård construction.
SHA-256 Design Overview:
┌──────────┐ ┌──────────┐ ┌──────────┐
│Message │ │ Padding │ │ Parsing │
│ (any len)│──►│ to mult │──►│into 512- │
│ │ │ of 512 │ │bit blocks│
└──────────┘ └──────────┘ └────┬─────┘
│
┌──────────────────────────┘
▼
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Block 1 │ │ Block 2 │ │ Block N │
└──────┬──────┘ └──────┬──────┘ └──────┬──────┘
│ │ │
▼ ▼ ▼
┌────────────┐ ┌────────────┐ ┌────────────┐
│Compression │ │Compression │ ... │Compression │
│ Function │───►│ Function │─── ──────│ Function │
└────────────┘ └────────────┘ └─────┬──────┘
▲ IV (H₀) │
(8 words) ▼
┌──────────────┐
│ 256-bit Hash │
└──────────────┘
Message Preprocessing:
- Padding: Append bit '1', then zeros, then 64-bit message length, so total length ≡ 0 mod 512
- Parsing: Divide padded message into 512-bit blocks
Compression Function (64 rounds):
The compression function takes a 512-bit block and the current 256-bit hash state (eight 32-bit words: a, b, c, d, e, f, g, h).
a b c d e f g h
│ │ │ │ │ │ │ │
▼ │ │ │ ▼ │ │ │
┌──────┐ │ │ │ ┌──────┐│ │ │
│ Σ0 │ │ │ │ │ Σ1 ││ │ │
└──┬───┘ │ │ │ └──┬───┘│ │ │
│ ▼ ▼ │ │ ▼ ▼ │
│ ┌─────────┐ │ │ ┌────────┐ │
│ │Majority │ │ │ │ Choose │ │
│ │(a,b,c) │ │ │ │(e,f,g) │ │
│ └────┬────┘ │ │ └───┬────┘ │
│ │ │ │ │ │
▼ ▼ │ ▼ ▼ ▼
┌───────────┐ │ ┌─────────────────┐
│ T1+T2 │ │ │ T1=h+Σ1+Ch+K+W │
└─────┬─────┘ │ └───────┬─────────┘
│ │ │
▼ ▼ ▼
a' b'=a c'=b d'=c e'=d+T1 f'=e g'=f h'=g
Each round computes:
- T1 = h + Σ1(e) + Ch(e,f,g) + Kₜ + Wₜ
- T2 = Σ0(a) + Maj(a,b,c)
- Ch(e,f,g) = (e AND f) XOR (NOT e AND g)
- Maj(a,b,c) = (a AND b) XOR (a AND c) XOR (b AND c)
- Σ0(a) = ROTR²(a) XOR ROTR¹³(a) XOR ROTR²²(a)
- Σ1(e) = ROTR⁶(e) XOR ROTR¹¹(e) XOR ROTR²⁵(e)
- Kₜ = Round constant (derived from cube roots of first 64 primes)
- Wₜ = Message schedule word (first 16 from block, rest derived)
Message Schedule: W₀–W₁₅ come directly from the block; for t=16..63:
Wₜ = σ1(Wₜ₋₂) + Wₜ₋₇ + σ0(Wₜ₋₁₅) + Wₜ₋₁₆
After 64 rounds, the output is added to the input hash state to produce the intermediate hash for the next block.
Module II - Blockchain Architecture — #### Question 13
Question 13
(a) Describe the generic elements of blockchain and its working with a diagram. (7 marks)
Generic Elements of Blockchain:
- Block: Container holding transaction data, timestamp, nonce, and hash pointers
- Chain: Linked sequence of blocks where each block references the previous block's hash
- Node: Participant in the network maintaining a copy of the ledger
- Consensus Mechanism: Protocol for nodes to agree on the valid state
- Cryptographic Hash: Ensures data integrity and immutability
- Distributed Ledger: Replicated database shared across all nodes
Blockchain Structure Diagram:
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Block 0 │ │ Block 1 │ │ Block 2 │
│ (Genesis) │ │ │ │ │
├─────────────────┤ ├─────────────────┤ ├─────────────────┤
│ Prev Hash: 0000 │◄───│ Prev Hash: A3F..│◄───│ Prev Hash: 7B2..│
│ Timestamp │ │ Timestamp │ │ Timestamp │
│ Nonce │ │ Nonce │ │ Nonce │
│ Merkle Root │ │ Merkle Root │ │ Merkle Root │
├─────────────────┤ ├─────────────────┤ ├─────────────────┤
│ Tx1, Tx2, Tx3 │ │ Tx4, Tx5, Tx6 │ │ Tx7, Tx8, Tx9 │
│ ... │ │ ... │ │ ... │
└─────────────────┘ └─────────────────┘ └─────────────────┘
Hash: A3F.. Hash: 7B2.. Hash: E91..
Working of Blockchain:
┌────────┐ 1. Initiate ┌───────────────┐
│ User │───Transaction──►│ Network │
└────────┘ │ (P2P Nodes) │
└───────┬───────┘
│
2. Broadcast to all nodes
│
▼
┌───────────────┐
│ Validation │
│ by Nodes │
└───────┬───────┘
│
3. Consensus mechanism
│
▼
┌───────────────┐
│ Block Created│
│ (Tx grouped) │
└───────┬───────┘
│
4. Block added to chain
│
▼
┌───────────────┐
│ Chain Updated│
│ on all Nodes │
└───────────────┘
│
5. Transaction confirmed
│
▼
┌───────────────┐
│ Complete │
└───────────────┘
Working Steps:
- A user initiates a transaction (e.g., transfer of value or data)
- The transaction is broadcast to all peer nodes in the network
- Network nodes validate the transaction using predefined rules (signature verification, sufficient balance, etc.)
- Validated transactions are collected into a candidate block by a miner/validator
- The consensus mechanism (PoW/PoS/etc.) determines which node proposes the next block
- Once consensus is reached, the new block is appended to the chain
- All nodes update their local copy of the ledger
- The transaction is confirmed as immutable
(b) Compare and Contrast Proof of Work (PoW), Proof of Stake (PoS), and Delegated Proof of Stake (DPoS) consensus mechanisms. (7 marks)
| Feature | Proof of Work (PoW) | Proof of Stake (PoS) | Delegated Proof of Stake (DPoS) |
|---|---|---|---|
| Selection Method | Solving cryptographic puzzle (finding nonce such that hash < target) | Validator selected based on stake (coins held and locked) | Token holders vote for delegates who validate blocks |
| Resource Required | Computational power (CPU/GPU/ASIC) | Cryptocurrency stake (collateral) | Voting power (token holdings) |
| Energy Consumption | Very high (mining hardware runs continuously) | Very low (no intensive computation) | Very low |
| Security Model | 51% attack requires majority hashpower | 51% attack requires majority of total stake | Requires corrupting majority of elected delegates |
| Throughput | Low (~7 TPS for Bitcoin) | Medium (~30+ TPS) | High (~1000+ TPS) |
| Decentralisation | Tends toward mining pool centralisation | Favours wealthy stakeholders | Semi-centralised (limited delegate set) |
| Finality | Probabilistic (more confirmations = more certain) | Often deterministic | Near-instant finality |
| Reward Mechanism | Block reward + transaction fees to miner | Transaction fees / interest to validator | Delegates share rewards with voters |
| Example Platforms | Bitcoin, Litecoin | Ethereum 2.0, Cardano | EOS, TRON, Lisk |
| Penalty for Misbehaviour | Wasted electricity (no block reward) | Slashing (stake confiscated) | Delegate voted out by community |
| Hardware Requirement | Specialised (ASICs, GPUs) | Standard computing | Standard computing |
| Block Time | ~10 min (Bitcoin) | ~12 sec (Ethereum) | ~0.5-3 sec |
PoW achieves Nakamoto consensus through computational work — miners compete to find a hash below a difficulty target. It is proven and battle-tested but wasteful in energy.
PoS replaces mining with staking — validators lock tokens as collateral, and the protocol selects validators proportional to their stake. Misbehaviour results in "slashing" (loss of staked funds).
DPoS introduces representative democracy — token holders elect a fixed number of delegates (e.g., 21 in EOS) who take turns producing blocks. This dramatically improves performance but sacrifices decentralisation.
Question 14
(a) Compare various types of blockchain and comment on the real world relevance of each type. (7 marks)
| Feature | Public Blockchain | Private Blockchain | Consortium Blockchain | Hybrid Blockchain |
|---|---|---|---|---|
| Access | Open to anyone | Restricted to single organisation | Restricted to group of organisations | Combination of public and private |
| Permission | Permissionless | Permissioned | Permissioned | Selective access control |
| Governance | Decentralised (community) | Centralised (single entity) | Semi-decentralised (member orgs) | Mixed governance |
| Transparency | Fully transparent | Limited to participants | Limited to consortium members | Configurable |
| Consensus | PoW, PoS (all nodes) | RAFT, PBFT (authorised nodes) | PBFT, PoA (member nodes) | Varies |
| Speed | Slow (high latency) | Fast (fewer nodes) | Moderate to fast | Moderate |
| Scalability | Limited | High | Moderate to high | High |
| Immutability | Very high | Can be overridden by admin | Depends on agreement | Partial |
| Energy Use | High (PoW) to Low (PoS) | Low | Low | Low to moderate |
| Trust Model | Trustless | Trust in organisation | Trust among consortium | Mixed |
Real-World Relevance:
Public Blockchain:
- Cryptocurrencies (Bitcoin, Ethereum) for decentralised finance
- Decentralised applications (dApps) requiring censorship resistance
- Token-based crowdfunding (ICOs/IDOs)
Private Blockchain:
- Enterprise supply chain management (Walmart using Hyperledger)
- Internal auditing and record keeping within corporations
- Healthcare data management within hospital networks
Consortium Blockchain:
- Banking and financial settlements (R3 Corda among banks)
- Trade finance (Marco Polo Network, we.trade)
- Industry-specific compliance (insurance claim processing)
Hybrid Blockchain:
- Government systems requiring public verification but private data (land registry)
- Enterprise solutions needing both public trust and data privacy (IBM Food Trust)
- Real estate transactions where ownership is public but details are private
(b) Describe the ecosystem of decentralisation. Explain the various methods of decentralisation. (7 marks)
Ecosystem of Decentralisation:
Decentralisation refers to the distribution of control, decision-making, and data storage away from a single central authority to a distributed network of participants. The ecosystem encompasses:
- Decentralised Finance (DeFi): Lending, borrowing, trading without intermediaries (Uniswap, Aave, Compound)
- Decentralised Storage: Distributed file systems (IPFS, Filecoin, Arweave)
- Decentralised Identity: Self-sovereign identity management (uPort, Civic)
- Decentralised Governance (DAOs): Community-driven decision making
- Decentralised Applications (dApps): Applications running on distributed networks
- Decentralised Autonomous Organisations: Entities governed by smart contracts and token holder votes
Methods of Decentralisation:
1. Architectural Decentralisation (Physical)
- Distribution of infrastructure across multiple physical nodes and geographic locations
- No single point of failure — if one node fails, the network continues
- Examples: Distributed server networks, P2P networks
- Measured by number of independent nodes and their geographic distribution
2. Political Decentralisation (Governance)
- No single entity controls or makes decisions for the entire system
- Governance distributed among stakeholders through voting mechanisms
- On-chain governance (protocol-level voting) vs. off-chain governance (social consensus)
- Examples: Bitcoin Improvement Proposals (BIPs), Ethereum governance
3. Logical Decentralisation (Data/Interface)
- Whether the system behaves as a single logical entity or multiple independent parts
- A blockchain is logically centralised (one shared state) but architecturally decentralised
- BitTorrent is logically decentralised (no single dataset, each swarm independent)
4. Economic Decentralisation (Incentives)
- Token economics and incentive structures that prevent wealth concentration
- Fair distribution mechanisms: mining, airdrops, yield farming
- Preventing monopolistic behaviour through protocol design
5. Network-Level Decentralisation
- Peer-to-peer communication without central servers
- Gossip protocols for information propagation
- Mesh networking and distributed hash tables (DHT)
- No DNS-like central authority for node discovery
6. Application-Level Decentralisation
- Smart contracts executing autonomously without central servers
- Frontend decentralisation using IPFS/ENS
- Decentralised oracles for external data (Chainlink)
Module III - Consensus Protocols and Bitcoin — #### Question 15
Question 15
(a) Explain how the Paxos protocol achieves consensus for crash fault tolerance. (7 marks)
Paxos Protocol
Paxos is a consensus protocol designed to achieve agreement among distributed nodes even when some nodes crash (fail-stop). It guarantees safety (all nodes agree on the same value) and liveness (progress is eventually made) under crash fault tolerance, tolerating up to f failures with 2f+1 nodes.
Roles in Paxos:
- Proposer: Proposes a value to be agreed upon
- Acceptor: Votes on proposals and stores accepted values
- Learner: Learns the agreed-upon value once consensus is reached
Two Phases of Paxos:
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 1: Prepare (Proposal Phase)
P->>A1: Prepare(n)
P->>A2: Prepare(n)
P->>A3: Prepare(n)
A1->>P: Promise(n, null)
A2->>P: Promise(n, null)
A3->>P: Promise(n, null)
Note over P,A3: Phase 2: Accept (Acceptance Phase)
P->>A1: Accept(n, v)
P->>A2: Accept(n, v)
P->>A3: Accept(n, v)
A1->>P: Accepted(n, v)
A2->>P: Accepted(n, v)
A3->>P: Accepted(n, v)
Note over P,L: Value Learned
A1->>L: Decided(v)
A2->>L: Decided(v)
Phase 1: Prepare (Proposal Phase)
- The Proposer selects a unique proposal number
n(higher than any it has used before) - Proposer sends
Prepare(n)to a majority of Acceptors - Each Acceptor receiving
Prepare(n):- If
nis higher than any previously seen proposal number:- Promises not to accept any proposal with number < n
- Returns
Promise(n, accepted_value)— the highest-numbered proposal it has already accepted (or null if none)
- Otherwise, ignores or rejects the request
- If
Phase 2: Accept (Acceptance Phase)
- If the Proposer receives promises from a majority of Acceptors:
- If any acceptor returned a previously accepted value, the Proposer must propose that value (highest-numbered one)
- Otherwise, it proposes its own value
v - Sends
Accept(n, v)to the majority
- Each Acceptor receiving
Accept(n, v):- If it has not promised to a higher proposal number: accepts and responds
Accepted(n, v) - Otherwise: rejects
- If it has not promised to a higher proposal number: accepts and responds
- Once a majority of Acceptors accept, consensus is reached and Learners are notified
Crash Fault Tolerance:
- If a Proposer crashes: another Proposer can take over with a higher proposal number
- If an Acceptor crashes: majority quorum ensures progress as long as >f nodes remain
- If a Learner crashes: it can recover by querying Acceptors
- The protocol never produces conflicting decisions because majority quorums always overlap
(b) List the fields of a Bitcoin transaction. Explain the payment process from a user perspective. (7 marks)
Bitcoin Transaction Fields:
| Field | Description |
|---|---|
| Version | Transaction format version (currently 1 or 2) |
| Input Count | Number of transaction inputs |
| Inputs (Vin) | Previous transaction hash, output index, scriptSig (unlocking script), sequence number |
| Output Count | Number of transaction outputs |
| Outputs (Vout) | Value (in satoshis), scriptPubKey (locking script/conditions for spending) |
| Locktime | Earliest time/block when transaction can be included in a block |
Payment Process from User Perspective:
Step 1: Wallet Setup
- User installs a Bitcoin wallet (software, hardware, or mobile)
- Wallet generates a private key and derives the corresponding public key and Bitcoin address
- User receives Bitcoin from an exchange, another user, or mining
Step 2: Initiating a Payment
- User enters recipient's Bitcoin address and the amount to send
- Wallet selects unspent transaction outputs (UTXOs) that collectively cover the payment amount
- User sets a transaction fee (higher fee = faster confirmation)
Step 3: Transaction Construction
- Wallet constructs the transaction:
- Inputs: References to UTXOs being spent
- Outputs: Recipient's address with payment amount + change address with remaining balance
- Example: Sending 0.5 BTC from a 1.0 BTC UTXO creates two outputs: 0.5 to recipient, 0.4997 back as change (0.0003 fee)
Step 4: Signing
- Wallet signs each input with the user's private key
- This proves ownership of the funds without revealing the private key
- Digital signature is placed in the scriptSig field
Step 5: Broadcasting
- Signed transaction is broadcast to the Bitcoin P2P network
- Nodes validate the transaction (valid signatures, sufficient inputs, no double-spend)
- Valid transactions enter the mempool (unconfirmed transaction pool)
Step 6: Mining and Confirmation
- Miners select transactions from the mempool and include them in a candidate block
- Once a miner solves the PoW puzzle, the block (including the transaction) is added to the chain
- After 1 confirmation, the payment is visible; after 6 confirmations, it is considered final
Step 7: Receipt
- Recipient's wallet detects the transaction in a confirmed block
- Funds become spendable as a new UTXO owned by the recipient
Question 16
(a) How does PBFT achieve consensus in the presence of Byzantine faults? (7 marks)
Practical Byzantine Fault Tolerance (PBFT)
PBFT is a consensus algorithm that tolerates up to f Byzantine (arbitrary/malicious) faults in a network of 3f+1 nodes. Unlike Paxos which only handles crash faults, PBFT handles nodes that may lie, send conflicting messages, or collude.
Roles:
- Client: Sends request to the network
- Primary (Leader): Orders requests and initiates consensus
- Replicas (Backups): Validate and execute requests
PBFT achieves consensus in three phases:
sequenceDiagram
participant C as Client
participant P as Primary (Node 0)
participant R1 as Replica 1
participant R2 as Replica 2
participant R3 as Replica 3
C->>P: Request(operation)
Note over P,R3: Phase 1: Pre-Prepare
P->>R1: Pre-Prepare(v, n, d)
P->>R2: Pre-Prepare(v, n, d)
P->>R3: Pre-Prepare(v, n, d)
Note over P,R3: Phase 2: Prepare
R1->>P: Prepare(v, n, d, R1)
R1->>R2: Prepare(v, n, d, R1)
R1->>R3: Prepare(v, n, d, R1)
R2->>P: Prepare(v, n, d, R2)
R2->>R1: Prepare(v, n, d, R2)
R2->>R3: Prepare(v, n, d, R2)
R3->>P: Prepare(v, n, d, R3)
R3->>R1: Prepare(v, n, d, R3)
R3->>R2: Prepare(v, n, d, R3)
Note over P,R3: Phase 3: Commit
P->>R1: Commit(v, n, d, P)
P->>R2: Commit(v, n, d, P)
P->>R3: Commit(v, n, d, P)
R1->>P: Commit(v, n, d, R1)
R2->>P: Commit(v, n, d, R2)
R3->>P: Commit(v, n, d, R3)
Note over P,R3: Execute and Reply
P->>C: Reply(result)
R1->>C: Reply(result)
R2->>C: Reply(result)
R3->>C: Reply(result)
Phase 1: Pre-Prepare
- Client sends request to the Primary
- Primary assigns a sequence number
nin viewvand multicastsPre-Prepare(v, n, d, m)to all replicas d= digest of messagem- Replicas accept if: they are in view v, sequence number is valid, and they haven't accepted a conflicting pre-prepare
Phase 2: Prepare
- Each replica that accepts the pre-prepare multicasts
Prepare(v, n, d, i)to all other nodes - A node enters "prepared" state when it has the pre-prepare AND 2f matching prepare messages (total 2f+1 agreements on ordering)
- This guarantees that non-faulty nodes agree on the order of requests within a view
Phase 3: Commit
- Once prepared, each node multicasts
Commit(v, n, d, i)to all other nodes - A node is "committed" when it collects 2f+1 commit messages
- This ensures that even across view changes, the decision persists
- The node executes the operation and sends Reply to the client
Client Verification:
- Client waits for f+1 identical replies from different nodes
- Since at most f nodes are Byzantine, f+1 matching replies guarantee at least one honest node confirmed the result
View Change (Leader Failure):
- If replicas suspect the Primary is faulty (timeout), they initiate a view change
- New primary is selected (typically node v+1 mod N)
- Ensures liveness even when the leader is Byzantine
(b) Describe the role of a Bitcoin miner. Explain the Bitcoin mining process with a diagram. (7 marks)
Role of a Bitcoin Miner:
- Transaction Validation: Miners verify that transactions are legitimate (valid signatures, no double-spending, correct format)
- Block Construction: Miners collect valid unconfirmed transactions from the mempool and assemble them into a candidate block
- Proof of Work: Miners expend computational resources to find a valid nonce that produces a block hash below the network's difficulty target
- Network Security: Mining secures the network by making it computationally expensive to alter transaction history
- Coin Issuance: Miners create new bitcoins through the coinbase transaction (block reward), serving as the monetary policy mechanism
Bitcoin Mining Process:
┌─────────────────────────────────────────────────────────┐
│ MINING PROCESS │
└─────────────────────────────────────────────────────────┘
┌──────────┐ ┌─────────────────────┐
│ Mempool │────►│ Select Transactions │
│(Unconfirmed │ (by fee priority) │
│ Txns) │ └──────────┬──────────┘
└──────────┘ │
▼
┌──────────────────────────┐
│ Construct Candidate │
│ Block: │
│ ┌────────────────────┐ │
│ │ Block Header: │ │
│ │ - Prev Block Hash │ │
│ │ - Merkle Root │ │
│ │ - Timestamp │ │
│ │ - Difficulty │ │
│ │ - Nonce = 0 │ │
│ ├────────────────────┤ │
│ │ Coinbase Tx │ │
│ │ (reward → miner) │ │
│ ├────────────────────┤ │
│ │ Tx1, Tx2, ... TxN │ │
│ └────────────────────┘ │
└────────────┬─────────────┘
│
▼
┌──────────────────────────┐
│ Compute Block Hash: │
│ Hash = SHA256(SHA256( │
│ Block Header)) │
└────────────┬─────────────┘
│
▼
┌──────────────────────────┐
│ Hash < Target? │
│ │
│ NO ──► Increment Nonce │──┐
│ and try again │ │
└──────────┬───────────────┘ │
│ │
│ YES │
▼ │
┌──────────────────────────┐ │
│ Block Found! │ │
│ Broadcast to Network │ │
└────────────┬─────────────┘ │
│ │
▼ │
┌──────────────────────────┐ │
│ Other Nodes Verify │ │
│ and Add to Chain │ │
└──────────────────────────┘ │
│
◄─────────────────────────────┘
(Billions of iterations)
Detailed Mining Steps:
-
Transaction Collection: Miner gathers unconfirmed transactions from the mempool, prioritising those with higher fees per byte
-
Merkle Tree Construction: All selected transactions are hashed pairwise into a Merkle tree; the root hash is placed in the block header
-
Block Header Assembly:
- Previous block hash (links to chain)
- Merkle root (commits to all transactions)
- Timestamp, difficulty target bits
- Nonce (32-bit value to be varied)
-
Hash Computation (PoW): Miner repeatedly:
- Hashes the block header using double-SHA256
- Checks if resulting hash ≤ difficulty target
- If not, increments nonce (or modifies coinbase extra nonce) and repeats
- Current network performs ~400 EH/s (400 × 10¹⁸ hashes/second)
-
Block Propagation: Upon finding a valid nonce, the miner broadcasts the block to all peers
-
Reward Collection: The miner receives:
- Block subsidy (currently 3.125 BTC, halves every 210,000 blocks)
- Sum of all transaction fees in the block
Module IV - Smart Contracts and Use Cases — #### Question 17
Question 17
(a) Explain the aspects and working of Decentralized Applications (DApps). (7 marks)
Aspects of DApps:
Decentralized Applications (DApps) are applications that run on a peer-to-peer blockchain network rather than a single centralized server. They possess four key aspects:
-
Open Source: The codebase of a DApp is publicly available for inspection. This transparency allows anyone to verify the application logic, audit for vulnerabilities, and propose improvements. No single entity controls the source code.
-
Decentralized: DApps store data and records on a distributed blockchain ledger. No central authority owns or controls the application. This eliminates single points of failure and censorship.
-
Incentivized: DApps use cryptographic tokens or digital assets to reward validators and participants who contribute computational resources to the network. Miners or stakers receive tokens for maintaining consensus.
-
Protocol/Algorithm: The community of users agrees upon a consensus mechanism (e.g., Proof of Work, Proof of Stake) to validate transactions and generate tokens. This protocol governs how the network reaches agreement.
Working of DApps:
┌─────────────────────────────────────────────────┐
│ DApp Architecture │
├─────────────────────────────────────────────────┤
│ │
│ ┌──────────┐ ┌──────────────────┐ │
│ │ User │ │ Front-End UI │ │
│ │ (Browser)│◄──────►│ (HTML/JS/CSS) │ │
│ └──────────┘ └────────┬─────────┘ │
│ │ │
│ Web3.js / Ethers.js │
│ │ │
│ ┌────────▼─────────┐ │
│ │ Smart Contracts │ │
│ │ (Backend Logic) │ │
│ └────────┬─────────┘ │
│ │ │
│ ┌────────▼─────────┐ │
│ │ Blockchain │ │
│ │ Network (EVM) │ │
│ └──────────────────┘ │
└─────────────────────────────────────────────────┘
How DApps Run on Blockchain:
-
Front-End Layer: The user interface is typically built with standard web technologies (HTML, CSS, JavaScript). It can be hosted on decentralized storage like IPFS or traditionally on web servers.
-
Web3 Middleware: Libraries such as Web3.js or Ethers.js act as the bridge between the front-end and the blockchain. They connect to nodes via JSON-RPC calls, enabling the UI to read blockchain state and submit transactions.
-
Smart Contract Layer: The backend logic resides in smart contracts deployed on the blockchain. These are immutable, self-executing programs written in languages like Solidity. When a user triggers an action, a transaction is sent to the smart contract.
-
Blockchain Execution: The transaction is broadcast to the network, validated by nodes, and executed by the Ethereum Virtual Machine (EVM). Once included in a block, the state change becomes permanent and verifiable by all participants.
-
Interaction Flow: A user connects their wallet (e.g., MetaMask), signs a transaction, which is then broadcast to the network. Miners/validators include it in a block, the smart contract executes, and the updated state is reflected back in the UI.
DApps differ from traditional apps because there is no central server that can be shut down, no single database that can be corrupted, and no administrator who can unilaterally alter the rules.
(b) Illustrate with a use case, the application of blockchain technology in the government sector. (7 marks)
Use Case: Blockchain-Based Land Registry System
Land registration in many countries suffers from fraud, corruption, lost records, and lengthy bureaucratic processes. A blockchain-based land registry provides an immutable, transparent, and tamper-proof system for recording property ownership.
Problem Statement:
Traditional land registries rely on paper-based or centralized digital records that are prone to forgery, unauthorized alterations, and disputes. Duplicate titles, ghost ownership, and bribery in land offices are common issues.
Blockchain Solution:
┌─────────────────────────────────────────────────────────────┐
│ Blockchain Land Registry Workflow │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────┐ ┌──────────────┐ ┌───────────────┐ │
│ │ Property │ │ Government │ │ Blockchain │ │
│ │ Owner │───►│ Land Office │───►│ Network │ │
│ └──────────┘ └──────────────┘ └───────┬───────┘ │
│ │ │ │
│ │ ┌────────────────┐ │ │
│ │ │ Verification │◄──────────┘ │
│ │ │ Nodes (Banks, │ │
│ │ │ Courts, Govt) │ │
│ │ └────────┬───────┘ │
│ │ │ │
│ │ ┌────────▼───────┐ │
│ │ │ Smart Contract│ │
│ │ │ Validates & │ │
│ │ │ Records Title │ │
│ │ └────────┬───────┘ │
│ │ │ │
│ ◄──────────────────┘ │
│ (Digital Title Deed Issued) │
│ │
│ Transfer Flow: │
│ Seller ──► Initiates Transfer ──► Smart Contract │
│ │ │ │
│ │ Buyer Confirms + Payment ────┘ │
│ │ │ │
│ │ Govt Node Approves │
│ │ │ │
│ ▼ Title Updated on Blockchain │
│ (Old title invalidated, new title minted) │
└─────────────────────────────────────────────────────────────┘
Implementation Details:
-
Registration: Property owners submit documents (survey plans, identity proof, sale deeds) to the land office. After physical verification, the land office creates a digital record on the blockchain via a smart contract.
-
Immutable Records: Once registered, the ownership record cannot be altered or deleted. Any transfer of ownership creates a new transaction linked to the previous one, forming a complete chain of title history.
-
Smart Contract for Transfer: When land is sold, a smart contract automates the transfer process — verifying that the seller is the legitimate owner, confirming payment receipt, obtaining government approval, and updating ownership records atomically.
-
Multi-Party Verification: Government bodies, banks, and courts operate validator nodes. A transfer requires consensus among these parties, preventing unilateral fraud.
-
Transparency and Access: Citizens can verify ownership records without visiting government offices. Banks can instantly verify property titles before issuing loans.
Benefits:
- Eliminates title fraud and duplicate registrations
- Reduces processing time from weeks to minutes
- Creates auditable trail of all ownership changes
- Reduces corruption through transparent automation
- Provides dispute resolution through immutable history
Real-World Examples: Sweden (Lantmäteriet), Georgia (National Agency of Public Registry), and India (Andhra Pradesh) have piloted blockchain-based land registries.
Question 18
(a) Discuss the legal and ethical implications of blockchain technology. (7 marks)
Blockchain technology, while revolutionary, raises significant legal and ethical concerns that must be addressed for mainstream adoption. The following are four key implications:
1. Privacy and GDPR Compliance (Right to be Forgotten vs. Immutability)
Blockchain's core feature — immutability — directly conflicts with data protection regulations like the EU's General Data Protection Regulation (GDPR). Article 17 of GDPR grants individuals the "right to erasure," allowing them to request deletion of personal data. However, once data is recorded on a blockchain, it cannot be modified or deleted. This creates a fundamental tension between regulatory compliance and blockchain architecture. Solutions being explored include off-chain storage of personal data with only hashes on-chain, zero-knowledge proofs, and permissioned blockchains where access can be restricted.
2. Regulatory and Jurisdictional Challenges
Blockchain networks operate across international boundaries without a central authority, making it unclear which jurisdiction's laws apply. A transaction initiated in one country, validated by nodes in another, and affecting parties in a third country raises complex questions about applicable law, taxation, and enforcement. Different countries have varying and often conflicting regulations — cryptocurrency may be legal tender in one jurisdiction and banned in another. This regulatory fragmentation creates uncertainty for businesses and users.
3. Money Laundering and Illicit Activities
The pseudonymous nature of blockchain transactions has raised concerns about facilitating money laundering, terrorist financing, and other illicit activities. While transactions are publicly visible, connecting wallet addresses to real-world identities is difficult without KYC (Know Your Customer) mechanisms. Regulatory bodies have responded with Anti-Money Laundering (AML) requirements for cryptocurrency exchanges, but decentralized exchanges and privacy coins continue to pose challenges. The ethical question arises: should financial privacy be sacrificed for regulatory oversight?
4. Environmental and Energy Consumption Concerns
Proof of Work consensus mechanisms (as used in Bitcoin) consume enormous amounts of electricity — comparable to small countries. This raises ethical concerns about environmental sustainability and resource allocation. The carbon footprint of mining operations contributes to climate change, leading to questions about whether the benefits of decentralization justify the environmental cost. While Proof of Stake and other energy-efficient alternatives exist, the ethical responsibility of technology designers to consider environmental impact remains a significant discussion point.
Additional Considerations:
- Smart Contract Liability: When a smart contract executes incorrectly (due to bugs), determining legal liability is unclear. Code may be "law" on the blockchain, but traditional legal systems may not recognize autonomous code execution as binding.
- Immutable Fraud: If fraudulent data is recorded on a blockchain, the permanence of the record complicates remediation and victim recovery.
- Digital Divide: Blockchain-based systems may exclude populations without technological access, raising equity concerns in government applications.
(b) Explain the generic data flow of an Oracle in the context of smart contracts. Name three types of Oracles. (7 marks)
Oracle Data Flow in Smart Contracts:
Smart contracts on the blockchain are deterministic and isolated — they cannot natively access external data (prices, weather, sports scores, API responses). Oracles serve as the bridge between the off-chain world and on-chain smart contracts, providing trusted external data.
┌───────────────────────────────────────────────────────┐
│ Oracle Generic Data Flow │
├───────────────────────────────────────────────────────┤
│ │
│ ┌─────────────┐ │
│ │ External │ (APIs, IoT devices, databases) │
│ │ Data Source │ │
│ └──────┬──────┘ │
│ │ │
│ ▼ │
│ ┌─────────────┐ │
│ │ Oracle │ 1. Fetches external data │
│ │ Service │ 2. Validates/aggregates data │
│ │ │ 3. Formats for on-chain use │
│ └──────┬──────┘ │
│ │ │
│ ▼ (Submits transaction with data) │
│ ┌─────────────┐ │
│ │ Oracle │ On-chain contract that stores │
│ │ Contract │ and serves verified data │
│ └──────┬──────┘ │
│ │ │
│ ▼ (Callback / data response) │
│ ┌─────────────┐ │
│ │ Consumer │ Smart contract that requested │
│ │ Smart │ external data and uses it │
│ │ Contract │ in its business logic │
│ └─────────────┘ │
│ │
│ Flow: Request ──► Fetch ──► Validate ──► Deliver │
└───────────────────────────────────────────────────────┘
Step-by-Step Data Flow:
- Request: A smart contract emits an event or calls an oracle contract function, specifying what external data it needs (e.g., ETH/USD price).
- Detection: Off-chain oracle nodes monitor the blockchain for these data requests.
- Fetching: The oracle service queries external data sources (APIs, web services, IoT sensors).
- Validation: The oracle validates, aggregates, and formats the data. In decentralized oracles, multiple nodes independently fetch and reach consensus on the data.
- Delivery: The oracle submits an on-chain transaction containing the data to the oracle contract.
- Callback: The oracle contract calls back the requesting smart contract with the verified data, which then executes its logic based on the received information.
Three Types of Oracles:
1. Software Oracles (Input Oracles)
Software oracles fetch data from online sources such as websites, APIs, and databases. They provide information like cryptocurrency prices, flight statuses, exchange rates, or temperature data. Examples include Chainlink Price Feeds that aggregate price data from multiple exchanges. They are the most common type and operate in real-time, continuously updating on-chain data.
2. Hardware Oracles (IoT Oracles)
Hardware oracles interface with the physical world through IoT devices, sensors, barcode scanners, and RFID readers. They translate real-world events into digital values that smart contracts can process. For example, a supply chain smart contract might use hardware oracles to confirm that a shipment has arrived at a specific GPS location or that a temperature sensor confirmed cold-chain compliance.
3. Consensus-Based Oracles (Decentralized Oracles)
Rather than relying on a single data source (which creates a single point of failure), consensus-based oracles use multiple independent nodes that independently fetch data and reach agreement through a consensus mechanism. If one node provides incorrect data, it is outvoted and potentially penalized (staking/slashing). Chainlink and Band Protocol are prominent examples. This approach solves the "oracle problem" — ensuring that the data bridge itself remains trustworthy and decentralized.
Module V - Ethereum and Solidity Programming — #### Question 19
Question 19
(a) Discuss the various control structures available in the Solidity programming language with examples. (7 marks)
Relevance of Solidity:
Solidity is a statically-typed, contract-oriented programming language designed specifically for implementing smart contracts on the Ethereum Virtual Machine (EVM). It is the primary language for Ethereum development, enabling developers to write self-executing contracts that manage digital assets, implement business logic, and create decentralized applications. Its syntax is influenced by JavaScript, C++, and Python.
1. Conditional Statements (if, else if, else)
Conditional statements allow smart contracts to execute different code paths based on conditions:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract ConditionalExample {
function checkValue(uint256 _value) public pure returns (string memory) {
if (_value > 100) {
return "High";
} else if (_value > 50) {
return "Medium";
} else {
return "Low";
}
}
// Ternary operator
function max(uint256 a, uint256 b) public pure returns (uint256) {
return a >= b ? a : b;
}
}
2. Loop Structures (for, while, do-while)
Loops enable repetitive execution. However, in Solidity, loops must be used cautiously due to gas costs — unbounded loops can cause transactions to fail.
contract LoopExample {
uint256[] public numbers;
// For loop
function sumArray() public view returns (uint256) {
uint256 total = 0;
for (uint256 i = 0; i < numbers.length; i++) {
total += numbers[i];
}
return total;
}
// While loop
function factorial(uint256 n) public pure returns (uint256) {
uint256 result = 1;
uint256 i = 1;
while (i <= n) {
result *= i;
i++;
}
return result;
}
// Do-while loop
function countDigits(uint256 n) public pure returns (uint256) {
uint256 count = 0;
do {
count++;
n /= 10;
} while (n > 0);
return count;
}
}
3. Function Modifiers
Modifiers are reusable code blocks that alter the behavior of functions. They are commonly used for access control, input validation, and state checks. The _; placeholder indicates where the modified function's body executes.
contract ModifierExample {
address public owner;
bool public paused;
constructor() {
owner = msg.sender;
paused = false;
}
// Access control modifier
modifier onlyOwner() {
require(msg.sender == owner, "Not the owner");
_;
}
// State check modifier
modifier whenNotPaused() {
require(!paused, "Contract is paused");
_;
}
// Input validation modifier
modifier validAddress(address _addr) {
require(_addr != address(0), "Invalid address");
_;
}
// Function using multiple modifiers
function transfer(address _to, uint256 _amount)
public
onlyOwner
whenNotPaused
validAddress(_to)
{
// Transfer logic here
}
function pause() public onlyOwner {
paused = true;
}
}
Additional control flow mechanisms include require() and revert() for validation, break and continue within loops, and return for early function exit.
(b) Write a Solidity smart contract for a simple voting system. Explain the logic. (7 marks)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Simple Voting System
/// @notice Allows an admin to register candidates and voters to cast votes
contract VotingSystem {
// Struct to store candidate information
struct Candidate {
uint256 id;
string name;
uint256 voteCount;
}
// Struct to store voter information
struct Voter {
bool isRegistered;
bool hasVoted;
uint256 votedCandidateId;
}
// State variables
address public admin; // Election administrator
mapping(uint256 => Candidate) public candidates; // Candidate ID => Candidate
mapping(address => Voter) public voters; // Voter address => Voter
uint256 public candidateCount; // Total number of candidates
uint256 public totalVotes; // Total votes cast
bool public votingActive; // Voting status flag
// Events for transparency
event CandidateRegistered(uint256 id, string name);
event VoterRegistered(address voter);
event VoteCast(address voter, uint256 candidateId);
event VotingStarted();
event VotingEnded();
// Modifier: only admin can call
modifier onlyAdmin() {
require(msg.sender == admin, "Only admin can perform this action");
_;
}
// Modifier: voting must be active
modifier votingIsActive() {
require(votingActive, "Voting is not active");
_;
}
/// @notice Constructor sets the deployer as admin
constructor() {
admin = msg.sender;
votingActive = false;
}
/// @notice Register a new candidate (admin only)
/// @param _name Name of the candidate
function registerCandidate(string memory _name) public onlyAdmin {
require(!votingActive, "Cannot add candidates during voting");
candidateCount++;
candidates[candidateCount] = Candidate(candidateCount, _name, 0);
emit CandidateRegistered(candidateCount, _name);
}
/// @notice Register a voter (admin only)
/// @param _voter Address of the voter to register
function registerVoter(address _voter) public onlyAdmin {
require(!voters[_voter].isRegistered, "Voter already registered");
voters[_voter] = Voter(true, false, 0);
emit VoterRegistered(_voter);
}
/// @notice Start the voting period (admin only)
function startVoting() public onlyAdmin {
require(candidateCount > 0, "No candidates registered");
votingActive = true;
emit VotingStarted();
}
/// @notice Cast a vote for a candidate
/// @param _candidateId ID of the candidate to vote for
function vote(uint256 _candidateId) public votingIsActive {
Voter storage sender = voters[msg.sender];
require(sender.isRegistered, "You are not a registered voter");
require(!sender.hasVoted, "You have already voted");
require(_candidateId > 0 && _candidateId <= candidateCount,
"Invalid candidate ID");
// Record the vote
sender.hasVoted = true;
sender.votedCandidateId = _candidateId;
candidates[_candidateId].voteCount++;
totalVotes++;
emit VoteCast(msg.sender, _candidateId);
}
/// @notice End the voting period (admin only)
function endVoting() public onlyAdmin {
votingActive = false;
emit VotingEnded();
}
/// @notice Get candidate details
function getCandidate(uint256 _id) public view
returns (string memory name, uint256 voteCount)
{
require(_id > 0 && _id <= candidateCount, "Invalid candidate ID");
Candidate memory c = candidates[_id];
return (c.name, c.voteCount);
}
/// @notice Get the winner (candidate with most votes)
function getWinner() public view
returns (string memory winnerName, uint256 winnerVotes)
{
require(!votingActive, "Voting is still active");
require(totalVotes > 0, "No votes cast");
uint256 maxVotes = 0;
uint256 winnerId = 0;
for (uint256 i = 1; i <= candidateCount; i++) {
if (candidates[i].voteCount > maxVotes) {
maxVotes = candidates[i].voteCount;
winnerId = i;
}
}
winnerName = candidates[winnerId].name;
winnerVotes = candidates[winnerId].voteCount;
}
}
Logic Explanation:
-
Data Structures: The
Candidatestruct holds an ID, name, and vote count. TheVoterstruct tracks registration status, whether they have voted, and their choice. Mappings provide O(1) lookup for both. -
Access Control: The
onlyAdminmodifier restricts administrative functions (registering candidates/voters, starting/ending elections) to the contract deployer. -
Workflow: Admin registers candidates → Admin registers eligible voters → Admin starts voting → Voters cast ballots → Admin ends voting → Anyone can query results.
-
Vote Integrity: The contract prevents double voting (
hasVotedcheck), unregistered voting (isRegisteredcheck), and invalid candidate selection (bounds check). Once cast, votes are immutable on the blockchain. -
Result Tabulation: The
getWinner()function iterates through candidates to find the one with the highest vote count, only callable after voting ends.
Question 20
(a) Compare Bitcoin and Ethereum blockchains. Explain the major elements of the Ethereum blockchain with diagrams. (7 marks)
Comparison of Bitcoin and Ethereum:
| Feature | Bitcoin | Ethereum |
|---|---|---|
| Purpose | Digital currency / Store of value | Programmable blockchain platform |
| Consensus | Proof of Work (SHA-256) | Proof of Stake (post-Merge 2022) |
| Block Time | ~10 minutes | ~12 seconds |
| Language | Script (limited, non-Turing complete) | Solidity (Turing complete) |
| Smart Contracts | Limited (basic scripts) | Full smart contract support |
| Supply | Capped at 21 million BTC | No hard cap (deflationary post-EIP-1559) |
| State Model | UTXO (Unspent Transaction Output) | Account-based model |
| Primary Use | Peer-to-peer payments | DApps, DeFi, NFTs, DAOs |
| VM | None (script interpreter) | Ethereum Virtual Machine (EVM) |
| Founder | Satoshi Nakamoto (2009) | Vitalik Buterin (2015) |
Major Elements of the Ethereum Blockchain:
┌─────────────────────────────────────────────────────┐
│ Ethereum Blockchain Architecture │
├─────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────────────────────────────┐ │
│ │ WORLD STATE │ │
│ │ (Global mapping: Address → Account State) │ │
│ └──────────────────────┬──────────────────────┘ │
│ │ │
│ ┌────────────────┼────────────────┐ │
│ ▼ ▼ ▼ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ EOA │ │ EOA │ │ Contract │ │
│ │ Account │ │ Account │ │ Account │ │
│ │ - Nonce │ │ - Nonce │ │ - Nonce │ │
│ │ - Balance │ │ - Balance │ │ - Balance │ │
│ │ │ │ │ │ - CodeHash │ │
│ │ │ │ │ │ - StorageRoot│ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ │
│ ┌─────────────────────────────────────────────┐ │
│ │ BLOCK STRUCTURE │ │
│ │ ┌────────────────────────────────────┐ │ │
│ │ │ Block Header │ │ │
│ │ │ - Parent Hash │ │ │
│ │ │ - State Root (Merkle Patricia Trie) │ │ │
│ │ │ - Transactions Root │ │ │
│ │ │ - Receipts Root │ │ │
│ │ │ - Block Number, Timestamp, Gas Limit│ │ │
│ │ └────────────────────────────────────┘ │ │
│ │ ┌────────────────────────────────────┐ │ │
│ │ │ Transaction List [tx1, tx2, ...] │ │ │
│ │ └────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────┐ │
│ │ ETHEREUM VIRTUAL MACHINE (EVM) │ │
│ │ │ │
│ │ Bytecode ──► Stack Machine ──► State Change │ │
│ │ │ │
│ │ - 256-bit word size │ │
│ │ - Sandboxed execution environment │ │
│ │ - Deterministic (same input = same output) │ │
│ │ - Gas-metered computation │ │
│ └─────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────┘
1. Accounts: Ethereum has two account types:
- Externally Owned Accounts (EOA): Controlled by private keys, owned by users. Contain nonce (transaction count) and balance.
- Contract Accounts: Controlled by code. Contain nonce, balance, code hash (immutable bytecode), and storage root (persistent data).
2. Transactions: Messages sent from EOAs that trigger state changes. They contain sender, recipient, value, data (for contract calls), gas limit, and gas price.
3. Blocks: Containers of ordered transactions. Each block header contains the parent hash (chaining blocks), state root, transaction root, and receipts root — all as Merkle Patricia Tries enabling efficient verification.
4. World State: The global state is a mapping from every address to its account state, stored as a Merkle Patricia Trie. Each transaction transitions the world from one state to the next.
5. EVM: A stack-based virtual machine that executes smart contract bytecode. It is sandboxed, deterministic, and gas-metered, ensuring that all nodes produce identical results for the same input.
(b) Explain the transaction processing mechanism in Ethereum. Discuss the concept of gas and its impact on Ethereum transactions. (7 marks)
Ethereum Transaction Processing Mechanism:
┌───────────────────────────────────────────────────┐
│ Transaction Processing Pipeline │
├───────────────────────────────────────────────────┤
│ │
│ 1. INITIATION │
│ User creates tx → Signs with private key │
│ │ │
│ ▼ │
│ 2. PROPAGATION │
│ Broadcast to network → Enters mempool │
│ │ │
│ ▼ │
│ 3. VALIDATION │
│ - Valid signature? │
│ - Sufficient balance (value + gas)? │
│ - Nonce matches account nonce? │
│ - Gas limit >= intrinsic gas? │
│ │ │
│ ▼ │
│ 4. EXECUTION (by validator/miner) │
│ - Deduct upfront gas cost │
│ - Execute transaction (transfer or EVM code) │
│ - Track gas consumed per opcode │
│ - If out-of-gas: revert state, gas consumed │
│ - Refund unused gas to sender │
│ │ │
│ ▼ │
│ 5. INCLUSION & CONFIRMATION │
│ - Validator includes tx in proposed block │
│ - Block proposed to network │
│ - Other validators attest (PoS) │
│ - Block finalized after 2 epochs (~13 min) │
│ │
└───────────────────────────────────────────────────┘
Detailed Steps:
-
Initiation: A user constructs a transaction specifying the recipient, value, data payload, gas limit, and max fee. The transaction is signed using the sender's private key (ECDSA signature).
-
Propagation: The signed transaction is submitted to a node and broadcast via gossip protocol to the peer-to-peer network. It enters the mempool (transaction pool) where it awaits inclusion.
-
Validation: Nodes verify the transaction's signature, check that the sender's balance covers the value plus maximum gas cost, confirm the nonce is correct (preventing replay attacks), and ensure the gas limit meets minimum requirements.
-
Execution: The selected validator executes the transaction in the EVM. For simple transfers, value is moved between accounts. For contract interactions, the EVM executes bytecode instruction by instruction, with each opcode consuming a predefined amount of gas.
-
Finalization: The transaction is included in a block, which is proposed and attested to by validators under Proof of Stake. After sufficient attestations, the block becomes finalized and irreversible.
The Concept of Gas:
Gas is the unit measuring computational effort required to execute operations on Ethereum. It serves as the "fuel" for the EVM.
Key Components:
| Term | Definition |
|---|---|
| Gas Limit | Maximum gas units the sender is willing to consume |
| Gas Used | Actual gas consumed during execution |
| Base Fee | Minimum price per gas unit (algorithmically adjusted per block) |
| Priority Fee (Tip) | Additional fee paid to validators as incentive |
| Max Fee | Maximum total fee per gas the sender will pay |
Transaction Cost Formula:
Transaction Fee = Gas Used × (Base Fee + Priority Fee)
Refund = (Gas Limit - Gas Used) × Gas Price [returned to sender]
Why Gas Exists:
- Prevents infinite loops: Since Solidity is Turing-complete, gas ensures that every computation has a bounded cost. Programs that run out of gas are halted.
- Spam prevention: Attackers must pay for every computational step, making DoS attacks economically infeasible.
- Resource allocation: Gas creates a market-based mechanism for allocating limited block space to the highest-value transactions.
EIP-1559 (London Upgrade):
Introduced in August 2021, EIP-1559 reformed the fee mechanism:
- Base fee is burned (destroyed), making ETH deflationary during high usage
- Priority fee goes to validators as incentive
- Base fee adjusts dynamically: increases when blocks are >50% full, decreases when <50% full
- Provides more predictable fees and reduces overpayment
Impact on Transactions:
- Complex smart contract calls cost more gas than simple transfers (21,000 gas for a basic ETH transfer vs. potentially millions for complex DeFi operations)
- During network congestion, base fees rise, pricing out lower-value transactions
- Developers must optimize contract code to minimize gas consumption, affecting smart contract design decisions