Answer Key - CST428 Blockchain Technologies
Answer Key - CST428 Blockchain Technologies
Examination: October 2023 (Supplementary)
Course Code: CST428
Course Name: Blockchain Technologies
Total Marks: 100
Duration: 3 Hours
Modules Covered: All (1-5)
Scheme: 2019
PART A
Answer all questions, each carries 3 marks.
Question 1: List the major differences between symmetric and asymmetric cryptography (3 marks)
Symmetric Cryptography uses the same key for both encryption and decryption, while Asymmetric Cryptography uses a pair of keys (public and private).
Key Differences:
| Aspect | Symmetric Cryptography | Asymmetric Cryptography |
|---|---|---|
| Keys Used | Single shared secret key | Key pair (public + private keys) |
| Speed | Fast (suitable for large data) | Slower (complex mathematical operations) |
| Key Distribution | Difficult (secure channel needed) | Easier (public key can be shared openly) |
| Use Cases | Bulk data encryption | Key exchange, digital signatures, authentication |
| Examples | AES, DES, 3DES | RSA, ECC, ElGamal |
| Key Management | Challenging with many parties (n² keys for n parties) | Simpler (each party needs only one key pair) |
Question 2: Describe what distributed hash tables are and how they work (3 marks)
Distributed Hash Table (DHT) is a decentralized distributed system that provides a lookup service similar to a hash table, where key-value pairs are stored across multiple nodes in a network.
Key Features:
- Decentralized: No central authority; nodes collectively maintain the system
- Scalability: Efficiently handles millions of nodes
- Fault Tolerance: System continues functioning even if nodes fail
- Self-Organization: Nodes can join or leave dynamically
How DHT Works:
- Key-Value Storage: Data is stored as (key, value) pairs distributed across network nodes
- Hashing: A consistent hashing function maps both keys and node identifiers to the same identifier space
- Routing: Each node maintains routing information to locate keys, typically requiring O(log N) hops for N nodes
- Data Location: When searching for a key, the query is routed through nodes until reaching the node responsible for that key's range
- Responsibility: Each node is responsible for storing keys that fall within its assigned range of the identifier space
Applications: BitTorrent (file sharing), Bitcoin (peer discovery), IPFS (distributed file storage).
Question 3: Define blockchain and elaborate on the different terminologies used in the definition (3 marks)
Blockchain Definition: Blockchain is a distributed, decentralized, immutable ledger that records transactions in blocks, which are cryptographically linked together in a chronological chain, maintained by a peer-to-peer network using consensus mechanisms.
Key Terminologies:
-
Distributed: The ledger is replicated across multiple nodes in the network, with no single point of failure. Each participant maintains a copy of the entire blockchain.
-
Decentralized: No central authority controls the network. Decision-making and validation are distributed among network participants.
-
Immutable: Once data is recorded in a block and added to the chain, it cannot be altered or deleted without detection. This is ensured through cryptographic hashing.
-
Ledger: A record-keeping system that tracks all transactions chronologically, similar to an accounting ledger but digital and distributed.
-
Transactions: Individual operations or data records (e.g., cryptocurrency transfers, smart contract executions) that are grouped together into blocks.
-
Block: A container that holds a batch of validated transactions, along with metadata including timestamp, previous block hash, and nonce.
-
Cryptographically Linked: Each block contains the hash of the previous block, creating a tamper-evident chain where any modification would break the chain.
-
Consensus Mechanism: The protocol used by network nodes to agree on the current state of the blockchain (e.g., Proof of Work, Proof of Stake).
Question 4: List and explain the different types of blockchain (3 marks)
Blockchains are classified into three main types based on access control and network participation:
1. Public Blockchain (Permissionless)
- Access: Open to anyone; no restrictions on participation
- Participation: Anyone can read, write, and participate in consensus
- Transparency: Fully transparent; all transactions are visible
- Examples: Bitcoin, Ethereum, Litecoin
- Use Case: Cryptocurrencies, public decentralized applications
2. Private Blockchain (Permissioned)
- Access: Restricted to authorized participants only
- Participation: Controlled by a single organization; invitation-required
- Transparency: Limited visibility; transactions visible only to authorized members
- Examples: Hyperledger Fabric, R3 Corda
- Use Case: Enterprise internal record-keeping, supply chain within organization
3. Consortium/Federated Blockchain (Semi-Permissioned)
- Access: Restricted to a group of pre-selected organizations
- Participation: Multiple organizations jointly control the network
- Transparency: Partial transparency; visible to consortium members
- Examples: Energy Web Chain, IBM Food Trust
- Use Case: Inter-organizational collaboration (banking consortiums, supply chains)
4. Hybrid Blockchain
- Access: Combines public and private elements
- Participation: Some data public, some restricted to specific participants
- Transparency: Selective disclosure of information
- Examples: Dragonchain
- Use Case: Businesses requiring both transparency and privacy
Question 5: If your blockchain network has 6 Byzantine nodes, what is the minimum number of nodes that are required to ensure Byzantine fault tolerance using PBFT protocol? (3 marks)
Given:
- Number of Byzantine (faulty) nodes: f = 6
PBFT (Practical Byzantine Fault Tolerance) Formula:
The PBFT protocol requires a minimum of n = 3f + 1 total nodes to tolerate f Byzantine faults.
Calculation:
n = 3f + 1
n = 3(6) + 1
n = 18 + 1
n = 19 nodes
Answer: Minimum 19 total nodes are required
Explanation:
- Byzantine Nodes (f): 6 malicious or faulty nodes
- Honest Nodes Required: At least 3f + 1 = 19 total nodes
- Reasoning: PBFT requires more than two-thirds (2f + 1) of nodes to be honest for consensus. With 19 total nodes:
- Honest nodes: 19 - 6 = 13
- Required honest majority: 2f + 1 = 2(6) + 1 = 13 ✓
- This ensures that even with 6 Byzantine nodes, the 13 honest nodes form a majority
Key Principle: In PBFT, the system can tolerate up to ⌊(n-1)/3⌋ Byzantine nodes, where n is the total number of nodes. For 19 nodes: ⌊(19-1)/3⌋ = ⌊18/3⌋ = 6 Byzantine nodes can be tolerated.
Question 6: What is the Byzantine generals problem, and how is it relevant to blockchain design? (3 marks)
Byzantine Generals Problem is a classic distributed computing problem that illustrates the challenges of achieving consensus in a distributed system where some participants may be faulty or malicious.
The Problem Scenario:
- Multiple Byzantine army generals surround an enemy city
- Generals must agree on a common plan (attack or retreat)
- Communication is only by messenger
- Some generals may be traitors who send conflicting messages
- Loyal generals must agree on the same plan despite traitors' interference
Relevance to Blockchain:
-
Distributed Consensus Challenge: Blockchain networks are distributed systems where nodes must agree on the state of the ledger without a central authority, similar to generals agreeing without a commander.
-
Malicious Actors: In blockchain, some nodes may be controlled by attackers who attempt to:
- Submit conflicting transactions (double-spending)
- Create fraudulent blocks
- Disrupt consensus
-
Trust in Trustless Environment: Blockchain must achieve consensus even when some participants cannot be trusted, just as loyal generals must coordinate despite traitors.
-
Byzantine Fault Tolerance: Blockchain consensus mechanisms (PoW, PoS, PBFT) are designed to solve the Byzantine Generals Problem by ensuring agreement despite the presence of malicious nodes, typically tolerating up to f < n/3 faulty nodes.
Practical Impact: Understanding this problem is crucial for designing robust blockchain systems that maintain integrity and consistency in adversarial environments.
Question 7: What is a Sybil attack, and how does the Bitcoin network prevent it? (3 marks)
Sybil Attack is a security threat where a malicious actor creates multiple fake identities (nodes) to gain disproportionate influence over a network, potentially controlling consensus or disrupting network operations.
Attack Mechanism:
- Attacker creates many pseudonymous identities
- These fake nodes can outvote honest nodes
- Can manipulate consensus, censor transactions, or disrupt routing
How Bitcoin Prevents Sybil Attacks:
-
Proof of Work (PoW):
- Creating blocks requires significant computational work (mining)
- Each block requires finding a valid nonce that produces a hash below the target
- Simply creating multiple identities doesn't provide advantage; computational power matters, not node count
- Key Principle: "One-CPU-one-vote" instead of "one-IP-one-vote"
-
Economic Cost:
- Mining requires expensive hardware and electricity
- Creating fake identities is cheap, but each identity needs computational resources to be effective
- Attack cost is proportional to computational power, not number of identities
-
Longest Chain Rule:
- Network follows the chain with most accumulated proof-of-work
- Attacker would need >50% of network's computational power (51% attack) to consistently control consensus
- Multiple fake identities without computational power cannot influence this
-
Decentralized Mining:
- Mining power distributed across many independent miners globally
- Difficult for single attacker to acquire majority hashrate
Result: In Bitcoin, Sybil attacks are economically infeasible because influence depends on computational resources, not node count.
Question 8: What are smart contracts? (3 marks)
Smart Contract is a self-executing program stored on a blockchain that automatically enforces and executes the terms of an agreement when predefined conditions are met, without requiring intermediaries.
Key Characteristics:
- Self-Executing: Code automatically runs when triggering conditions are satisfied
- Immutable: Once deployed on blockchain, cannot be altered (depending on design)
- Transparent: Code and execution visible to all network participants
- Deterministic: Same inputs always produce same outputs
- Trustless: No need to trust counterparty; code enforces agreement
Components:
- Code Logic: Business rules and conditions written in programming language (e.g., Solidity)
- State Variables: Data stored on blockchain that the contract manages
- Functions: Methods that can be called to interact with the contract
- Events: Notifications emitted during execution for logging
How They Work:
- Contract deployed to blockchain with encoded rules
- External transaction triggers contract function
- Contract verifies conditions are met
- If conditions satisfied, contract automatically executes actions (transfer tokens, update data)
- State changes recorded permanently on blockchain
Example Use Cases:
- Cryptocurrency transfers with conditions
- Decentralized finance (DeFi) protocols
- Supply chain automation
- Digital identity management
- Voting systems
Platforms: Ethereum (primary platform), Binance Smart Chain, Cardano, Solana.
Question 9: What are the two types of accounts used in Ethereum and what are the differences between them? (3 marks)
Ethereum has two types of accounts that interact with the blockchain:
1. Externally Owned Account (EOA)
Characteristics:
- Controlled by private keys held by users
- No associated code
- Can initiate transactions
- Has an Ether balance
- Created by generating a key pair
Key Features:
- Address: Derived from public key (20-byte identifier)
- Control: User with private key has full control
- Actions: Can send transactions, transfer Ether, call smart contracts
- Cost: No cost to create or maintain (except for transaction fees)
2. Contract Account (CA)
Characteristics:
- Controlled by smart contract code
- Contains executable code (smart contract)
- Has an Ether balance
- Cannot initiate transactions on its own
- Created when smart contract is deployed
Key Features:
- Address: Generated when contract is deployed (based on creator address and nonce)
- Control: Controlled by contract code logic, not private keys
- Actions: Executes code when triggered by transactions from EOAs or other contracts
- Storage: Has persistent storage on blockchain
- Cost: Requires gas to deploy and execute
Key Differences:
| Aspect | Externally Owned Account (EOA) | Contract Account (CA) |
|---|---|---|
| Control | Private key | Smart contract code |
| Code | No code | Contains executable code |
| Transaction Initiation | Can initiate transactions | Cannot initiate; only responds |
| Creation | Free (key pair generation) | Requires deployment transaction |
| Storage | Only balance | Balance + code + storage |
| Purpose | User wallet | Autonomous programs |
Question 10: Explain different datatypes in solidity (3 marks)
Solidity supports various data types for smart contract development:
1. Value Types (Store Actual Data)
Boolean:
bool: true or false values- Example:
bool isActive = true;
Integers:
int/int256: Signed integers (-2²⁵⁵ to 2²⁵⁵-1)uint/uint256: Unsigned integers (0 to 2²⁵⁶-1)- Available in steps of 8:
uint8,uint16, ...,uint256 - Example:
uint256 balance = 1000;
Address:
address: 20-byte Ethereum addressaddress payable: Can receive Ether- Example:
address owner = 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb;
Fixed-Size Byte Arrays:
bytes1tobytes32: Fixed-length byte sequences- Example:
bytes32 hash;
Enums:
- User-defined type with named constants
- Example:
enum State { Created, Locked, Inactive }
2. Reference Types (Store Location of Data)
Arrays:
- Fixed-size:
uint[5] fixedArray; - Dynamic:
uint[] dynamicArray; - Methods: push, pop, length
Strings:
string: Dynamic UTF-8 encoded text- Example:
string public name = "MyToken";
Bytes (Dynamic):
bytes: Dynamically-sized byte array- Example:
bytes data;
Structs:
- Custom composite data types
struct Person {
string name;
uint age;
}
Mappings:
- Key-value pairs (hash tables)
- Example:
mapping(address => uint) public balances; - Note: Keys are not stored; values accessed via key lookup
3. Special Data Types
Function Types:
- Variables that store function references
- Example:
function(uint) external returns (uint) myFunction;
Data Location Specifiers:
storage: Persistent blockchain storage (expensive)memory: Temporary during function executioncalldata: Non-modifiable temporary location (for function parameters)
Example Using Multiple Types:
contract DataTypesExample {
uint256 public count; // Unsigned integer
address public owner; // Address
bool public isActive; // Boolean
string public name; // String
mapping(address => uint) public balances; // Mapping
uint[] public numbers; // Dynamic array
struct User { // Struct
string username;
uint age;
}
}
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 some of the main cryptographic properties of hash functions and how they are used in blockchain technology (7 marks)
Cryptographic Hash Function is a mathematical algorithm that takes an input of any size and produces a fixed-size output (hash value or digest) with specific security properties.
Main Cryptographic Properties:
1. Deterministic
- Same input always produces the same hash output
- Essential for verification: anyone can independently verify by re-computing the hash
- Example: SHA-256("hello") will always produce the same 256-bit hash
2. Pre-image Resistance (One-way Function)
- Given hash h, computationally infeasible to find input m such that hash(m) = h
- Cannot reverse-engineer the original data from its hash
- Strength: Makes hash functions suitable for password storage and commitments
3. Second Pre-image Resistance (Weak Collision Resistance)
- Given input m₁ and hash(m₁), computationally infeasible to find different m₂ where hash(m₁) = hash(m₂)
- Protects against finding alternative inputs with same hash
- Security Implication: Prevents substitution attacks
4. Collision Resistance (Strong Collision Resistance)
- Computationally infeasible to find any two different inputs m₁ and m₂ where hash(m₁) = hash(m₂)
- Strongest property; implies second pre-image resistance
- Importance: Critical for blockchain integrity
5. Avalanche Effect
- Small change in input produces drastically different output
- Single bit change in input changes approximately 50% of output bits
- Example: SHA-256("hello") vs SHA-256("hallo") produce completely different hashes
6. Fixed Output Size
- Regardless of input size, output is always fixed length
- SHA-256 always produces 256-bit (32-byte) hash
Use in Blockchain Technology:
1. Block Linking (Chain Integrity)
- Each block contains hash of previous block's header
- Creates tamper-evident chain: modifying any block changes its hash
- All subsequent blocks would need recalculation (computationally infeasible)
graph LR
A[Block N-1<br/>Hash: ABC123] --> B[Block N<br/>Prev Hash: ABC123<br/>Hash: DEF456]
B --> C[Block N+1<br/>Prev Hash: DEF456<br/>Hash: GHI789]
2. Proof of Work (Mining)
- Miners search for nonce that produces hash below target difficulty
- Pre-image resistance ensures finding solution requires brute force
- Collision resistance ensures solution is unique and verifiable
3. Transaction Integrity
- Each transaction is hashed to create unique identifier (TXID)
- Any modification to transaction changes its hash
- Enables quick verification of transaction authenticity
4. Merkle Trees
- Efficiently summarize all transactions in a block
- Root hash in block header represents all transactions
- Enables lightweight verification without downloading all transactions
5. Address Generation
- Cryptocurrency addresses derived from hashing public keys
- Provides shorter, more manageable identifiers
- Adds security layer (one-way function protects public key)
6. Digital Signatures
- Messages are hashed before signing (efficiency)
- Signature verifies both authenticity and data integrity
- Hash ensures fixed-size input to signature algorithm
Example - Bitcoin Block Hashing:
Block Header = Version + Prev Hash + Merkle Root + Timestamp + Difficulty + Nonce
Block Hash = SHA-256(SHA-256(Block Header))
Security Benefits:
- Immutability: Cannot alter historical data without detection
- Efficient Verification: Quick hash comparison instead of comparing entire data
- Integrity: Ensures data hasn't been tampered with
- Pseudonymity: Addresses derived from hashes provide privacy
(b) Explain public and private keys. Perform encryption and decryption using RSA for p=3; q=11, e=7; M=5 (7 marks)
Public and Private Keys:
Private Key:
- Secret key known only to the owner
- Used for decryption and digital signatures
- Must be kept secure and never shared
- Compromise of private key means loss of security
Public Key:
- Openly shared key available to everyone
- Used for encryption and signature verification
- Can be distributed freely without security risk
- Mathematically related to private key but computationally infeasible to derive private from public
Key Pair Relationship:
- Generated together as a mathematically related pair
- Data encrypted with public key can only be decrypted with corresponding private key
- Data signed with private key can be verified with corresponding public key
RSA Encryption and Decryption:
Given:
- p = 3
- q = 11
- e = 7 (public exponent)
- M = 5 (plaintext message)
Step 1: Calculate n (Modulus)
n = p × q
n = 3 × 11
n = 33
Step 2: Calculate φ(n) (Euler's Totient Function)
φ(n) = (p - 1) × (q - 1)
φ(n) = (3 - 1) × (11 - 1)
φ(n) = 2 × 10
φ(n) = 20
Step 3: Verify Public Exponent e
Check: gcd(e, φ(n)) = gcd(7, 20) = 1 ✓
e is valid as it is coprime to φ(n)
Public Key: (e, n) = (7, 33)
Step 4: Calculate Private Exponent d
We need to find d such that:
d × e ≡ 1 (mod φ(n))
d × 7 ≡ 1 (mod 20)
Using Extended Euclidean Algorithm or trial:
7d mod 20 = 1
Testing values:
d = 3: 7 × 3 = 21 = 20 + 1 ≡ 1 (mod 20) ✓
Private Key: (d, n) = (3, 33)
Verification:
d × e mod φ(n) = 3 × 7 mod 20 = 21 mod 20 = 1 ✓
Step 5: ENCRYPTION
Encrypt using public key (e, n):
C = M^e mod n
C = 5^7 mod 33
Calculate 5^7:
5^1 = 5
5^2 = 25
5^3 = 125 mod 33 = 125 - 3(33) = 125 - 99 = 26
5^4 = 5 × 26 = 130 mod 33 = 130 - 3(33) = 130 - 99 = 31
5^5 = 5 × 31 = 155 mod 33 = 155 - 4(33) = 155 - 132 = 23
5^6 = 5 × 23 = 115 mod 33 = 115 - 3(33) = 115 - 99 = 16
5^7 = 5 × 16 = 80 mod 33 = 80 - 2(33) = 80 - 66 = 14
Ciphertext: C = 14
Step 6: DECRYPTION
Decrypt using private key (d, n):
M = C^d mod n
M = 14^3 mod 33
Calculate 14^3:
14^1 = 14
14^2 = 196 mod 33 = 196 - 5(33) = 196 - 165 = 31
14^3 = 14 × 31 = 434 mod 33
434 ÷ 33 = 13 remainder 5
434 = 13(33) + 5
14^3 mod 33 = 5
Decrypted Message: M = 5 ✓
Summary:
| Parameter | Value |
|---|---|
| Prime p | 3 |
| Prime q | 11 |
| Modulus n | 33 |
| φ(n) | 20 |
| Public Key | (e=7, n=33) |
| Private Key | (d=3, n=33) |
| Plaintext M | 5 |
| Ciphertext C | 14 |
| Decrypted M | 5 ✓ |
Encryption: M = 5 → C = 5^7 mod 33 = 14
Decryption: C = 14 → M = 14^3 mod 33 = 5 ✓
The decrypted message matches the original plaintext, confirming the RSA encryption and decryption process works correctly.
Question 12
(a) Explain Merkle tree with the help of a neat diagram. Explain the use of Merkle tree in blockchain (7 marks)
Merkle Tree (also called Hash Tree) is a tree data structure where each leaf node contains the hash of a data block, and each non-leaf node contains the cryptographic hash of its child nodes, culminating in a single root hash.
Structure of Merkle Tree:
graph TD
A[Merkle Root<br/>Hash ABCD] --> B[Hash AB]
A --> C[Hash CD]
B --> D[Hash A<br/>Leaf]
B --> E[Hash B<br/>Leaf]
C --> F[Hash C<br/>Leaf]
C --> G[Hash D<br/>Leaf]
D --> H[Transaction A]
E --> I[Transaction B]
F --> J[Transaction C]
G --> K[Transaction D]
style A fill:#90EE90
style B fill:#FFD700
style C fill:#FFD700
style D fill:#87CEEB
style E fill:#87CEEB
style F fill:#87CEEB
style G fill:#87CEEB
Construction Process:
Step 1: Hash Leaf Nodes
Hash A = SHA-256(Transaction A)
Hash B = SHA-256(Transaction B)
Hash C = SHA-256(Transaction C)
Hash D = SHA-256(Transaction D)
Step 2: Hash Pairs to Create Parent Nodes
Hash AB = SHA-256(Hash A + Hash B)
Hash CD = SHA-256(Hash C + Hash D)
Step 3: Continue Until Root
Merkle Root = SHA-256(Hash AB + Hash CD)
Properties:
- Binary Tree Structure: Each parent has exactly two children (if odd number, last hash is duplicated)
- Bottom-Up Construction: Built from leaf nodes (transactions) up to root
- Single Root Hash: One hash representing all data
- Tamper-Evident: Any change in leaf propagates up, changing root
Merkle Proof (Verification Path):
To verify Transaction B is in the tree, only need:
- Hash B (transaction hash)
- Hash A (sibling)
- Hash CD (parent's sibling)
Verification:
Compute Hash AB = SHA-256(Hash A + Hash B)
Compute Root = SHA-256(Hash AB + Hash CD)
Compare with stored Merkle Root
Use of Merkle Trees in Blockchain:
1. Efficient Transaction Summarization
- Block header stores only Merkle root (32 bytes)
- Represents potentially thousands of transactions
- Enables compact block headers
Example - Bitcoin Block:
Block Header (80 bytes):
- Version
- Previous Block Hash
- Merkle Root ← Summarizes all transactions
- Timestamp
- Difficulty Target
- Nonce
2. Simplified Payment Verification (SPV)
- Lightweight clients don't download entire blockchain
- Can verify transaction inclusion without full transaction data
- Only need block headers + Merkle proof
- Efficiency: Verify transaction with O(log n) hashes instead of n transactions
Example:
- Block with 1000 transactions = ~1 MB
- SPV proof = ~10 hashes = 320 bytes
- Space savings: 99.97%
3. Integrity Verification
- Any transaction modification changes Merkle root
- Quick detection of tampering
- No need to check every transaction
4. Efficient Synchronization
- Nodes can quickly verify downloaded blocks
- Compare Merkle roots to detect corrupt data
- Re-request only problematic blocks
5. Proof of Inclusion
- Prove a specific transaction is in a block
- Provide Merkle path (logarithmic size proof)
- Third parties can verify without full block data
Merkle Proof Example:
graph TD
A[Merkle Root] --> B[Hash AB]
A --> C[Hash CD - Provided]
B --> D[Hash A - Provided]
B --> E[Hash B - Verify This]
style E fill:#90EE90
style D fill:#FFD700
style C fill:#FFD700
style A fill:#87CEEB
To verify Transaction B:
- Provided: Hash A, Hash CD
- Compute: Hash B from Transaction B
- Compute: Hash AB = hash(Hash A + Hash B)
- Compute: Root = hash(Hash AB + Hash CD)
- Compare with block's Merkle root
Advantages in Blockchain:
| Benefit | Description |
|---|---|
| Space Efficiency | Store thousands of transactions in 32-byte root |
| Fast Verification | O(log n) complexity for inclusion proofs |
| Tamper Detection | Any change immediately detectable |
| Scalability | Enables light clients and SPV |
| Privacy | Can prove transaction without revealing others |
Real-World Usage:
- Bitcoin: Transaction verification in blocks
- Ethereum: State tree, transaction tree, receipt tree
- Git: Version control (similar concept)
- IPFS: Distributed file systems
(b) Explain SHA-256 algorithm with a neat diagram (7 marks)
SHA-256 (Secure Hash Algorithm 256-bit) is a cryptographic hash function that produces a 256-bit (32-byte) hash value from input data of any size. It is part of the SHA-2 family designed by the NSA.
Key Specifications:
- Input: Any size (0 to 2^64 - 1 bits)
- Output: Fixed 256-bit (64 hexadecimal characters)
- Block Size: 512 bits processed at a time
- Rounds: 64 rounds of processing per block
SHA-256 Algorithm Overview:
flowchart TD
A[Input Message] --> B[Padding]
B --> C[Append Length]
C --> D[Divide into 512-bit Blocks]
D --> E[Initialize Hash Values H0-H7]
E --> F[Process Each Block]
F --> G{More Blocks?}
G -->|Yes| F
G -->|No| H[Concatenate Final Hash Values]
H --> I[256-bit Hash Output]
Detailed Algorithm Steps:
Step 1: Message Padding
Add padding bits to make message length ≡ 448 (mod 512):
Original Message
↓
Append 1 bit
↓
Append 0 bits until length ≡ 448 (mod 512)
↓
Append 64-bit length of original message
↓
Result: Multiple of 512 bits
Example:
- Original: "abc" = 24 bits
- After padding: 512 bits
- "abc" + 1 + (423 zeros) + (64-bit length = 24)
Step 2: Initialize Hash Values
Eight 32-bit initial hash values (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 3: Process Each 512-bit Block
Compression Function (Main Processing):
flowchart LR
A[512-bit Block] --> B[Message Schedule<br/>Expand to 64 words]
B --> C[64 Rounds of<br/>Compression]
C --> D[Add to Hash Values]
D --> E[Updated Hash Values]
a) Message Schedule - Create 64 Words (W0 to W63):
For i = 0 to 15:
W[i] = 32-bit word from message block
For i = 16 to 63:
W[i] = σ1(W[i-2]) + W[i-7] + σ0(W[i-15]) + W[i-16]
Where:
σ0(x) = ROTR^7(x) ⊕ ROTR^18(x) ⊕ SHR^3(x)
σ1(x) = ROTR^17(x) ⊕ ROTR^19(x) ⊕ SHR^10(x)
b) Compression Function (64 Rounds):
Initialize working variables:
a = H0, b = H1, c = H2, d = H3
e = H4, f = H5, g = H6, h = H7
Compression Round Structure:
flowchart TD
A[a,b,c,d,e,f,g,h] --> B[Compute T1 and T2]
B --> C[Update Variables]
C --> D{Round < 64?}
D -->|Yes| B
D -->|No| E[Add to Hash Values]
For each round i = 0 to 63:
T1 = h + Σ1(e) + Ch(e,f,g) + K[i] + W[i]
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
Functions Used:
Ch(x,y,z) = (x AND y) ⊕ (NOT x AND z) [Choose function]
Maj(x,y,z) = (x AND y) ⊕ (x AND z) ⊕ (y AND z) [Majority function]
Σ0(x) = ROTR^2(x) ⊕ ROTR^13(x) ⊕ ROTR^22(x)
Σ1(x) = ROTR^6(x) ⊕ ROTR^11(x) ⊕ ROTR^25(x)
ROTR^n(x) = Rotate right by n bits
⊕ = XOR operation
Constants K[0..63]:
- 64 constant values (first 32 bits of fractional parts of cube roots of first 64 primes)
Step 4: Update Hash Values
After 64 rounds, add working variables to 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: Final Hash Output
Concatenate final hash values:
SHA-256 Hash = H0 || H1 || H2 || H3 || H4 || H5 || H6 || H7
Complete SHA-256 Processing Diagram:
Message → Padding → 512-bit Blocks
Block 1
↓
[H0-H7] → [Message Schedule] → [64 Rounds] → [Update H0-H7]
↓
Block 2
↓
[H0-H7] → [Message Schedule] → [64 Rounds] → [Update H0-H7]
↓
...
↓
Block n
↓
[H0-H7] → [Message Schedule] → [64 Rounds] → [Final H0-H7]
↓
256-bit Hash Output
Example:
Input: "abc"
Output (in hexadecimal):
ba7816bf 8f01cfea 414140de 5dae2223
b00361a3 96177a9c b410ff61 f20015ad
Security Properties:
- Pre-image Resistance: Given hash, cannot find message
- Collision Resistance: Cannot find two different messages with same hash
- Avalanche Effect: Single bit change produces completely different hash
Applications in Blockchain:
- Bitcoin mining (double SHA-256)
- Transaction ID generation
- Block header hashing
- Merkle tree construction
- Proof of Work calculations
Why SHA-256 for Bitcoin:
- Proven security (no practical collisions found)
- Fast computation
- Produces uniform hash distribution
- Widely studied and trusted
Module II - Fundamentals of Blockchain Technology — #### Question 13
Question 13
(a) Explain the layered blockchain architecture with the help of a diagram (7 marks)
Layered Blockchain Architecture organizes blockchain systems into distinct functional layers, each responsible for specific aspects of the system. This modular approach facilitates understanding, development, and maintenance of blockchain networks.
Blockchain Architecture Layers:
graph TB
A[Application Layer] --> B[Execution Layer]
B --> C[Semantic Layer]
C --> D[Propagation Layer]
D --> E[Consensus Layer]
E --> F[Data Layer]
style A fill:#FFB6C1
style B fill:#DDA0DD
style C fill:#87CEEB
style D fill:#98FB98
style E fill:#FFD700
style F fill:#FFA07A
Detailed Explanation of Each Layer:
1. Data Layer (Foundation)
Purpose: Stores and manages the blockchain data structure
Components:
- Blocks: Containers for transaction data
- Block Header (metadata)
- Block Body (transactions)
- Chain Structure: Blocks linked via cryptographic hashes
- Merkle Trees: Efficient transaction summarization
- Digital Signatures: Transaction authentication
- Timestamps: Temporal ordering
Functions:
- Data storage and retrieval
- Cryptographic linking of blocks
- Transaction verification
- Historical data preservation
Example Structure:
Block:
Header:
- Previous Block Hash
- Merkle Root
- Timestamp
- Nonce
- Difficulty
Body:
- Transaction List
2. Consensus Layer
Purpose: Ensures all nodes agree on the blockchain state
Components:
- Consensus Algorithms:
- Proof of Work (PoW)
- Proof of Stake (PoS)
- Practical Byzantine Fault Tolerance (PBFT)
- Raft, Paxos
- Validation Rules: Define valid blocks and transactions
- Incentive Mechanisms: Rewards for participation
Functions:
- Achieve distributed consensus
- Prevent double-spending
- Maintain blockchain integrity
- Handle Byzantine faults
Key Mechanisms:
- Block proposal
- Block validation
- Conflict resolution
- Fork management
3. Propagation Layer (Network Layer)
Purpose: Facilitates communication between nodes
Components:
- Peer-to-Peer (P2P) Network: Decentralized node connectivity
- Gossip Protocol: Information dissemination
- Network Topology: Node connection structure
- Discovery Mechanisms: Finding and connecting to peers
Functions:
- Transaction broadcasting
- Block propagation
- Node discovery and management
- Network synchronization
- Bandwidth optimization
Communication Flow:
- Node creates transaction
- Broadcasts to connected peers
- Peers validate and re-broadcast
- Transaction reaches entire network
4. Semantic Layer
Purpose: Defines rules and logic for blockchain operations
Components:
- Smart Contracts: Self-executing code
- Business Logic: Application-specific rules
- Transaction Types: Different operation categories
- State Machine: Defines state transitions
Functions:
- Interpret and execute smart contracts
- Enforce business rules
- Manage state transitions
- Validate transaction semantics
Examples:
- Token transfer logic
- Voting mechanisms
- Supply chain tracking rules
- Financial contract terms
5. Execution Layer
Purpose: Executes transactions and smart contracts
Components:
- Virtual Machine: Isolated execution environment (e.g., EVM)
- Transaction Processor: Executes transactions
- State Manager: Tracks current system state
- Gas Mechanism: Resource allocation and metering
Functions:
- Execute smart contract code
- Process transactions
- Update blockchain state
- Manage computational resources
Example - Ethereum:
- Ethereum Virtual Machine (EVM) executes Solidity smart contracts
- Gas system prevents infinite loops
- State updated with each transaction
6. Application Layer (Top)
Purpose: User-facing interfaces and applications
Components:
- Decentralized Applications (DApps): Frontend applications
- Wallets: User interfaces for transactions
- APIs: Integration interfaces
- User Interfaces: Web/mobile applications
Functions:
- Provide user interaction
- Display blockchain data
- Submit transactions
- Manage keys and accounts
Examples:
- Cryptocurrency wallets (MetaMask)
- DeFi platforms (Uniswap)
- NFT marketplaces (OpenSea)
- Blockchain explorers (Etherscan)
Complete Layered Architecture Diagram:
graph TD
subgraph "Application Layer"
A1[DApps] --- A2[Wallets] --- A3[Web Interfaces]
end
subgraph "Execution Layer"
B1[Virtual Machine] --- B2[Transaction Processor]
end
subgraph "Semantic Layer"
C1[Smart Contracts] --- C2[Business Logic]
end
subgraph "Propagation Layer"
D1[P2P Network] --- D2[Gossip Protocol]
end
subgraph "Consensus Layer"
E1[PoW/PoS] --- E2[Validation Rules]
end
subgraph "Data Layer"
F1[Blocks] --- F2[Merkle Trees] --- F3[Signatures]
end
A1 --> B1
B1 --> C1
C1 --> D1
D1 --> E1
E1 --> F1
Interaction Between Layers:
| Layer | Receives From | Sends To | Example |
|---|---|---|---|
| Application | User input | Execution Layer | User submits transfer transaction |
| Execution | Application | Semantic Layer | Process transaction logic |
| Semantic | Execution | Propagation | Validate transaction rules |
| Propagation | Semantic | Consensus | Broadcast to network |
| Consensus | Propagation | Data | Include in block after validation |
| Data | Consensus | All layers (read) | Store in blockchain |
Benefits of Layered Architecture:
- Modularity: Each layer can be developed/modified independently
- Scalability: Layer-specific optimizations possible
- Security: Separation of concerns reduces attack surface
- Maintainability: Easier debugging and updates
- Interoperability: Standard interfaces between layers
(b) Illustrate and explain how blockchain works using a neat diagram (7 marks)
Blockchain is a distributed ledger technology where transactions are recorded in cryptographically linked blocks, forming an immutable chain maintained by a decentralized network.
How Blockchain Works - Step-by-Step Process:
sequenceDiagram
participant User
participant Network
participant Miners/Validators
participant Blockchain
User->>Network: 1. Initiate Transaction
Network->>Network: 2. Broadcast to Nodes
Network->>Miners/Validators: 3. Transaction Pool
Miners/Validators->>Miners/Validators: 4. Validate Transaction
Miners/Validators->>Miners/Validators: 5. Create Block & Solve Puzzle
Miners/Validators->>Network: 6. Broadcast New Block
Network->>Network: 7. Validate Block
Network->>Blockchain: 8. Add Block to Chain
Blockchain->>User: 9. Transaction Confirmed
Detailed Step-by-Step Explanation:
Step 1: Transaction Initiation
- User creates a transaction (e.g., send 5 BTC to address X)
- Transaction signed with user's private key
- Contains: sender address, receiver address, amount, digital signature
Transaction = {
From: Alice's Address
To: Bob's Address
Amount: 5 BTC
Signature: [Digital Signature]
Timestamp
}
Step 2: Transaction Broadcasting
- Transaction broadcasted to P2P network
- Propagates to all connected nodes via gossip protocol
- Nodes receive and validate the transaction
Step 3: Transaction Pool (Mempool)
- Validated transactions enter mempool (memory pool)
- Miners/validators select transactions for inclusion in next block
- Usually prioritized by transaction fees
Step 4: Transaction Validation
- Nodes verify:
- Digital signature authenticity
- Sufficient balance (no double-spending)
- Correct format
- Valid inputs and outputs
Step 5: Block Creation and Mining (PoW) / Validation (PoS)
For Proof of Work (Bitcoin):
flowchart TD
A[Select Transactions<br/>from Mempool] --> B[Create Block Header]
B --> C[Set Initial Nonce = 0]
C --> D[Compute Hash = SHA-256<br/>Block Header + Nonce]
D --> E{Hash < Target?}
E -->|No| F[Increment Nonce]
F --> D
E -->|Yes| G[Block Mined!<br/>Broadcast Block]
Miner must find nonce such that:
SHA-256(Block Header + Nonce) < Target Difficulty
Block Structure:
Block N:
Header:
- Previous Block Hash: [Hash of Block N-1]
- Merkle Root: [Root of transaction tree]
- Timestamp: 2023-10-25 14:30:00
- Difficulty Target: 0x1d00ffff
- Nonce: 2,450,689,234 (found by miner)
Body:
- Transaction 1
- Transaction 2
- ...
- Transaction n
Step 6: Block Broadcasting
- Successful miner broadcasts new block to network
- Block propagates to all nodes
- Includes proof of work (valid nonce)
Step 7: Block Validation by Network
- Each node independently validates the block:
- ✓ Proof of work is correct
- ✓ All transactions are valid
- ✓ Previous block hash matches
- ✓ Merkle root is correct
- ✓ Block size within limits
- ✓ Timestamp is reasonable
Step 8: Block Addition to Blockchain
- If valid, nodes add block to their local blockchain copy
- Block becomes part of the permanent ledger
- Blockchain grows by one block
Blockchain Structure:
graph LR
A[Genesis Block<br/>Block 0<br/>Hash: 000000] --> B[Block 1<br/>Prev: 000000<br/>Hash: 00ABC1]
B --> C[Block 2<br/>Prev: 00ABC1<br/>Hash: 00DEF2]
C --> D[Block 3<br/>Prev: 00DEF2<br/>Hash: 00GHI3]
D --> E[Block 4<br/>Prev: 00GHI3<br/>Hash: 00JKL4]
style A fill:#90EE90
style E fill:#FFD700
Step 9: Transaction Confirmation
- Transaction is now confirmed
- More blocks added = more confirmations = more security
- Bitcoin typically requires 6 confirmations for large amounts
Confirmation Depth:
Block N-5: Transaction included (1 confirmation)
Block N-4: (2 confirmations)
Block N-3: (3 confirmations)
Block N-2: (4 confirmations)
Block N-1: (5 confirmations)
Block N: (6 confirmations) ← Highly secure
Key Mechanisms Ensuring Blockchain Security:
1. Cryptographic Hashing
- Each block contains hash of previous block
- Any change in historical block invalidates entire subsequent chain
- Tamper-evident property
2. Distributed Consensus
- Majority of network must agree on blockchain state
- No single point of control or failure
- 51% attack threshold
3. Immutability
- Modifying old blocks requires:
- Recalculating proof of work for that block
- Recalculating all subsequent blocks
- Overtaking the current blockchain length
- Computationally infeasible
4. Transparency
- All transactions are visible
- Anyone can verify blockchain integrity
- Public audit trail
Complete Blockchain Workflow Diagram:
flowchart TD
A[User Creates<br/>Transaction] --> B[Digital Signature<br/>Applied]
B --> C[Broadcast to<br/>P2P Network]
C --> D[Validation by<br/>Network Nodes]
D --> E{Valid?}
E -->|No| F[Reject Transaction]
E -->|Yes| G[Add to<br/>Mempool]
G --> H[Miner Selects<br/>Transactions]
H --> I[Create Block<br/>Header]
I --> J[Mining:<br/>Find Valid Nonce]
J --> K[Block Found!]
K --> L[Broadcast Block<br/>to Network]
L --> M[Network Validates<br/>Block]
M --> N{Valid?}
N -->|No| O[Reject Block]
N -->|Yes| P[Add Block to<br/>Blockchain]
P --> Q[Transaction<br/>Confirmed]
Q --> R[More Blocks Added<br/>= More Confirmations]
Example - Bitcoin Transaction Flow:
- Alice wants to send 5 BTC to Bob
- Alice creates transaction, signs with private key
- Transaction broadcasted: "Alice → Bob: 5 BTC"
- Nodes verify Alice has sufficient balance
- Transaction added to mempool
- Miner includes transaction in new block
- Miner solves PoW puzzle (finds nonce)
- New block broadcasted to network
- Nodes validate and accept block
- Transaction confirmed (included in blockchain)
- After 6 blocks: Transaction highly secure
Security Through Confirmations:
| Confirmations | Security Level | Use Case |
|---|---|---|
| 0 (Mempool) | Unconfirmed | Pending |
| 1 | Low | Small transactions |
| 3 | Medium | Regular transactions |
| 6 | High | Large transactions |
| 100+ | Very High | Exchange deposits |
Question 14
(a) Explain the benefits, features and limitations of blockchain (7 marks)
Benefits of Blockchain:
1. Decentralization
- No central authority: Eliminates single point of failure and control
- Distributed power: Decision-making spread across network
- Censorship resistance: No single entity can block transactions
- Example: Bitcoin operates without central bank
2. Transparency
- Public ledger: All transactions visible to network participants
- Auditability: Complete transaction history available
- Trust through verification: Anyone can verify blockchain integrity
- Example: Etherscan allows viewing all Ethereum transactions
3. Immutability
- Tamper-proof records: Historical data cannot be altered
- Audit trail: Permanent record of all changes
- Fraud prevention: Modifications immediately detectable
- Example: Supply chain tracking ensures product authenticity
4. Security
- Cryptographic protection: Hashing and digital signatures secure data
- Distributed consensus: Majority agreement required for changes
- Byzantine fault tolerance: Operates despite malicious nodes
- Example: 51% attack threshold provides security
5. Cost Reduction
- Eliminates intermediaries: Direct peer-to-peer transactions
- Reduced transaction fees: No bank or payment processor fees
- Automated processes: Smart contracts reduce manual overhead
- Example: International remittances without Western Union fees
6. Speed and Efficiency
- 24/7 operations: No banking hours restrictions
- Faster settlements: Near real-time vs days for traditional systems
- Automated execution: Smart contracts execute instantly when conditions met
- Example: Cross-border payments in minutes instead of days
7. Traceability
- Complete history: Track asset from origin to current state
- Provenance verification: Authenticate product origins
- Supply chain visibility: End-to-end tracking
- Example: Diamond certification tracking from mine to consumer
Features of Blockchain:
1. Distributed Ledger
- Replicated across all network nodes
- No single storage location
- Synchronized through consensus
2. Peer-to-Peer Network
- Direct node-to-node communication
- No central servers
- Gossip protocol for information dissemination
3. Cryptographic Security
- SHA-256 hashing for data integrity
- Public-key cryptography for authentication
- Digital signatures for non-repudiation
4. Consensus Mechanisms
- Agreement protocols (PoW, PoS, PBFT)
- Byzantine fault tolerance
- Majority-based validation
5. Smart Contracts
- Self-executing code on blockchain
- Automated enforcement of agreements
- Programmable business logic
6. Tokenization
- Digital representation of assets
- Cryptocurrency creation
- Asset fractional ownership
7. Append-Only Structure
- New blocks added sequentially
- Historical blocks never modified
- Chain grows continuously
8. Block Chaining
- Each block linked to previous via hash
- Chronological ordering
- Tamper-evident structure
Limitations of Blockchain:
1. Scalability Issues
- Limited throughput:
- Bitcoin: ~7 transactions/second
- Ethereum: ~15-30 transactions/second
- Visa: ~24,000 transactions/second
- Blockchain bloat: Storage requirements grow continuously
- Network congestion: High demand causes delays and high fees
- Challenge: Balancing decentralization with transaction speed
2. High Energy Consumption
- Proof of Work: Bitcoin mining consumes ~150 TWh/year (comparable to Argentina)
- Environmental concerns: Carbon footprint of mining operations
- Hardware requirements: Specialized ASIC miners
- Mitigation: Shift to Proof of Stake (Ethereum 2.0)
3. Irreversibility
- No chargeback: Transactions cannot be reversed
- Lost keys = lost funds: No recovery mechanism
- Error permanence: Mistakes cannot be undone
- Example: Sending funds to wrong address is permanent loss
4. Storage Limitations
- Growing blockchain size: Bitcoin blockchain >400 GB
- Full node requirements: Substantial storage needed
- Synchronization time: New nodes take days to sync
- Solution: Light clients, pruning
5. Speed and Latency
- Block time: Bitcoin ~10 minutes, Ethereum ~13 seconds
- Confirmation delays: Multiple confirmations needed for security
- Not suitable for: Real-time applications requiring instant finality
- Comparison: Credit cards confirm instantly (with fraud risk)
6. Regulatory Uncertainty
- Legal status: Varies by country
- Compliance challenges: KYC/AML difficult in decentralized systems
- Tax implications: Unclear cryptocurrency taxation
- Government restrictions: Some countries ban cryptocurrencies
7. Complexity
- Technical barrier: Understanding cryptography, consensus, etc.
- User experience: Managing private keys challenging for average users
- Development difficulty: Smart contract programming requires expertise
- Risk: Code bugs can lead to irreversible losses (e.g., DAO hack)
8. Privacy Concerns
- Pseudonymity ≠ Anonymity: Addresses can be traced to identities
- Transaction transparency: All transactions publicly visible
- Data immutability: Cannot erase personal data (GDPR conflict)
- Solutions: Zero-knowledge proofs, privacy coins (Monero, Zcash)
9. 51% Attack Risk
- Majority control: Entity with >50% computational power can manipulate blockchain
- Cost: Expensive but possible for smaller blockchains
- Consequence: Double-spending, transaction censorship
- Defense: Large, distributed mining network
10. Integration Challenges
- Legacy system compatibility: Difficult to integrate with existing infrastructure
- Standardization: Lack of universal standards
- Interoperability: Different blockchains don't communicate easily
- Solution: Blockchain bridges, cross-chain protocols
Comparison Summary:
| Aspect | Blockchain | Traditional Systems |
|---|---|---|
| Control | Decentralized | Centralized |
| Transparency | High (public ledger) | Limited (controlled access) |
| Speed | Moderate (minutes) | Fast (seconds) |
| Scalability | Limited | High |
| Cost | Low (no intermediaries) | Variable (fees) |
| Immutability | High | Low (can be modified) |
| Energy | High (PoW) | Low |
| Reversibility | No | Yes (chargebacks) |
Use Case Suitability:
Blockchain is suitable for:
- Supply chain tracking
- Digital identity
- Cryptocurrency payments
- Smart contracts and DeFi
- Voting systems
Blockchain is not suitable for:
- High-frequency trading
- Real-time gaming
- Large file storage
- Applications requiring data deletion
(b) What is a consensus mechanism? Explain different types of consensus mechanisms (7 marks)
Consensus Mechanism is a protocol used in blockchain networks to achieve agreement among distributed nodes on the current state of the ledger, ensuring all participants have the same view of the blockchain despite the presence of faulty or malicious nodes.
Why Consensus is Needed:
- Distributed System: No central authority to validate transactions
- Byzantine Generals Problem: Some nodes may be malicious or faulty
- Double-Spending Prevention: Ensure same cryptocurrency unit not spent twice
- State Agreement: All nodes maintain identical blockchain copy
- Transaction Ordering: Determine chronological order of transactions
Properties of Good Consensus:
- Safety: All nodes agree on the same valid blockchain
- Liveness: System continues to make progress (adds new blocks)
- Fault Tolerance: Functions despite node failures
- Byzantine Tolerance: Handles malicious nodes
- Finality: Once confirmed, transactions cannot be reversed
Types of Consensus Mechanisms:
1. Proof of Work (PoW)
Concept: Miners compete to solve computationally intensive puzzle; first to solve gets to add block and receive reward.
How it Works:
- Miners hash block header with different nonce values
- Goal: Find hash below difficulty target
- Probability-based: More computational power = higher chance
- Difficulty adjusts to maintain constant block time
Mathematical Challenge:
Find nonce such that:
SHA-256(Block Header + nonce) < Target
Example Target: 0000000000000000000abc123...
Must find hash starting with many zeros
Characteristics:
- Energy-intensive: Requires massive computational power
- Secure: Expensive to attack (need 51% of network hashrate)
- Decentralized: Anyone can participate with computational resources
- Slow: Block time ~10 minutes (Bitcoin)
Used by: Bitcoin, Ethereum (before merge), Litecoin, Dogecoin
Advantages:
- High security
- Proven track record
- True decentralization
Disadvantages:
- High energy consumption
- Slow transaction finality
- Hardware centralization (ASIC miners)
2. Proof of Stake (PoS)
Concept: Validators are chosen to create blocks based on their stake (cryptocurrency holdings) rather than computational power.
How it Works:
- Participants "stake" their cryptocurrency as collateral
- Network selects validator based on stake size (and other factors)
- Selected validator proposes new block
- Other validators attest to block validity
- Rewards distributed to validators
Selection Criteria:
- Stake amount
- Randomization
- Coin age (in some implementations)
Characteristics:
- Energy-efficient: No intensive computation required
- Economic security: Malicious behavior results in stake loss (slashing)
- Faster: Block times in seconds
- Lower barriers: No expensive mining hardware needed
Slashing Mechanism:
- Validators lose staked cryptocurrency for:
- Proposing invalid blocks
- Being offline
- Double-signing
- Incentivizes honest behavior
Used by: Ethereum 2.0, Cardano, Polkadot, Algorand
Types of PoS:
a) Basic PoS: Selection based purely on stake
b) Delegated PoS (DPoS): Token holders vote for validators
c) Liquid PoS: Flexible staking with delegation
Advantages:
- Energy-efficient (~99.95% less than PoW)
- Faster finality
- Lower entry barriers
Disadvantages:
- "Rich get richer" (more stake = more rewards)
- Nothing-at-stake problem (validators can vote on multiple forks)
- Less tested than PoW
3. Delegated Proof of Stake (DPoS)
Concept: Token holders vote to elect delegates/witnesses who validate transactions and create blocks.
How it Works:
- Token holders vote for delegates (limited number, e.g., 21-101)
- Elected delegates take turns producing blocks
- Round-robin or scheduled order
- Delegates can be voted out if performance poor
Characteristics:
- Highly scalable: Few validators = faster consensus
- Democratic: Token holders have governance power
- Accountable: Poor-performing delegates replaced
- Fast: Block times in seconds
Used by: EOS, TRON, Steem, Lisk
Advantages:
- High throughput (thousands of TPS)
- Fast finality
- Democratic governance
Disadvantages:
- More centralized (fewer validators)
- Potential for vote buying
- Cartel formation risk
4. Practical Byzantine Fault Tolerance (PBFT)
Concept: Consensus algorithm for permissioned networks that tolerates Byzantine (malicious) nodes through multiple rounds of voting.
How it Works:
sequenceDiagram
participant Client
participant Primary
participant Replica1
participant Replica2
participant Replica3
Client->>Primary: Request
Primary->>Replica1: Pre-Prepare
Primary->>Replica2: Pre-Prepare
Primary->>Replica3: Pre-Prepare
Replica1->>Replica2: Prepare
Replica1->>Replica3: Prepare
Replica2->>Replica1: Prepare
Replica2->>Replica3: Prepare
Replica3->>Replica1: Prepare
Replica3->>Replica2: Prepare
Replica1->>Replica2: Commit
Replica1->>Replica3: Commit
Replica2->>Replica1: Commit
Replica2->>Replica3: Commit
Replica3->>Replica1: Commit
Replica3->>Replica2: Commit
Replica1->>Client: Reply
Phases:
- Request: Client sends request to primary
- Pre-Prepare: Primary broadcasts request to replicas
- Prepare: Replicas exchange prepare messages
- Commit: After 2f+1 prepare messages, replicas commit
- Reply: After 2f+1 commits, execute and reply
Requirements:
- Minimum n = 3f + 1 nodes to tolerate f Byzantine failures
- Example: 10 nodes can tolerate 3 Byzantine nodes
Characteristics:
- No mining: Deterministic consensus
- Fast finality: Immediate once committed
- Communication-intensive: O(n²) messages
Used by: Hyperledger Fabric, Zilliqa, NEO
Advantages:
- Immediate finality
- Energy-efficient
- High throughput in permissioned networks
Disadvantages:
- Requires known participants
- Poor scalability (message overhead)
- Not suitable for public blockchains
5. Proof of Authority (PoA)
Concept: Pre-approved validators (authorities) take turns validating transactions and creating blocks based on reputation.
How it Works:
- Network admins select trusted validators
- Validators' identities are known and at stake
- Validators take turns proposing blocks
- Reputation-based trust model
Characteristics:
- Permissioned: Validators must be approved
- Fast: High throughput, low latency
- Energy-efficient: No mining
- Centralized: Trust in selected authorities
Used by: VeChain, POA Network, some private Ethereum chains
Advantages:
- High performance
- Predictable block times
- Low computational requirements
Disadvantages:
- Centralized (trust in authorities)
- Not suitable for public, permissionless networks
- Vulnerable if authorities collude
6. Proof of Elapsed Time (PoET)
Concept: Uses trusted execution environments (Intel SGX) to randomly select leader based on lottery-style wait times.
How it Works:
- Each node requests wait time from trusted hardware
- Wait time randomly assigned
- Node with shortest wait time wins the right to create block
- Fair because wait times generated by trusted hardware
Used by: Hyperledger Sawtooth
7. Crash Fault Tolerance Algorithms
Paxos:
- Consensus for non-Byzantine (crash) faults
- Multi-phase voting protocol
- Theoretical foundation for many consensus algorithms
Raft:
- Simpler alternative to Paxos
- Leader-based consensus
- Leader election, log replication, safety
- Used in distributed databases
Comparison of Consensus Mechanisms:
| Mechanism | Energy | Speed | Decentralization | Security | Scalability |
|---|---|---|---|---|---|
| PoW | Very High | Slow | High | Very High | Low |
| PoS | Low | Medium | Medium | High | Medium |
| DPoS | Low | Fast | Low | Medium | High |
| PBFT | Low | Fast | Low | High | Low |
| PoA | Low | Fast | Very Low | Medium | Medium |
Selection Criteria:
- Public permissionless: PoW, PoS
- Consortium blockchain: PBFT, PoA
- High throughput needed: DPoS, PoA
- Energy efficiency priority: PoS, PBFT, PoA
- Maximum security: PoW (for large networks)
- Fast finality: PBFT, PoS with finality gadgets
Module III - Consensus Algorithms and Bitcoin — #### Question 15
Question 15
(a) What are the different tasks of a Bitcoin miner? Explain the mining algorithm used in Bitcoin with the help of a flowchart (7 marks)
Bitcoin Miner is a network participant who validates transactions, creates new blocks, and secures the blockchain through Proof of Work consensus.
Tasks of a Bitcoin Miner:
1. Transaction Collection and Validation
- Monitor network for new transactions
- Collect transactions from mempool
- Validate each transaction:
- Verify digital signatures
- Check sufficient balance (UTXO validation)
- Ensure no double-spending
- Validate transaction format
- Select valid transactions for inclusion in block
- Prioritize by transaction fees (higher fees = higher priority)
2. Block Creation
- Assemble selected transactions into a block
- Create block header with:
- Version number
- Previous block hash
- Merkle root of transactions
- Timestamp
- Difficulty target (nBits)
- Nonce (initially 0)
- Calculate Merkle tree root from transactions
- Ensure block size within limits (current: ~4 MB with SegWit)
3. Proof of Work Mining
- Search for valid nonce that satisfies difficulty target
- Repeatedly hash block header with different nonce values
- Goal: Find hash below target difficulty
- Computational brute-force process
- Adjust nonce, re-hash, check result
4. Block Broadcasting
- Once valid nonce found, broadcast block to network
- Propagate to all connected peers
- Include proof of work (valid nonce)
5. Blockchain Maintenance
- Store complete blockchain copy
- Validate blocks from other miners
- Resolve forks (follow longest chain)
- Update local blockchain with accepted blocks
6. Network Security
- Prevent double-spending attacks
- Make blockchain immutable through computational work
- Increase cost of 51% attacks
- Contribute to network decentralization
7. New Bitcoin Issuance
- Create coinbase transaction (first transaction in block)
- Claim block reward (currently 6.25 BTC per block)
- Collect transaction fees from included transactions
- Economic incentive for mining
Bitcoin Mining Algorithm:
flowchart TD
A[Start] --> B[Collect Transactions<br/>from Mempool]
B --> C[Validate Transactions]
C --> D[Select Transactions<br/>Based on Fees]
D --> E[Create Merkle Tree<br/>Calculate Root Hash]
E --> F[Create Block Header<br/>Set Nonce = 0]
F --> G[Compute Hash<br/>SHA-256 SHA-256 Block Header]
G --> H{Hash < Target<br/>Difficulty?}
H -->|No| I[Increment Nonce]
I --> J{Nonce Max<br/>Reached?}
J -->|No| G
J -->|Yes| K[Update Timestamp<br/>or Extra Nonce]
K --> G
H -->|Yes| L[Valid Block Found!]
L --> M[Broadcast Block<br/>to Network]
M --> N[Collect Block Reward<br/>+ Transaction Fees]
N --> O[Wait for Network<br/>Confirmation]
O --> P{Block Accepted?}
P -->|Yes| Q[Add to Blockchain<br/>Start Next Block]
P -->|No| R[Discard Block<br/>Fork Resolved]
R --> B
Q --> B
style L fill:#90EE90
style N fill:#FFD700
style R fill:#FF6B6B
Detailed Mining Algorithm Steps:
Step 1: Initialize
Collect valid transactions from mempool
Prioritize by fee: tx_fee / tx_size (satoshis per byte)
Step 2: Create Block Structure
Block:
Coinbase Transaction (reward to miner)
Transaction 1
Transaction 2
...
Transaction n
Calculate Merkle Root from all transactions
Step 3: Setup Block Header
Block Header (80 bytes):
Version (4 bytes): Protocol version
Previous Block Hash (32 bytes): Hash of block N-1
Merkle Root (32 bytes): Root of transaction tree
Timestamp (4 bytes): Current Unix timestamp
Bits (4 bytes): Difficulty target (compact format)
Nonce (4 bytes): Initially 0, to be found
Step 4: Mining Loop (Proof of Work)
nonce = 0
target = difficulty_bits_to_target(bits)
while True:
block_header = version + prev_hash + merkle_root + timestamp + bits + nonce
hash_result = SHA256(SHA256(block_header))
if hash_result < target:
# Valid block found!
broadcast_block()
break
nonce += 1
if nonce > 2^32: # Nonce overflow
# Update extra nonce in coinbase or timestamp
update_merkle_root()
nonce = 0
Step 5: Hash Calculation
Double SHA-256:
hash = SHA-256(SHA-256(Block Header))
Example:
Block Header: 0100000000000000000000...
First SHA-256: a1b2c3d4e5f6...
Second SHA-256: 0000000000000abc123... (must be < target)
Step 6: Difficulty Target
Target Example:
0000000000000000000abc1234567890...
Hash must have sufficient leading zeros
Difficulty adjusts every 2016 blocks (~2 weeks)
Goal: Maintain 10-minute average block time
Mining Performance Metrics:
Hash Rate:
- Measures computational power
- Units: H/s (hashes per second)
- KH/s = thousand
- MH/s = million
- GH/s = billion
- TH/s = trillion
- PH/s = quadrillion
- EH/s = quintillion
Bitcoin Network (2023): ~400 EH/s
Mining Economics:
Revenue = Block Reward + Transaction Fees
Cost = Electricity + Hardware + Cooling + Maintenance
Profitability = Revenue - Cost
Block Reward Schedule:
2009-2012: 50 BTC
2012-2016: 25 BTC
2016-2020: 12.5 BTC
2020-2024: 6.25 BTC
2024-2028: 3.125 BTC (next halving)
Difficulty Adjustment:
Every 2016 blocks:
New_Difficulty = Old_Difficulty × (Actual_Time / Expected_Time)
Expected_Time = 2016 blocks × 10 minutes = 20160 minutes
If actual < expected: Increase difficulty
If actual > expected: Decrease difficulty
(b) Describe the process of achieving consensus through the Paxos protocol, and provide an example to illustrate its implementation (7 marks)
Paxos Protocol is a consensus algorithm designed for distributed systems to achieve agreement among nodes despite failures. It solves the consensus problem in asynchronous networks with crash failures (not Byzantine faults).
Key Concepts:
Roles in Paxos:
- Proposer: Proposes values for consensus
- Acceptor: Votes on proposed values
- Learner: Learns the chosen value
(Note: A node can play multiple roles)
Properties Guaranteed:
- Safety: Only one value is chosen
- Liveness: Eventually a value is chosen (if majority available)
- Validity: Chosen value must be proposed
Paxos Protocol Phases:
Phase 1: Prepare Phase (Promise)
1a. Prepare Request (Proposer → Acceptors)
Proposer generates unique proposal number n
Sends PREPARE(n) to majority of acceptors
Proposal number must be higher than any previously seen
1b. Promise Response (Acceptors → Proposer)
Acceptor receives PREPARE(n):
If n > highest proposal number seen:
Promise to ignore proposals < n
Respond with PROMISE(n, value, accepted_number)
- value: previously accepted value (if any)
- accepted_number: proposal number of that value
Else:
Reject or ignore
Phase 2: Accept Phase (Consensus)
2a. Accept Request (Proposer → Acceptors)
Proposer receives promises from majority:
If any acceptor sent previously accepted value:
Use that value (highest accepted_number)
Else:
Use proposer's own value
Send ACCEPT(n, value) to acceptors
2b. Accepted Response (Acceptors → Learners)
Acceptor receives ACCEPT(n, value):
If n >= highest promised proposal number:
Accept the value
Send ACCEPTED(n, value) to all learners
Else:
Reject
Learning Phase:
Learner receives ACCEPTED messages:
Once majority of acceptors accept same (n, value):
Value is chosen/learned
Consensus achieved!
Paxos Protocol Diagram:
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: Phase 1: Prepare
P->>A1: PREPARE(n=1)
P->>A2: PREPARE(n=1)
P->>A3: PREPARE(n=1)
A1->>P: PROMISE(n=1, null, null)
A2->>P: PROMISE(n=1, null, null)
Note over P: Majority received
Note over P: Phase 2: Accept
P->>A1: ACCEPT(n=1, value=X)
P->>A2: ACCEPT(n=1, value=X)
P->>A3: ACCEPT(n=1, value=X)
A1->>L: ACCEPTED(n=1, value=X)
A2->>L: ACCEPTED(n=1, value=X)
A3->>L: ACCEPTED(n=1, value=X)
Note over L: Consensus: X is chosen
Example: Distributed Database Commit
Scenario: Three database servers (A, B, C) must agree on whether to commit or abort a transaction.
Initial State:
- Proposer: Server A (wants to commit)
- Acceptors: Servers A, B, C
- Value to decide: "COMMIT" or "ABORT"
Execution Trace:
Round 1: Proposer A attempts consensus
Step 1: Prepare Phase
T=1: Proposer A sends PREPARE(n=1) to A, B, C
T=2: Server A receives PREPARE(1)
- Highest seen: none
- Responds: PROMISE(1, null, null)
T=3: Server B receives PREPARE(1)
- Highest seen: none
- Responds: PROMISE(1, null, null)
T=4: Server C receives PREPARE(1)
- Highest seen: none
- Responds: PROMISE(1, null, null)
Result: Proposer A has majority promises (3/3)
Step 2: Accept Phase
T=5: Proposer A sends ACCEPT(1, "COMMIT") to A, B, C
(No previous values, so uses own value)
T=6: Server A receives ACCEPT(1, "COMMIT")
- 1 >= highest promised (1) ✓
- Accepts value "COMMIT"
- Responds: ACCEPTED(1, "COMMIT")
T=7: Server B receives ACCEPT(1, "COMMIT")
- 1 >= highest promised (1) ✓
- Accepts value "COMMIT"
- Responds: ACCEPTED(1, "COMMIT")
T=8: Server C receives ACCEPT(1, "COMMIT")
- 1 >= highest promised (1) ✓
- Accepts value "COMMIT"
- Responds: ACCEPTED(1, "COMMIT")
Result: All acceptors accepted (3/3) - Majority achieved!
Step 3: Learning
T=9: Learners receive ACCEPTED(1, "COMMIT") from A, B, C
- Majority (3/3) accepted same value
- Consensus achieved: "COMMIT"
- Transaction commits on all servers
Example with Conflict: Concurrent Proposers
Scenario: Two servers try to propose simultaneously
Server A: Proposes "COMMIT" with proposal n=1
Server C: Proposes "ABORT" with proposal n=2
Timeline:
T=1: Server A sends PREPARE(1) to all acceptors
T=2: Server C sends PREPARE(2) to all acceptors
T=3: Server B receives both:
- PREPARE(1): Promises with n=1
- PREPARE(2): Higher number! Overwrites promise
- Responds: PROMISE(2, null, null) to C
- Ignores A's subsequent ACCEPT(1, ...)
T=4: Server A receives promises from A, B (but B later changed)
T=5: Server C receives promises from B, C (majority)
T=6: Server A sends ACCEPT(1, "COMMIT")
- Server B rejects (promised n=2)
- Only A accepts
- No majority - A's proposal fails
T=7: Server C sends ACCEPT(2, "ABORT")
- Servers B, C accept
- Majority achieved!
- Consensus: "ABORT"
Handling Failures:
Case 1: Acceptor Failure
3 acceptors, 1 fails:
- Need majority = 2 acceptors
- If 2 remain responsive: Consensus possible
- If <2 remain: Cannot achieve consensus (liveness lost)
Case 2: Proposer Failure
Proposer crashes after Phase 1:
- Acceptors in promise state
- New proposer can take over
- Uses higher proposal number
- Learns any previously accepted values
- Continues consensus process
Paxos in Blockchain Context:
Use in Permissioned Blockchains:
- Consensus among known validators
- No mining required
- Fast finality (no probabilistic confirmation)
- Suitable for consortium blockchains
Example - Hyperledger Fabric:
- Uses Raft (similar to Paxos) for ordering service
- Crash fault tolerance
- Deterministic consensus
Advantages:
- Proven correctness
- Handles crash failures
- No energy waste
- Fast consensus
Limitations:
- Not Byzantine fault tolerant
- Requires majority of nodes operational
- Communication overhead
- Complex to implement correctly
Comparison with Blockchain Consensus:
| Aspect | Paxos | PoW (Bitcoin) | PBFT |
|---|---|---|---|
| Fault Model | Crash | Byzantine | Byzantine |
| Performance | Fast | Slow | Fast |
| Energy | Low | Very High | Low |
| Network Type | Permissioned | Permissionless | Permissioned |
| Finality | Immediate | Probabilistic | Immediate |
Question 16
(a) Let us assume, for consensus in Bitcoin, instead of PoW, a random node is selected as the winner who can propose the next block in the blockchain. If the randomly chosen node is a malicious (Byzantine) node, then which of the following statement is true? Justify your answer (7 marks)
Given Statements:
- The malicious node can steal Bitcoin from other addresses
- The malicious node can make a denial-of-service attack
- The malicious node can make a double spend attack
Analysis:
Statement 1: The malicious node can steal Bitcoin from other addresses
Answer: FALSE
Justification:
Why This is NOT Possible:
-
Cryptographic Security:
- Bitcoin uses public-key cryptography (ECDSA)
- Transactions must be signed with private key
- Malicious miner cannot forge signatures without private key
- Private key cannot be derived from public address (one-way function)
-
Transaction Validation:
- Every node independently validates all transactions
- Invalid transactions are rejected by network
- Even if malicious miner includes invalid transaction in block:
- Other nodes will reject the entire block
- Block won't be added to blockchain
- Miner gains nothing
-
Consensus Layer vs. Cryptographic Layer:
- Consensus (block proposal) is separate from transaction validity
- Cryptographic security protects individual transactions
- Breaking this requires breaking ECDSA (computationally infeasible)
Example:
Alice's Bitcoin address: 1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa
Alice's balance: 10 BTC
Malicious miner cannot:
- Create transaction: "Send 10 BTC from Alice to Attacker"
- Without Alice's private key, signature is invalid
- Network rejects transaction
- Block containing it is rejected
What Malicious Miner CAN do:
- Exclude Alice's legitimate transactions (censorship)
- Reorder transactions
- Include their own valid transactions
What Malicious Miner CANNOT do:
- Spend Alice's bitcoins
- Forge Alice's signature
- Create bitcoins beyond block reward
Statement 2: The malicious node can make a denial-of-service attack
Answer: TRUE (Limited)
Justification:
Why This IS Possible:
-
Transaction Censorship:
- Malicious miner can exclude specific transactions from blocks
- Can target specific addresses/users
- Prevents those transactions from being confirmed
-
Single Block Impact:
- In random selection model (not PoW), malicious node selected for one block
- Can censor transactions for that block only
- Next block (likely honest miner) can include censored transactions
-
Network-Wide DoS:
- If repeatedly selected (random selection with replacement)
- Can cause persistent delays
- Affects liveness but not safety
Example Scenario:
Block N (Malicious Miner Selected):
- Mempool has 1000 transactions
- Includes transaction from Alice to Bob
- Malicious miner creates empty block or excludes Alice's transaction
- Alice's transaction remains unconfirmed
Block N+1 (Honest Miner Selected):
- Includes Alice's transaction
- Transaction finally confirmed
- Delay caused, but not permanent denial
Severity in Random Selection vs. PoW:
Random Selection (Proposed Scenario):
- If 10% of nodes are malicious
- 10% probability of malicious block
- Persistent DoS possible if malicious nodes frequently selected
PoW (Bitcoin Reality):
- Requires 51% of computational power for persistent censorship
- Extremely expensive
- Economic disincentive
Impact:
- Liveness affected: Transactions delayed
- Safety maintained: Cannot steal or create invalid transactions
- Temporary: Only affects blocks created by malicious miner
Statement 3: The malicious node can make a double spend attack
Answer: TRUE
Justification:
Why This IS Possible:
Double-Spending Attack Mechanism:
-
Transaction Creation:
- Malicious node (Eve) has 10 BTC
- Creates Transaction A: "Send 10 BTC to Merchant"
- Broadcasts to network
-
Merchant Acceptance:
- Merchant receives Transaction A
- Transaction included in Block N by honest miner
- Merchant ships goods
-
Malicious Block Proposal:
- Eve selected as next block proposer (Block N+1)
- Eve creates Transaction B: "Send same 10 BTC to Eve's other address"
- Eve builds Block N' (alternative to N) containing Transaction B instead of A
- Eve's block creates a fork
-
Fork Resolution:
- In PoW: Longest chain wins (requires computational work)
- In random selection: No objective way to choose
- If Eve's block accepted, Transaction A is invalidated
- Eve keeps goods AND bitcoins
Double-Spend Attack Diagram:
graph LR
A[Block N-1] --> B[Block N<br/>Contains: Alice→Merchant<br/>10 BTC]
B --> C[Block N+1<br/>Honest chain]
A --> D[Block N'<br/>Contains: Alice→Alice2<br/>Same 10 BTC]
D --> E[Block N'+1<br/>Malicious chain]
style D fill:#FF6B6B
style E fill:#FF6B6B
style B fill:#90EE90
style C fill:#90EE90
Why This Works in Random Selection:
-
No PoW Requirement:
- In PoW, rewriting history requires re-mining blocks (expensive)
- In random selection, proposing alternative block is costless
- No computational barrier
-
Fork Resolution Problem:
- Random selection provides no objective "heaviest chain" rule
- Cannot distinguish between competing chains
- Network may split
-
Nothing at Stake:
- Malicious miner can propose multiple conflicting blocks
- No cost to proposing invalid history
- Can attempt double-spend repeatedly
Attack Example:
Initial State:
Eve's balance: 10 BTC
Step 1: Eve→Merchant Transaction
Block 100: [..., Eve→Merchant: 10 BTC]
Merchant confirms, ships product
Step 2: Eve Selected for Block 101
Instead of building on Block 100, Eve creates:
Block 100': [..., Eve→Eve2: 10 BTC] (conflicting transaction)
Block 101': [on top of Block 100']
Step 3: Network Confusion
Some nodes follow: Block 100 → Block 101
Other nodes follow: Block 100' → Block 101'
Fork persists (no PoW to resolve)
Result:
- Merchant shipped goods (thinks paid)
- Eve has bitcoins in Eve2 address
- Double-spend successful!
Why PoW Prevents This:
-
Computational Cost:
- Rewriting block requires re-mining
- Needs >50% hashrate for sustained attack
- Economically infeasible
-
Longest Chain Rule:
- Objective measure: accumulated PoW
- Honest majority will build longer chain
- Orphans alternative blocks
-
Time Factor:
- Confirmations increase security
- 6 confirmations = very secure
- Attacker must rewrite 6+ blocks (nearly impossible)
Summary Table:
| Attack Type | Possible? | Severity | Reason |
|---|---|---|---|
| Steal from other addresses | ✗ NO | N/A | Cryptographic protection (ECDSA signatures) |
| Denial of Service | ✓ YES | Medium | Can censor transactions temporarily |
| Double Spend | ✓ YES | HIGH | No computational cost to fork, nothing at stake |
Correct Answer: Statement 3 is TRUE (most critical)
Key Insight:
Random node selection for consensus is fundamentally flawed because:
- No cost to propose alternative history
- No objective fork resolution
- Enables costless double-spending
- This is why Bitcoin uses PoW instead
Real-World Requirement:
Secure blockchain consensus must have:
- Sybil resistance: Cost to gain consensus power (PoW, PoS)
- Fork resolution: Objective rule to choose canonical chain
- Economic incentives: Honest behavior more profitable than attacks
Random selection fails all three criteria.
(b) With a neat diagram explain the structure of a transaction in Bitcoin. Explain Unspent Transaction Output (UTXO) and its use in transaction verification (7 marks)
Bitcoin Transaction Structure:
A Bitcoin transaction is a data structure that transfers value from transaction inputs to transaction outputs.
Complete Transaction Structure Diagram:
graph TD
A[Bitcoin Transaction] --> B[Transaction Metadata]
A --> C[Inputs]
A --> D[Outputs]
B --> B1[Version]
B --> B2[Transaction ID TXID]
B --> B3[Locktime]
B --> B4[Size]
C --> C1[Input 1]
C --> C2[Input 2]
C --> C3[Input n]
C1 --> C1A[Previous TXID]
C1 --> C1B[Output Index]
C1 --> C1C[ScriptSig Signature]
C1 --> C1D[Sequence]
D --> D1[Output 1]
D --> D2[Output 2]
D --> D3[Output m]
D1 --> D1A[Value in satoshis]
D1 --> D1B[ScriptPubKey Address]
style A fill:#FFD700
style B fill:#87CEEB
style C fill:#90EE90
style D fill:#FFA07A
Detailed Transaction Components:
1. Transaction Metadata
Version: 4 bytes
- Protocol version number
- Currently version 1 or 2 (SegWit)
Transaction ID (TXID): 32 bytes
- Double SHA-256 hash of transaction
- Unique identifier
- Example: a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d
Locktime: 4 bytes
- Earliest time/block when transaction can be added
- 0 = immediate
- >0 = Unix timestamp or block height
Size: Variable
- Transaction size in bytes
- Affects transaction fees
2. Inputs (Spending Previous Outputs)
Each input references a previous unspent output:
Input Structure:
{
Previous Transaction Hash (TXID): 32 bytes
- References output being spent
Output Index (vout): 4 bytes
- Which output of that transaction (0-indexed)
ScriptSig (Unlocking Script): Variable
- Digital signature proving ownership
- Public key
- Unlocks the referenced output
Sequence: 4 bytes
- Used for transaction replacement
- 0xFFFFFFFF = final
}
Example Input:
{
"txid": "0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098",
"vout": 0,
"scriptSig": {
"asm": "304402... [signature] 03bc89... [pubkey]",
"hex": "47304402..."
},
"sequence": 4294967295
}
3. Outputs (Creating New UTXOs)
Each output specifies amount and recipient:
Output Structure:
{
Value: 8 bytes
- Amount in satoshis (1 BTC = 100,000,000 satoshis)
ScriptPubKey (Locking Script): Variable
- Specifies conditions to spend
- Usually contains recipient's address
- "Puzzle" that must be solved to spend
}
Example Output:
{
"value": 0.05000000, // 5,000,000 satoshis
"n": 0, // Output index
"scriptPubKey": {
"asm": "OP_DUP OP_HASH160 ab68025513c3dbd2f7b92a94e0581f5d50f654e7 OP_EQUALVERIFY OP_CHECKSIG",
"hex": "76a914ab68025513c3dbd2f7b92a94e0581f5d50f654e788ac",
"type": "pubkeyhash",
"address": "1GdK9UzpHBzqzX2A9JFP3Di4weBwqgmoQA"
}
}
Complete Transaction Example:
Transaction: Alice sends 0.5 BTC to Bob
{
"txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
"version": 2,
"size": 225,
"locktime": 0,
"inputs": [
{
"txid": "prev_tx_id_1",
"vout": 0,
"scriptSig": "[Alice's signature + pubkey]",
"value_spent": 0.6 BTC
}
],
"outputs": [
{
"value": 0.5 BTC, // To Bob
"scriptPubKey": "[Bob's address]"
},
{
"value": 0.0999 BTC, // Change back to Alice
"scriptPubKey": "[Alice's change address]"
}
// 0.0001 BTC implicit transaction fee (0.6 - 0.5 - 0.0999)
]
}
Transaction Flow Diagram:
graph LR
A[Alice's UTXO<br/>0.6 BTC] -->|Input| B[Transaction]
B -->|Output 0| C[Bob's UTXO<br/>0.5 BTC]
B -->|Output 1| D[Alice's Change<br/>0.0999 BTC]
B -.->|Fee| E[Miner<br/>0.0001 BTC]
style A fill:#FFD700
style C fill:#90EE90
style D fill:#87CEEB
style E fill:#FFA07A
Unspent Transaction Output (UTXO):
UTXO Definition:
An Unspent Transaction Output is an output of a blockchain transaction that has not been spent (used as input in another transaction). UTXOs represent the spendable balance in the Bitcoin network.
Key Concepts:
1. No Account Balances in Bitcoin:
- Bitcoin doesn't store account balances
- Only tracks UTXOs
- Your "balance" = sum of all UTXOs you can spend
2. UTXO as Discrete Chunks:
- UTXOs are indivisible in transactions
- Must spend entire UTXO
- Receive change as new UTXO if needed
3. UTXO Set:
- Collection of all unspent outputs in blockchain
- Maintained by full nodes
- Used for fast transaction validation
UTXO Model Example:
Alice's Wallet:
UTXO 1: 0.5 BTC (from transaction tx1, output 0)
UTXO 2: 0.3 BTC (from transaction tx2, output 1)
UTXO 3: 0.2 BTC (from transaction tx3, output 0)
Total Balance: 1.0 BTC (sum of UTXOs)
Transaction Example with UTXOs:
Scenario: Alice wants to send 0.7 BTC to Bob
Alice's UTXOs:
- UTXO A: 0.5 BTC
- UTXO B: 0.3 BTC
- UTXO C: 0.2 BTC
Transaction:
Inputs:
- UTXO A (0.5 BTC) ✓ Spent
- UTXO B (0.3 BTC) ✓ Spent
Total Input: 0.8 BTC
Outputs:
- Output 0: 0.7 BTC → Bob's address (new UTXO for Bob)
- Output 1: 0.099 BTC → Alice's change address (new UTXO for Alice)
- Fee: 0.001 BTC (0.8 - 0.7 - 0.099)
After Transaction:
Alice's UTXOs:
- UTXO C: 0.2 BTC (unchanged)
- New UTXO: 0.099 BTC (change)
Total: 0.299 BTC
Bob's UTXOs:
- New UTXO: 0.7 BTC
UTXO Lifecycle:
flowchart LR
A[Transaction Creates<br/>Output] --> B[UTXO<br/>Unspent]
B --> C[Used as Input<br/>in New Transaction]
C --> D[No Longer UTXO<br/>Spent]
D --> E[New UTXOs Created]
E --> B
style B fill:#90EE90
style D fill:#FF6B6B
UTXO in Transaction Verification:
Verification Process:
Step 1: Check UTXO Existence
For each input in transaction:
1. Look up referenced UTXO in UTXO set
2. Verify UTXO exists and is unspent
3. If UTXO already spent or doesn't exist → Invalid transaction
Step 2: Verify Ownership
For each input:
1. Execute ScriptSig (unlocking script from input)
2. Execute ScriptPubKey (locking script from referenced UTXO)
3. Scripts must execute successfully
4. Verifies cryptographic signature
5. Proves sender owns the UTXO
Step 3: Verify Amounts
Sum of input UTXOs ≥ Sum of output values + transaction fee
Example:
Inputs: 0.5 + 0.3 = 0.8 BTC
Outputs: 0.7 + 0.099 = 0.799 BTC
Fee: 0.8 - 0.799 = 0.001 BTC ✓ Valid
Step 4: Prevent Double-Spending
Check UTXO has not been spent in:
1. This block
2. Previous blocks
3. Other transactions in mempool (if applicable)
If UTXO already spent → Double-spend attempt → Reject
Step 5: Update UTXO Set
After transaction confirmed:
1. Remove spent UTXOs from UTXO set
2. Add new UTXOs from transaction outputs
3. UTXO set remains consistent
UTXO Verification Example:
Transaction Verification:
Input Claims:
- Spend UTXO from TX abc123, output 0 (0.5 BTC)
- Spend UTXO from TX def456, output 1 (0.3 BTC)
Verification Steps:
1. ✓ UTXO abc123:0 exists in UTXO set (0.5 BTC)
2. ✓ UTXO def456:1 exists in UTXO set (0.3 BTC)
3. ✓ Signatures valid (proves ownership)
4. ✓ Amounts: 0.8 BTC in ≥ 0.799 BTC out
5. ✓ Neither UTXO previously spent
Transaction Valid! ✓
Update UTXO Set:
- Remove: abc123:0, def456:1
- Add: new_tx:0 (0.7 BTC to Bob)
- Add: new_tx:1 (0.099 BTC to Alice)
Advantages of UTXO Model:
-
Parallel Validation:
- Different transactions with different UTXOs can be validated independently
- No sequential account balance updates
-
No Account State:
- Stateless verification
- Only need UTXO set, not full account history
-
Double-Spend Prevention:
- Clear: UTXO either spent or unspent
- No ambiguity
-
Privacy:
- Multiple UTXOs per user
- Harder to track total balance
-
Transaction Transparency:
- Clear input-output relationships
- Easy to trace fund flows
UTXO Set Statistics (Bitcoin 2023):
Total UTXOs: ~90 million
UTXO Set Size: ~6 GB
Average UTXO value: ~0.01 BTC
Growth: ~10-15% per year
Comparison: UTXO vs Account Model
| Aspect | UTXO (Bitcoin) | Account (Ethereum) |
|---|---|---|
| Balance Storage | Sum of UTXOs | Single account balance |
| Transaction Model | Consume UTXOs, create new ones | Debit/Credit accounts |
| State | Stateless | Stateful |
| Parallelization | Easy | Complex |
| Smart Contracts | Limited | Full support |
| Simplicity | Transaction-centric | Account-centric |
Module IV - Smart Contracts and Use Cases — #### Question 17
Question 17
(a) Illustrate how blockchain technology can be used in supply chain management (7 marks)
Blockchain in Supply Chain Management creates transparent, traceable supply chains tracking products from origin to consumer with immutable records, smart contract automation, and real-time visibility.
Traditional Supply Chain Problems:
- Lack of transparency and visibility
- Counterfeiting and fraud
- Paper-based inefficiencies
- Data silos and disconnected systems
- Trust issues between parties
- Slow dispute resolution
Blockchain Supply Chain Architecture:
graph LR
A[Supplier] -->|Record Origin| B[Blockchain]
C[Manufacturer] -->|Processing Data| B
D[Distributor] -->|Shipment Info| B
E[Retailer] -->|Receipt| B
F[Consumer] -->|Verify| B
B -->|Smart Contracts| G[Automated Payments]
B -->|IoT Data| H[Quality Monitoring]
Key Applications:
1. Product Traceability - End-to-End Tracking
Each product gets unique digital identity, every step recorded immutably on blockchain.
Example - Food Supply Chain:
Farm → Blockchain Record (origin, harvest date, farmer ID)
Processing → Record (processing date, quality checks)
Distribution → Record (shipment details, temperature logs)
Retail → Record (received date, shelf placement)
Consumer → Scan QR code, see complete journey
Benefits: Track contamination source in seconds vs. days
2. Anti-Counterfeiting
Digital fingerprint prevents product duplication, consumers verify authenticity via blockchain.
Pharmaceutical Example:
Manufacturing → Unique hash for each medicine batch
Distribution → Each transfer verified on blockchain
Pharmacy → Scans code, blockchain confirms genuine
Consumer → Final authenticity check
3. Smart Contract Automation
Automatic execution when conditions met:
// Simplified example
contract SupplyChainPayment {
function confirmDelivery(uint orderId) public {
if (deliveryVerified(orderId)) {
// Automatic payment release
paySupplier(orderId);
}
}
}
Triggers: Payment on delivery, quality penalties, automatic reordering
4. IoT Integration for Quality Assurance
Temperature, humidity, location sensors feed data to blockchain.
Cold Chain Example:
Refrigerated Transport:
- Sensor logs temperature every 15 minutes
- If temp > threshold → Alert + reject shipment
- Smart contract withholds payment automatically
5. Regulatory Compliance
Immutable audit trail for regulators, automatic compliance checks, instant reporting.
Benefits: 90% faster audits, automatic violation detection
Real-World Examples:
- Walmart + IBM Food Trust: Track produce, 7 days → 2.2 seconds trace time
- Maersk + TradeLens: Shipping containers, 80% paperwork reduction
- De Beers Tracr: Diamond tracking, prevents conflict diamonds
Benefits Summary:
- Transparency: 100% supply chain visibility
- Efficiency: 40% cost reduction
- Trust: Zero disputes with immutable records
- Speed: Real-time tracking vs. days of delays
- Anti-fraud: 95% reduction in counterfeits
(b) Detail the basic architecture of a DApp with the help of a neat diagram (7 marks)
DApp (Decentralized Application) runs on blockchain instead of centralized servers, providing transparency, censorship resistance, and user control.
DApp Architecture:
graph TB
subgraph "Frontend Layer"
A[Web UI React/Vue]
B[Mobile App]
end
subgraph "Web3 Layer"
C[Web3.js/Ethers.js]
D[Wallet MetaMask]
end
subgraph "Blockchain Layer"
E[Smart Contracts]
F[Ethereum Network]
end
subgraph "Storage Layer"
G[On-Chain State]
H[IPFS Off-Chain]
end
A --> C
B --> C
C --> D
D --> E
E --> F
E --> G
A --> H
Architecture Layers:
1. Frontend Layer
- User interface (web/mobile)
- React, Vue, Angular
- Displays blockchain data
- Sends transactions
2. Web3 Interface Layer
- Web3 Libraries: Connect frontend to blockchain
- Wallet Integration: MetaMask manages keys, signs transactions
- RPC Providers: Infura/Alchemy provide blockchain access
Example:
import { ethers } from 'ethers';
// Connect to blockchain
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
// Interact with smart contract
const contract = new ethers.Contract(address, abi, signer);
const result = await contract.getValue();
3. Blockchain Layer
- Smart Contracts: Core business logic in Solidity
- Blockchain Network: Ethereum, Polygon, etc.
- Consensus: Validates all transactions
Smart Contract Example:
contract MyDApp {
mapping(address => uint) public balances;
function deposit() public payable {
balances[msg.sender] += msg.value;
emit Deposit(msg.sender, msg.value);
}
function withdraw(uint amount) public {
require(balances[msg.sender] >= amount);
balances[msg.sender] -= amount;
payable(msg.sender).transfer(amount);
}
}
4. Storage Layer
- On-Chain: Critical data (balances, ownership) - expensive
- Off-Chain (IPFS): Large files, images - cost-effective
- Store IPFS hash on-chain, actual data off-chain
5. Backend Services (Optional)
- The Graph: Index blockchain data for queries
- Event Listeners: Monitor smart contract events
- APIs: Off-chain data integration
Data Flow:
sequenceDiagram
User->>Frontend: Click button
Frontend->>Wallet: Request transaction
Wallet->>User: Approve?
User->>Wallet: Approve
Wallet->>SmartContract: Send transaction
SmartContract->>Blockchain: Execute
Blockchain-->>Frontend: Confirmation
Frontend-->>User: Success!
DApp Examples:
- Uniswap: Decentralized exchange
- OpenSea: NFT marketplace
- Aave: Lending protocol
Key Characteristics:
- Open Source: Code publicly available
- Decentralized: No central control
- Incentivized: Token rewards
- Trustless: No need to trust authority
Advantages:
- Zero downtime
- Censorship resistant
- Transparent operations
- User data control
Challenges:
- Complex user experience
- High gas fees
- Scalability limitations
- Immutable bugs
Question 18
(a) Elaborate on the concept of an oracle in the context of smart contracts, and illustrate the general flow of data between an oracle and a smart contract using a neat diagram (7 marks)
Oracle bridges blockchain and external world, providing real-world data to smart contracts that cannot directly access off-chain information.
The Oracle Problem:
Smart contracts are isolated—they can't:
- Access internet
- Fetch API data
- Get random numbers
- Read real-world events
Need for Oracles:
Smart Contract Needs:
- Price feeds (DeFi)
- Weather data (insurance)
- Sports scores (betting)
- IoT sensor data
- API responses
Oracle provides this data
Types of Oracles:
1. Inbound Oracles: Bring external data to blockchain
- Price feeds, weather, sports results
2. Outbound Oracles: Send blockchain data to external systems
- Trigger bank payments, external notifications
3. Centralized: Single provider (fast, less secure)
4. Decentralized: Multiple providers (slower, more secure)
- Example: Chainlink
Oracle Data Flow:
sequenceDiagram
participant SC as Smart Contract
participant Oracle as Oracle Contract
participant Node as Oracle Node
participant API as External API
SC->>Oracle: 1. Request data (ETH price)
Oracle->>Node: 2. Emit event
Node->>API: 3. Fetch data
API-->>Node: 4. Return price ($1850)
Node->>Node: 5. Verify & sign
Node->>Oracle: 6. Submit on-chain
Oracle->>SC: 7. Callback with data
SC->>SC: 8. Execute logic
Detailed Flow:
Step 1: Smart Contract Requests Data
contract PriceFeed {
uint public ethPrice;
function requestPrice() public {
oracle.requestData("ETH/USD", this.callback);
}
function callback(uint price) external {
require(msg.sender == oracleAddress);
ethPrice = price;
}
}
Step 2: Oracle Contract Emits Event
contract OracleContract {
event DataRequested(bytes32 requestId, string query);
function requestData(string memory query) public {
emit DataRequested(requestId, query);
}
}
Step 3: Off-Chain Node Fetches Data
// Oracle node detects event
oracleContract.on("DataRequested", async (id, query) => {
const data = await fetch(`https://api.coinbase.com/v2/prices/${query}`);
await oracleContract.fulfillRequest(id, data);
});
Step 4: Multiple Nodes Provide Data
Node 1: $1850.50
Node 2: $1851.00
Node 3: $1850.75
Median: $1850.75 ← Used for security
Step 5: Oracle Submits Data
function fulfillRequest(bytes32 id, uint data) public {
require(verifyOracleNode(msg.sender));
requests[id].callbackAddress.call(
abi.encodeWithSelector(requests[id].callback, data)
);
}
Chainlink Example (Leading Oracle):
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
contract PriceConsumer {
AggregatorV3Interface internal priceFeed;
constructor() {
priceFeed = AggregatorV3Interface(
0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419 // ETH/USD
);
}
function getLatestPrice() public view returns (int) {
(, int price, , , ) = priceFeed.latestRoundData();
return price;
}
}
Oracle Use Cases:
1. DeFi - Price Feeds
- Aave, Compound need asset prices
- For collateral valuation, liquidations
2. Insurance - Parametric Insurance
- Flight delay insurance
- Automatic payout if flight delayed > 2 hours
3. Gaming - Random Numbers
- Lottery needs verifiable randomness
- Chainlink VRF provides this
4. Supply Chain - IoT Data
- Temperature sensor readings
- Trigger alerts on threshold breach
Security Considerations:
Risks:
- Single oracle can be manipulated
- False data injection
- Oracle failure
Solutions:
- Use multiple decentralized oracles
- Aggregate data (median/average)
- Reputation systems
- Economic incentives (stake slashing)
Key Points:
- Oracles enable smart contracts to interact with real world
- Decentralized oracles preferred for security
- Essential for DeFi, insurance, gaming
- Trust in oracle = trust in entire system
(b) Explain the benefits and applications of integrating blockchain in cloud computing (7 marks)
Blockchain-Cloud Integration combines distributed ledger technology with cloud infrastructure for enhanced security, transparency, and decentralization.
Why Integrate?
Cloud Challenges:
- Centralization (single provider control)
- Trust issues (must trust provider)
- Data privacy concerns
- Vendor lock-in
- Security breaches
Blockchain Solutions:
- Decentralized infrastructure
- Cryptographic security
- Immutable audit trails
- Transparent operations
- Smart contract automation
Integration Architecture:
graph TB
subgraph "User Layer"
U[Users/Applications]
end
subgraph "Blockchain Layer"
B1[Smart Contracts]
B2[Access Control]
B3[Audit Logs]
end
subgraph "Cloud Services"
C1[Compute]
C2[Storage]
C3[Database]
end
subgraph "Providers"
P1[AWS]
P2[Azure]
P3[Google Cloud]
end
U --> B1
B1 --> B2
B2 --> C1
C1 --> P1
C2 --> P2
C3 --> P3
Benefits:
1. Enhanced Security and Data Integrity
Store data hash on blockchain, actual data on cloud:
contract CloudIntegrity {
mapping(string => bytes32) public fileHashes;
function storeHash(string memory fileId, bytes32 hash) public {
fileHashes[fileId] = hash;
}
function verifyFile(string memory fileId, bytes32 hash)
public view returns (bool)
{
return fileHashes[fileId] == hash;
}
}
Any data tampering detected immediately.
2. Decentralized Cloud Storage
Distribute data across multiple providers:
- Filecoin, Storj, Sia
- No single point of failure
- Lower costs through competition
- User controls encryption keys
3. Transparent Access Control
contract AccessControl {
mapping(address => mapping(string => bool)) public permissions;
mapping(string => AccessLog[]) public logs;
struct AccessLog {
address user;
uint timestamp;
string action;
}
function grantAccess(address user, string memory resource) public {
permissions[user][resource] = true;
logs[resource].push(AccessLog(user, block.timestamp, "GRANT"));
}
}
Benefits:
- Every access logged immutably
- Real-time monitoring
- Compliance-friendly (GDPR, HIPAA)
- Automatic audit reports
4. Smart Contract Automation
Automate cloud resource management:
contract CloudAutomation {
function renewSubscription() public payable {
require(msg.value >= fee);
subscriptions[msg.sender].expiry = block.timestamp + 30 days;
provisionResources(msg.sender); // Auto-provision
}
}
Applications:
- Automatic billing
- Resource scaling
- SLA enforcement
- Payment processing
5. Multi-Cloud Interoperability
Blockchain as neutral layer:
User → Blockchain → AWS
→ Azure
→ Google Cloud
No vendor lock-in, move workloads freely
6. Secure Data Sharing
Healthcare Example:
contract MedicalData {
mapping(address => mapping(address => bool)) public authorized;
function grantAccess(address doctor) public {
authorized[msg.sender][doctor] = true;
}
function revokeAccess(address doctor) public {
authorized[msg.sender][doctor] = false;
}
}
Patient controls own data, granular permissions, full audit trail.
Applications:
1. Healthcare Cloud
- Secure patient data sharing
- Patient controls access
- HIPAA compliant audit trails
2. Supply Chain Cloud
- Multi-party data verification
- Real-time tracking with trust
- Transparent operations
3. Financial Services
- Regulatory compliance
- Immutable transaction logs
- Fraud detection
4. IoT Data Management
- Validate massive IoT data
- Blockchain verification + cloud analytics
- Data integrity at scale
5. Identity Management
- Self-sovereign identity on blockchain
- Cloud services authentication
- User privacy control
Real-World Examples:
1. Microsoft Azure + Ethereum
- Azure Blockchain Service
- Blockchain-as-a-Service (BaaS)
- Enterprise applications
2. AWS + Hyperledger
- Amazon Managed Blockchain
- Scalable blockchain networks
- Cloud-native blockchain
3. IBM Cloud + Hyperledger Fabric
- IBM Blockchain Platform
- Food Trust (Walmart)
- TradeLens (Maersk shipping)
Benefits Summary:
| Benefit | Impact |
|---|---|
| Security | 99% reduction in tampering |
| Transparency | Full auditability |
| Decentralization | No single point of failure |
| Cost | 30-40% reduction |
| Trust | Verifiable operations |
| Interoperability | Multi-cloud flexibility |
Challenges:
- Integration complexity
- Performance overhead
- Scalability limits
- Additional costs
- Lack of standards
Future Trends:
- More BaaS offerings
- Edge computing integration
- AI model verifiability
- Quantum-resistant cryptography
- Green cloud with PoS
Module V - Ethereum and Solidity — #### Question 19
Question 19
(a) Create a Solidity bank contract that allows users to deposit, withdraw, and view their balance (7 marks)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Bank Contract
* @dev Allows users to deposit, withdraw, and check balance
*/
contract Bank {
// State variables
mapping(address => uint256) private balances;
address public owner;
uint256 public totalDeposits;
// Events
event Deposit(address indexed user, uint256 amount, uint256 newBalance);
event Withdrawal(address indexed user, uint256 amount, uint256 newBalance);
event BalanceChecked(address indexed user, uint256 balance);
// Modifiers
modifier onlyOwner() {
require(msg.sender == owner, "Only owner can call this function");
_;
}
modifier hasBalance(uint256 amount) {
require(balances[msg.sender] >= amount, "Insufficient balance");
_;
}
// Constructor
constructor() {
owner = msg.sender;
totalDeposits = 0;
}
/**
* @dev Deposit Ether into the bank
* User sends Ether with transaction, amount credited to their balance
*/
function deposit() public payable {
require(msg.value > 0, "Deposit amount must be greater than zero");
// Update user balance
balances[msg.sender] += msg.value;
// Update total deposits
totalDeposits += msg.value;
// Emit deposit event
emit Deposit(msg.sender, msg.value, balances[msg.sender]);
}
/**
* @dev Withdraw specified amount from user's balance
* @param amount Amount to withdraw in wei
*/
function withdraw(uint256 amount) public hasBalance(amount) {
require(amount > 0, "Withdrawal amount must be greater than zero");
require(address(this).balance >= amount, "Insufficient contract balance");
// Update balance before transfer (prevent reentrancy)
balances[msg.sender] -= amount;
totalDeposits -= amount;
// Transfer Ether to user
payable(msg.sender).transfer(amount);
// Emit withdrawal event
emit Withdrawal(msg.sender, amount, balances[msg.sender]);
}
/**
* @dev Get balance of caller
* @return User's balance in wei
*/
function getBalance() public view returns (uint256) {
return balances[msg.sender];
}
/**
* @dev Get balance of specific user (only owner can call)
* @param user Address to check
* @return Balance of specified user
*/
function getBalanceOf(address user) public view onlyOwner returns (uint256) {
return balances[user];
}
/**
* @dev Get total contract balance
* @return Total Ether held by contract
*/
function getContractBalance() public view returns (uint256) {
return address(this).balance;
}
/**
* @dev Get total deposits across all users
* @return Total deposits
*/
function getTotalDeposits() public view returns (uint256) {
return totalDeposits;
}
// Fallback function to receive Ether
receive() external payable {
deposit();
}
}
Contract Features:
1. State Variables:
balances: Mapping of user addresses to their balancesowner: Contract deployer addresstotalDeposits: Track total Ether deposited
2. Events:
Deposit: Logged when user depositsWithdrawal: Logged when user withdrawsBalanceChecked: Optional event for balance queries
3. Modifiers:
onlyOwner: Restrict functions to ownerhasBalance: Ensure sufficient balance before withdrawal
4. Functions:
deposit():
- Accepts Ether via
payable - Updates user balance
- Emits Deposit event
- Checks: Amount > 0
withdraw(amount):
- Transfers Ether back to user
- Uses
hasBalancemodifier - Updates balance before transfer (reentrancy protection)
- Checks: Sufficient balance, amount > 0
getBalance():
- View function (no gas cost)
- Returns caller's balance
- Public access
getBalanceOf(user):
- Owner-only function
- Check any user's balance
- Useful for administration
5. Security Features:
Reentrancy Protection:
// Update state BEFORE transfer
balances[msg.sender] -= amount;
payable(msg.sender).transfer(amount);
Input Validation:
require(msg.value > 0, "Amount must be greater than zero");
require(balances[msg.sender] >= amount, "Insufficient balance");
Access Control:
modifier onlyOwner() {
require(msg.sender == owner, "Not authorized");
_;
}
Usage Example:
// Deploy contract
const bank = await Bank.deploy();
// Deposit 1 ETH
await bank.deposit({ value: ethers.utils.parseEther("1.0") });
// Check balance
const balance = await bank.getBalance();
console.log(`Balance: ${ethers.utils.formatEther(balance)} ETH`);
// Withdraw 0.5 ETH
await bank.withdraw(ethers.utils.parseEther("0.5"));
// Check new balance
const newBalance = await bank.getBalance();
console.log(`New Balance: ${ethers.utils.formatEther(newBalance)} ETH`);
Testing Scenarios:
- Deposit Test: User deposits 1 ETH, balance updates correctly
- Withdraw Test: User withdraws 0.5 ETH, receives funds
- Insufficient Balance: Withdrawal exceeds balance, transaction reverts
- Multiple Users: Multiple users deposit/withdraw independently
- Event Emission: Events logged correctly for audit trail
(b) Explain how transactions are processed in Ethereum. Briefly explain the concept of gas and how does it affect the transaction processing? (7 marks)
Ethereum Transaction Processing:
Transaction Structure:
{
from: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb", // Sender
to: "0x123...", // Recipient
value: 1000000000000000000, // 1 ETH in wei
gas: 21000, // Gas limit
gasPrice: 50000000000, // 50 Gwei
nonce: 5, // Transaction count
data: "0x...", // Contract call data
chainId: 1, // Ethereum mainnet
v, r, s // Signature components
}
Transaction Processing Flow:
sequenceDiagram
participant User
participant Wallet
participant Node
participant Mempool
participant Miner
participant EVM
participant Blockchain
User->>Wallet: Create transaction
Wallet->>Wallet: Sign with private key
Wallet->>Node: Broadcast signed tx
Node->>Node: Validate signature & nonce
Node->>Mempool: Add to mempool
Miner->>Mempool: Select transactions (by gas price)
Miner->>EVM: Execute transaction
EVM->>EVM: Check gas, execute code
EVM->>Miner: Return result & gas used
Miner->>Blockchain: Include in block
Blockchain-->>User: Transaction confirmed
Detailed Steps:
Step 1: Transaction Creation
const tx = {
to: recipientAddress,
value: ethers.utils.parseEther("1.0"),
gasLimit: 21000,
gasPrice: ethers.utils.parseUnits("50", "gwei")
};
Step 2: Signing
const signer = provider.getSigner();
const signedTx = await signer.signTransaction(tx);
// Uses private key to create digital signature
Step 3: Broadcasting
const txResponse = await signer.sendTransaction(tx);
// Broadcasts to Ethereum network
Step 4: Validation
Nodes check:
- Valid signature
- Sufficient balance (value + gas fees)
- Correct nonce (prevents replay attacks)
- Gas limit reasonable
Step 5: Mempool (Pending Transactions)
Transaction Pool (Mempool):
- Pending transactions wait here
- Miners select highest gas price first
- Low gas price = longer wait time
Step 6: Miner Selection
Miner prioritizes by:
1. Gas price (higher = priority)
2. Nonce order (sequential)
3. Block gas limit constraints
Step 7: Execution in EVM
For each transaction:
1. Deduct gas prepayment
2. Execute code step-by-step
3. Each operation costs gas
4. If gas runs out → revert
5. If successful → apply state changes
6. Refund unused gas
Step 8: Block Inclusion
Miner creates block:
- Multiple transactions
- Block reward + tx fees
- Broadcast to network
- Validators verify
- Add to blockchain
Step 9: Confirmations
Block N: Transaction included (1 confirmation)
Block N+1: (2 confirmations)
Block N+2: (3 confirmations)
...
Block N+12: (12 confirmations) ← Considered final
Gas Concept:
What is Gas?
Gas is the unit measuring computational work required to execute operations on Ethereum.
Purpose:
- Prevent infinite loops: Limit computation
- Prioritize transactions: Higher gas price = faster processing
- Compensate miners: Pay for computational resources
- Prevent spam: Cost to use network
Gas Mechanics:
Gas Limit:
- Maximum gas willing to spend
- Set by user
- If execution exceeds limit → transaction fails
- Unused gas refunded
Gas Price:
- Price per unit of gas (in Gwei)
- User sets this (higher = faster confirmation)
- 1 Gwei = 0.000000001 ETH
Gas Used:
- Actual gas consumed by transaction
- Depends on operations executed
Transaction Fee Calculation:
Transaction Fee = Gas Used × Gas Price
Example:
Gas Used: 21,000 (simple ETH transfer)
Gas Price: 50 Gwei
Fee = 21,000 × 50 = 1,050,000 Gwei = 0.00105 ETH
If ETH = $1,800:
Fee = 0.00105 × $1,800 = $1.89
Gas Costs for Operations:
Operation | Gas Cost
------------------------|----------
ADD (addition) | 3 gas
MUL (multiplication) | 5 gas
SSTORE (storage write) | 20,000 gas
SLOAD (storage read) | 800 gas
LOG0 (event) | 375 gas
CREATE (contract) | 32,000 gas
SHA3 (hash) | 30 gas
CALL (external call) | 700 gas
Example Gas Usage:
Simple Transfer:
// Send ETH: 21,000 gas (fixed)
payable(recipient).transfer(amount);
Storage Write:
// Expensive! ~20,000 gas
myVariable = 123;
Complex Contract:
contract GasExample {
uint[] public numbers;
// More operations = more gas
function addNumbers(uint count) public {
for (uint i = 0; i < count; i++) {
numbers.push(i); // Storage write each iteration
}
// count=10: ~250,000 gas
// count=100: ~2,000,000 gas
}
}
EIP-1559 Gas Model (Post-London Upgrade):
New Fee Structure:
Total Fee = (Base Fee + Priority Fee) × Gas Used
Base Fee:
- Network-determined
- Burned (removed from circulation)
- Adjusts based on congestion
Priority Fee (Tip):
- User-set
- Goes to miner
- Incentivizes inclusion
Example:
{
maxFeePerGas: ethers.utils.parseUnits("100", "gwei"), // Maximum willing to pay
maxPriorityFeePerGas: ethers.utils.parseUnits("2", "gwei"), // Tip to miner
}
If Base Fee = 50 Gwei:
Actual Fee = (50 + 2) × Gas Used
Max Fee ensures won't pay more than 100 Gwei/gas
Impact of Gas on Transaction Processing:
1. Transaction Priority:
High Gas Price → Fast confirmation (next block)
Medium Gas Price → Normal confirmation (2-5 blocks)
Low Gas Price → Slow confirmation (10+ blocks or timeout)
2. Transaction Success:
function riskyFunction() public {
// If gas runs out mid-execution
for (uint i = 0; i < 1000000; i++) {
// Loop consumes gas
}
// Transaction reverts if gas limit too low
// All changes rolled back
// Gas fee still paid (work was done)
}
3. Network Congestion:
High demand → Base fee increases → Higher tx costs
Low demand → Base fee decreases → Lower tx costs
NFT launch:
- Demand spikes
- Base fee: 50 Gwei → 500 Gwei
- Transaction costs 10x higher
4. Smart Contract Design:
// Gas-inefficient
function badLoop() public {
for (uint i = 0; i < 1000; i++) {
data[i] = i; // 1000 storage writes = 20M gas!
}
}
// Gas-efficient
function goodApproach() public {
// Batch operations
// Use memory instead of storage
// Minimize loops
}
Gas Optimization Strategies:
- Use memory instead of storage
- Batch operations
- Avoid loops over storage
- Pack variables (use uint8, uint16 when possible)
- Delete unused storage (gas refund)
- Use events instead of storage for logging
Gas Estimation:
// Estimate before sending
const gasEstimate = await contract.estimateGas.myFunction(params);
console.log(`Estimated gas: ${gasEstimate.toString()}`);
// Add 10% buffer
const gasLimit = gasEstimate.mul(110).div(100);
// Send with estimated gas
await contract.myFunction(params, { gasLimit });
Key Takeaways:
- Gas prevents infinite loops and spam
- Higher gas price = faster confirmation
- Gas fees compensate miners/validators
- Unused gas refunded
- Failed transactions still cost gas
- Optimize contracts to reduce gas costs
- Network congestion affects gas prices
- EIP-1559 introduced base fee + priority fee model
Question 20
(a) Define Smart Contract. Using Solidity language, create a simple contract that allows a user to store and retrieve a single string value (7 marks)
Smart Contract Definition:
A Smart Contract is a self-executing program stored on a blockchain that automatically enforces and executes the terms of an agreement when predefined conditions are met, without requiring intermediaries or central authority.
Key Characteristics:
- Self-Executing: Automatically runs when conditions satisfied
- Immutable: Once deployed, code cannot be changed
- Transparent: Code and execution visible to all
- Deterministic: Same inputs always produce same outputs
- Trustless: No need to trust counterparty; code enforces rules
- Distributed: Runs on decentralized blockchain network
Components:
- State Variables: Data stored on blockchain
- Functions: Methods to interact with contract
- Events: Notifications emitted during execution
- Modifiers: Reusable code for access control
Simple String Storage Contract:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title SimpleStorage
* @dev Store and retrieve a single string value
* Demonstrates basic smart contract functionality
*/
contract SimpleStorage {
// State variable - stored on blockchain
string private storedData;
// Track who last updated the data
address public lastUpdater;
// Track when data was last updated
uint256 public lastUpdateTime;
// Event emitted when data is stored
event DataStored(
address indexed user,
string data,
uint256 timestamp
);
// Event emitted when data is retrieved
event DataRetrieved(
address indexed user,
string data,
uint256 timestamp
);
// Modifier to check if data exists
modifier hasData() {
require(bytes(storedData).length > 0, "No data stored yet");
_;
}
/**
* @dev Store a string value
* @param _data The string to store
* Emits DataStored event
*/
function store(string memory _data) public {
// Validate input
require(bytes(_data).length > 0, "Cannot store empty string");
require(bytes(_data).length <= 256, "String too long (max 256 chars)");
// Update state variables
storedData = _data;
lastUpdater = msg.sender;
lastUpdateTime = block.timestamp;
// Emit event for off-chain tracking
emit DataStored(msg.sender, _data, block.timestamp);
}
/**
* @dev Retrieve the stored string
* @return The stored string value
* Emits DataRetrieved event
*/
function retrieve() public hasData returns (string memory) {
// Emit event
emit DataRetrieved(msg.sender, storedData, block.timestamp);
// Return stored data
return storedData;
}
/**
* @dev View function to retrieve data without emitting event
* @return The stored string value
* No gas cost (view function)
*/
function getData() public view hasData returns (string memory) {
return storedData;
}
/**
* @dev Check if data has been stored
* @return True if data exists, false otherwise
*/
function hasStoredData() public view returns (bool) {
return bytes(storedData).length > 0;
}
/**
* @dev Get metadata about stored data
* @return updater Address of last updater
* @return timestamp Time of last update
* @return dataLength Length of stored string
*/
function getMetadata() public view returns (
address updater,
uint256 timestamp,
uint256 dataLength
) {
return (
lastUpdater,
lastUpdateTime,
bytes(storedData).length
);
}
/**
* @dev Clear stored data (only last updater can clear)
* Demonstrates access control
*/
function clear() public {
require(msg.sender == lastUpdater, "Only last updater can clear");
require(bytes(storedData).length > 0, "No data to clear");
storedData = "";
emit DataStored(msg.sender, "", block.timestamp);
}
}
Contract Explanation:
1. State Variables:
string private storedData; // The main data
address public lastUpdater; // Who updated last
uint256 public lastUpdateTime; // When updated
2. Events:
event DataStored(address indexed user, string data, uint timestamp);
event DataRetrieved(address indexed user, string data, uint timestamp);
- Allow off-chain applications to track changes
- Cost less than storing data on-chain
3. Modifiers:
modifier hasData() {
require(bytes(storedData).length > 0, "No data stored");
_;
}
- Reusable access control logic
- Checks conditions before function executes
4. Functions:
store(string):
- Public function anyone can call
- Validates input (not empty, length check)
- Updates state variables (costs gas)
- Emits event
retrieve():
- Returns stored string
- Emits event (costs gas)
- Requires data exists
getData():
- View function (FREE - no gas cost)
- Doesn't modify state
- Doesn't emit events
- Read-only
Usage Example:
// Deploy contract
const SimpleStorage = await ethers.getContractFactory("SimpleStorage");
const storage = await SimpleStorage.deploy();
await storage.deployed();
// Store a string
await storage.store("Hello, Blockchain!");
// Retrieve using view function (free)
const data = await storage.getData();
console.log(`Stored data: ${data}`);
// Check metadata
const [updater, timestamp, length] = await storage.getMetadata();
console.log(`Updated by: ${updater}`);
console.log(`At: ${new Date(timestamp * 1000)}`);
console.log(`Length: ${length} characters`);
// Retrieve with event (costs gas)
const tx = await storage.retrieve();
await tx.wait();
// Listen for events
storage.on("DataStored", (user, data, timestamp) => {
console.log(`Data stored by ${user}: ${data}`);
});
Testing Scenarios:
- Store Valid String: Store "Hello World", verify stored correctly
- Retrieve String: Retrieve data, check matches stored value
- Empty String: Attempt to store "", transaction reverts
- Long String: Store 256+ chars, transaction reverts
- Multiple Updates: Update multiple times, lastUpdater changes
- Clear Data: Last updater clears, unauthorized user cannot
Gas Costs:
Operation | Estimated Gas
-----------------------|---------------
Deploy contract | ~300,000 gas
Store "Hello" | ~50,000 gas
Store longer string | ~60,000+ gas
Retrieve (view) | 0 gas (free)
Retrieve (with event) | ~30,000 gas
Advanced Features (Optional):
// Version history
mapping(uint => string) public history;
uint public versionCount;
function storeWithHistory(string memory _data) public {
storedData = _data;
history[versionCount] = _data;
versionCount++;
}
// Multiple users
mapping(address => string) public userData;
function storeForUser(string memory _data) public {
userData[msg.sender] = _data;
}
Security Considerations:
- Input Validation: Check string length, emptiness
- Access Control: Restrict who can clear data
- Gas Limits: Limit string length to prevent high gas costs
- Event Logging: Track all changes for transparency
Smart Contract Benefits Demonstrated:
- Transparency: Anyone can verify stored data
- Immutability: Historical data cannot be changed
- Accessibility: Available 24/7 on blockchain
- Trustless: No central authority needed
- Automated: Executes automatically when called
(b) Explain the various elements present in the Ethereum blockchain (7 marks)
Ethereum Blockchain Elements:
Ethereum is a decentralized platform for running smart contracts and decentralized applications (DApps). Understanding its architecture is essential for blockchain development.
1. Accounts
Two types of accounts in Ethereum:
Externally Owned Accounts (EOAs):
Address: 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb
Balance: 10.5 ETH
Nonce: 42 (transaction count)
Code: None
Controlled by: Private key
Can: Initiate transactions, send ETH
Cannot: Execute code
Contract Accounts:
Address: 0x1234... (generated when deployed)
Balance: 5.2 ETH
Code: Smart contract bytecode
Storage: Persistent contract state
Controlled by: Contract code
Can: Execute code, store data
Cannot: Initiate transactions (only respond)
Key Differences:
| Feature | EOA | Contract Account |
|---|---|---|
| Control | Private key | Code |
| Code | None | Solidity/bytecode |
| Initiate Tx | Yes | No |
| Storage | Balance only | Balance + state |
2. Transactions
Data structure transferring value or calling contract functions:
{
from: "0x742d...", // Sender (EOA only)
to: "0x1234...", // Recipient (EOA or contract)
value: 1000000000000000000, // 1 ETH in wei
gasLimit: 21000, // Max gas willing to spend
gasPrice: 50000000000, // 50 Gwei per gas
nonce: 5, // Transaction count (prevents replay)
data: "0x...", // Contract function call data
v, r, s // Signature components (ECDSA)
}
Transaction Types:
- Value Transfer: Send ETH between accounts
- Contract Creation: Deploy new smart contract
- Contract Interaction: Call contract functions
3. Blocks
Container for transactions, forming the blockchain:
{
number: 15537394, // Block height
hash: "0xabc123...", // Block identifier
parentHash: "0xdef456...", // Previous block hash
timestamp: 1663224162, // Unix timestamp
miner: "0x789...", // Block proposer
difficulty: 15000000000000000, // Mining difficulty
gasLimit: 30000000, // Max gas per block
gasUsed: 25000000, // Actual gas used
transactions: [tx1, tx2, ...], // List of transactions
stateRoot: "0x...", // State trie root
receiptsRoot: "0x...", // Receipts trie root
transactionsRoot: "0x...", // Transactions trie root
}
Block Components:
Header:
- Metadata and roots
- Links to previous block
- Proof of work/stake
Body:
- Transaction list
- Can contain 100-300 transactions
- Limited by gas limit
4. Ethereum Virtual Machine (EVM)
Purpose: Execution environment for smart contracts
Characteristics:
- Stack-based: Uses stack for operations
- Deterministic: Same inputs → same outputs
- Isolated: Sandboxed execution
- Gas-metered: Every operation costs gas
EVM Architecture:
graph TB
A[Smart Contract<br/>Solidity Code] --> B[Compiler]
B --> C[Bytecode]
C --> D[EVM]
D --> E[Stack]
D --> F[Memory]
D --> G[Storage]
D --> H[Call Data]
style D fill:#FFD700
EVM Components:
Stack:
- 1024-item stack
- Stores temporary values
- LIFO (Last In, First Out)
Memory:
- Temporary storage during execution
- Cleared after transaction
- Array of bytes
Storage:
- Persistent key-value store
- Part of account state
- Expensive to use
Example EVM Operations:
PUSH1 5 // Push 5 onto stack
PUSH1 3 // Push 3 onto stack
ADD // Pop 2 values, add, push result (8)
SSTORE // Store result in storage
5. Gas
Computational unit measuring work:
Gas Limit: Maximum gas for transaction
Gas Price: Price per gas unit (Gwei)
Gas Used: Actual gas consumed
Transaction Fee = Gas Used × Gas Price
Purpose:
- Prevent infinite loops
- Prioritize transactions
- Compensate miners/validators
- Prevent spam
Operation Costs:
ADD: 3 gas
MUL: 5 gas
SSTORE: 20,000 gas (storage write)
SLOAD: 800 gas (storage read)
CREATE: 32,000 gas (deploy contract)
6. State
Global state of all accounts:
{
"0x742d...": { // EOA
balance: 10500000000000000000,
nonce: 42,
codeHash: null,
storageRoot: null
},
"0x1234...": { // Contract
balance: 5200000000000000000,
nonce: 1,
codeHash: "0xabc...",
storageRoot: "0xdef..."
}
}
State Trie:
- Modified Merkle Patricia Trie
- Efficiently stores account data
- Root hash in block header
- Any change → new root hash
7. Consensus Mechanism
Historical: Proof of Work (PoW)
- Miners solve puzzles
- High energy consumption
- ~13 second block time
Current: Proof of Stake (PoS) - Post-Merge
- Validators stake 32 ETH
- Randomly selected to propose blocks
- 99.95% less energy
- ~12 second block time (finality in 2 epochs)
Consensus Flow:
1. Validators stake ETH
2. Random selection for block proposal
3. Other validators attest (vote)
4. 2/3+ attestations → block accepted
5. Rewards distributed
6. Slashing for misbehavior
8. Network
Peer-to-Peer Network:
Nodes:
- Full nodes: Store entire blockchain
- Light nodes: Store block headers only
- Archive nodes: Store all historical states
Node Functions:
- Validate transactions
- Propose/validate blocks
- Maintain blockchain copy
- Broadcast information
Communication:
- Gossip protocol
- RLPx (transport protocol)
- Devp2p (peer discovery)
9. Smart Contracts
Definition: Self-executing code on blockchain
Components:
contract Example {
// State variables (storage)
uint public data;
// Events (logging)
event DataUpdated(uint newData);
// Functions
function setData(uint _data) public {
data = _data;
emit DataUpdated(_data);
}
}
Deployment:
1. Write Solidity code
2. Compile to bytecode
3. Send deployment transaction
4. Contract gets address
5. Bytecode stored on blockchain
10. Ether (ETH)
Native Cryptocurrency:
Purpose:
- Pay transaction fees (gas)
- Staking (validators lock 32 ETH)
- Store of value
- Medium of exchange
Units:
1 ETH = 1,000,000,000,000,000,000 wei
1 ETH = 1,000,000,000 Gwei
1 Gwei = 1,000,000,000 wei
Supply:
- No hard cap
- Issuance rate varies
- EIP-1559 burns base fees (deflationary pressure)
11. Storage
Types:
Storage: Persistent, expensive
uint public permanentData; // Stored forever
Memory: Temporary, cheaper
function process() public {
uint[] memory temp; // Cleared after function
}
Calldata: Read-only, cheapest
function process(uint[] calldata data) external {
// Cannot modify data
}
12. Events and Logs
Purpose: Notify external applications
event Transfer(address indexed from, address indexed to, uint value);
function transfer(address to, uint amount) public {
// ... transfer logic
emit Transfer(msg.sender, to, amount);
}
Storage:
- Stored in transaction receipts
- Not accessible by contracts
- Cheaper than storage
- Queryable by off-chain applications
13. Addresses
Format:
0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb
- 40 hexadecimal characters
- Derived from public key (EOA) or contract creation (contract)
- Checksum (mixed case) prevents typos
Ethereum Architecture Summary:
graph TB
A[User/DApp] --> B[Transaction]
B --> C[P2P Network]
C --> D[Validators]
D --> E[EVM]
E --> F[Execute Smart Contracts]
F --> G[Update State]
G --> H[Blocks]
H --> I[Blockchain]
style E fill:#FFD700
style I fill:#90EE90
Key Principles:
- Decentralization: No single point of control
- Transparency: All data publicly visible
- Immutability: Historical data cannot change
- Determinism: Predictable execution
- Trustlessness: Cryptographic security
Ethereum Evolution:
- Frontier (2015): Launch
- Homestead (2016): Stability improvements
- Byzantium/Constantinople (2017-2019): Features
- London (2021): EIP-1559 (new fee structure)
- The Merge (2022): PoW → PoS
- Shanghai (2023): Validator withdrawals
- Future: Sharding, scalability upgrades
END OF ANSWER KEY