CST428 · Blockchain Technologies · ← all papers

August 2024 (Supplementary) answer key

Every question from the KTU paper, answered line by line with its mark distribution. Tap a question to open it, or search across the whole paper.

Examination: August 2024 (Supplementary)
Course Code: CST428
Course Name: Blockchain Technologies
Total Marks: 100
Duration: 3 Hours
Modules Covered: All (1-5)
QP Code: 0400CST428082401

Part A Answer all · 3 marks each

Q1 Explain the different types of keys used in cryptography. 3 m

Mark distribution: Secret key, Public key and Private key - 1 mark each

Cryptography utilizes different types of keys to secure data, broadly categorized into symmetric and asymmetric systems.

  1. Secret Key (Symmetric Key): A single, shared key used for both encryption and decryption. Both communicating parties must possess this identical secret key. It is highly efficient for bulk data encryption but faces challenges in secure key distribution.
  2. Public Key (Asymmetric): Part of a key pair distributed openly. It is used to encrypt data or verify a digital signature. Anyone can use the public key to send a secure message to the key owner.
  3. Private Key (Asymmetric): The confidential counterpart to the public key, kept strictly secret by the owner. It is used to decrypt data encrypted with the corresponding public key or to generate a digital signature.

Diagram
Figure: Types of cryptographic keys in symmetric and asymmetric systems.

Q2 Explain the properties of cryptographic hash functions. 3 m

Mark distribution: Any three properties – 3 marks

A cryptographic hash function takes an arbitrary input and produces a fixed-size output (hash). To be secure, it must possess the following essential properties:

  1. Pre-image Resistance (One-Way): Given a specific hash output h, it must be computationally infeasible to find any input x such that H(x) = h. This ensures the hash cannot be reversed to reveal the original data.
  2. Second Pre-image Resistance: Given an input x1, it must be computationally infeasible to find a different input x2 such that H(x1) = H(x2). This prevents an attacker from substituting a malicious input that yields the same hash as a legitimate one.
  3. Collision Resistance: It must be computationally infeasible to find any two distinct inputs x1 and x2 such that H(x1) = H(x2). This is a stronger requirement than second pre-image resistance and is vital for digital signatures.

Additionally, hash functions exhibit the Avalanche Effect, where a minor change in input drastically alters the output, and are Deterministic, meaning the same input always yields the same hash.

Diagram
Figure: Core properties and flow of a cryptographic hash function.

Q3 With labelled diagram explain the block header? 3 m

Mark distribution: Components – 3 marks. May give full marks if illustrated with diagram

The block header is a metadata structure containing the summary of a block's contents. It is hashed to generate the block's unique identifier and linked to the previous block, forming the blockchain. Its primary components include:

  1. Version: Indicates the block validation rules or software version used to create the block.
  2. Previous Block Hash: A 256-bit hash of the previous block's header. This creates the immutable chain; altering any past block changes this hash, breaking the chain.
  3. Merkle Root: A single hash representing all transactions in the block, generated via a Merkle Tree. It ensures transaction integrity.
  4. Timestamp: Records the exact time the block was created by the miner or validator.
  5. Difficulty Target: Defines the cryptographic puzzle's difficulty level required to mine the block.
  6. Nonce: A 32-bit number incremented by miners during the Proof of Work process to find a valid block hash.

Diagram
Figure: Labelled components of a standard blockchain block header.

Q4 Explain the layered architecture of blockchain 3 m

Mark distribution: Architecture Explanation- 3 marks

Blockchain architecture is structured in a layered model to separate concerns, ensuring modularity, scalability, and security. The standard layered architecture consists of:

  1. Application/Presentation Layer: The topmost layer where users interact with the network via DApps, wallets, and user interfaces. It translates user actions into network requests.
  2. Smart Contract/Logic Layer: Contains the business logic and rules (smart contracts) that execute automatically when predefined conditions are met.
  3. Consensus Layer: The core mechanism that ensures all nodes agree on the state of the ledger. It handles block validation, node selection, and fault tolerance (e.g., PoS, PBFT).
  4. Network/P2P Layer: Manages node discovery, message propagation, and peer-to-peer communication, ensuring decentralized data transmission without a central server.
  5. Data/Storage Layer: The foundational layer where the actual ledger (blocks, transactions, state) is stored across distributed nodes, ensuring data persistence and immutability.

Diagram
Figure: Layered architecture of a blockchain network.

Q5 What are coinbase transactions? 3 m

Mark distribution: Explanation- 3 marks

A coinbase transaction (also known as a generation transaction) is a special type of transaction that is always the very first transaction in a newly mined block. Unlike regular transactions that transfer existing funds, a coinbase transaction creates new cryptocurrency out of thin air.

Key Characteristics:

  1. No Inputs: It does not reference any previous transaction outputs as inputs. Instead, it contains a special coinbase data field.
  2. Block Reward: It is used to pay the block reward (newly minted coins) and accumulated transaction fees to the miner or validator who successfully created the block.
  3. Maturity Rule: In networks like Bitcoin, the newly generated coins from a coinbase transaction cannot be spent until a certain number of blocks (e.g., 100 blocks) have been added to the chain, preventing issues in case of a blockchain reorganization.

Diagram
Figure: Position and purpose of the coinbase transaction within a block.

Q6 What do you mean by forks in blockchain? List the different types of forks in Blockchain? 3 m

Mark distribution: Explanation of fork – 2 marks, listing the types – 1 mark

A fork in blockchain refers to a divergence in the distributed ledger's network path, occurring when a blockchain splits into two alternative paths or when the protocol rules are changed. This happens due to disagreements in the community regarding protocol upgrades, resulting in a split where some nodes follow the old rules and others follow the new rules.

Types of Forks:

  1. Hard Fork: A permanent, backward-incompatible divergence. Nodes running the old software cannot validate blocks created by the new software, effectively splitting the blockchain into two separate networks (e.g., Ethereum and Ethereum Classic).
  2. Soft Fork: A backward-compatible upgrade. Nodes with the old software can still validate blocks from the new software, provided they follow the new rules. The network remains unified.
  3. Accidental Fork: Occurs when two miners mine a block at the exact same time, creating a temporary split that is resolved when the next block is mined (longest chain rule).

Diagram
Figure: Types of Blockchain Forks

Q7 What are the criteria to be met for an application to be considered as decentralized? 3 m

Mark distribution: Any three criteria- 3 marks

For an application or system to be considered truly decentralized, it must satisfy specific architectural and operational criteria to eliminate single points of control and failure. The three primary criteria are:

  1. Architectural Decentralization (No Single Point of Failure): The application's infrastructure must be distributed across multiple independent nodes. If one or several nodes fail, the system must continue to operate seamlessly without data loss or downtime.
  2. Political Decentralization (No Central Authority): No single entity, organization, or individual should have absolute control over the network's governance, rule changes, or data. Decision-making must be distributed among network participants.
  3. Logical Decentralization (Distributed Consensus): The application's state and data must be agreed upon via a distributed consensus mechanism (like Proof of Stake) rather than a central server. The data structure should appear as a single, coherent logical entity to the user, even though it is computed and stored across many nodes.

Diagram
Figure: Criteria for a Decentralized Application

Q8 List and explain the different types of oracles. 3 m

Mark distribution: Types of Oracles (explain any three) – 3 marks

Generic oracle data flow from external source to consumer contract
Figure: Generic oracle data flow from external source to consumer contract.

Oracles are third-party services that provide external, off-chain data to smart contracts, bridging the gap between the blockchain and the real world. The different types of oracles include:

  1. Inbound Oracles: These bring external data into the blockchain. They fetch real-world information (like weather data, asset prices, or sports results) and feed it to smart contracts so they can execute their logic based on off-chain events.
  2. Outbound Oracles: These send data from the blockchain to the external world. They allow smart contracts to trigger events or send information to external systems, such as notifying a traditional payment gateway to process a fiat transaction.
  3. Cross-Chain Oracles: These facilitate the reading and writing of data between different blockchain networks. They enable interoperability, allowing a smart contract on one blockchain (e.g., Ethereum) to verify and use data or transactions originating from another blockchain (e.g., Bitcoin).
  4. Hardware Oracles: These obtain data directly from physical sensors, RFID tags, or IoT devices, transmitting real-world physical conditions directly to the blockchain.

Diagram
Figure: Types of Blockchain Oracles

Q9 Illustrate inheritance in Solidity language. 3 m

Mark distribution: Explanation- 3 marks

Inheritance in Solidity is an object-oriented programming concept where a new contract (derived contract) can inherit the properties, state variables, and functions of an existing contract (base contract). This promotes code reusability and modularity. Solidity supports multiple inheritance, and the is keyword is used to derive a contract from a base contract. If a function is overridden, the override keyword must be used.

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

contract BaseContract {
    uint public baseValue;
    function setBase(uint _val) public { baseValue = _val; }
}

contract DerivedContract is BaseContract {
    function getBase() public view returns (uint) {
        return baseValue;
    }
}

In this example, DerivedContract inherits baseValue and setBase from BaseContract, allowing it to use and extend the base functionality without rewriting the code.

Diagram
Figure: Inheritance in Solidity

Q10 List the various components in Ethereum blockchain 3 m

Mark distribution: Addresses, EVM, cryptocurrency, smart contracts (explain any three) - 3 marks

Ethereum architecture: world state, blocks and the EVM
Figure: Ethereum architecture: world state, blocks and the EVM.

The Ethereum blockchain ecosystem comprises several core components that enable its decentralized functionality:

  1. Accounts and Addresses: Ethereum uses two types of accounts: Externally Owned Accounts (EOAs) controlled by private keys (users), and Contract Accounts controlled by smart contract code. Each account is identified by a unique 42-character hexadecimal address derived from the public key.
  2. Ethereum Virtual Machine (EVM): The EVM is the state machine and runtime environment for Ethereum. It executes smart contract bytecode in a sandboxed, deterministic environment across all nodes, ensuring consensus on the network's state without central coordination.
  3. Smart Contracts: These are self-executing programs written in high-level languages like Solidity, compiled into EVM bytecode, and deployed on the blockchain. They automatically enforce and execute the terms of an agreement when predefined conditions are met.
  4. Cryptocurrency (Ether): Ether (ETH) is the native cryptocurrency of the network. It is used to pay for transaction fees and computational services (Gas) required to execute smart contracts and secure the network via Proof of Stake.

Diagram
Figure: Core Components of the Ethereum Blockchain

Module I Fundamentals of Cryptography

Part B — answer any one full question from each module · 14 marks each

Q11 (a) Explain the working of AES algorithm. (b) What are the applications of cryptography. 14 m
(a) Explain the working of AES algorithm. (8 marks)

Mark distribution: Listing basic operations - 2 marks, explanation of AES rounds showing details of transformation of state matrix - 6 marks.

AES-128 encryption flow: key expansion, initial round, rounds 1–9 and the final round
Figure: AES-128 encryption flow: key expansion, initial round, rounds 1–9 and the final round.

The Advanced Encryption Standard (AES) is a symmetric key block cipher widely used for securing sensitive data. It operates on fixed-size blocks of data (128 bits) and uses cryptographic keys of 128, 192, or 256 bits.

Basic Operations of AES:
AES relies on four fundamental transformation operations applied to a 4x4 byte matrix known as the state matrix:

  1. SubBytes: A non-linear substitution step where each byte in the state matrix is replaced with another byte using a fixed lookup table called an S-box. This provides confusion.
  2. ShiftRows: A transposition step where each row of the state matrix is shifted cyclically to the left by a specific offset (Row 0 by 0, Row 1 by 1, Row 2 by 2, Row 3 by 3). This provides diffusion.
  3. MixColumns: A mixing step that operates on the columns of the state matrix, combining the four bytes in each column using a linear transformation. This provides further diffusion.
  4. AddRoundKey: A bitwise XOR operation where the state matrix is combined with a subkey derived from the main cipher key using a key schedule.

AES Rounds and State Matrix Transformation:
For a 128-bit key, AES performs exactly 10 rounds of transformation. The 128-bit plaintext is first arranged into a 4x4 state matrix (16 bytes). The rounds are structured as follows:

Diagram
Figure: AES Encryption Round Structure and State Matrix Transformations

  • Initial Round: Only the AddRoundKey operation is applied to the initial state matrix.
  • Rounds 1 to 9: All four operations (SubBytes, ShiftRows, MixColumns, AddRoundKey) are applied sequentially to the state matrix.
  • Final Round (Round 10): The MixColumns operation is omitted. Only SubBytes, ShiftRows, and AddRoundKey are applied to the final state matrix.

The resulting 4x4 state matrix after the final round is read column by column to produce the 128-bit ciphertext.

(b) What are the applications of cryptography. (6 marks)

Mark distribution: Any three applications with explanation - 2 marks each.

Cryptography is the foundational technology for securing digital information. Its applications span across various domains to ensure confidentiality, integrity, and authenticity.

Diagram
Figure: Core Applications and Goals of Cryptography

1. Data Confidentiality (Encryption):
Cryptography ensures that data is accessible only to authorized parties by converting plaintext into unreadable ciphertext. Symmetric algorithms (like AES) are used for bulk data encryption, while asymmetric algorithms (like RSA) secure the exchange of symmetric keys. Applications include securing web communications (TLS/SSL protocols), encrypting databases, protecting stored files on mobile devices, and securing messaging apps (end-to-end encryption).

2. Data Integrity (Hash Functions):
Cryptographic hash functions (like SHA-256) generate a unique, fixed-size digest for any given input. Even a single-bit change in the input produces a completely different hash. Applications include verifying the integrity of downloaded files or software updates, securely storing passwords (systems store the hash of a password rather than the plaintext), and forming the structural backbone of blockchain networks to link blocks and validate transactions.

3. Authentication and Non-Repudiation (Digital Signatures):
Using asymmetric cryptography, digital signatures verify the identity of the sender and ensure they cannot deny having sent the message. The sender signs a message hash with their private key, and the receiver verifies it with the corresponding public key. Applications include legally binding electronic contracts, authorizing financial transactions in banking, code signing for software distribution to prevent malware injection, and authorizing asset transfers in cryptocurrency networks.

Q12 (a) Explain digital signatures. Explain the uses of digital signatures (b) Explain how hash functions are used to build Merkle trees in blockchain. 14 m
(a) Explain digital signatures. Explain the uses of digital signatures (7 marks)

Mark distribution: Explanation of digital signatures - 4 marks, uses - 3 marks.

Explanation of Digital Signatures:
A digital signature is a mathematical mechanism used to verify the authenticity, integrity, and origin of a digital message or document. It serves as the digital equivalent of a handwritten signature but provides a much higher level of security using Public Key Infrastructure (PKI) and asymmetric cryptography.

The process involves two main phases:

  1. Signing Process: The sender first computes a cryptographic hash of the original message. This hash is then encrypted using the sender's private key. The resulting encrypted hash is the digital signature, which is attached to the original message and sent to the receiver.
  2. Verification Process: Upon receiving the message and signature, the receiver decrypts the signature using the sender's public key to retrieve the original hash. The receiver then independently computes the hash of the received message. If the two hashes match exactly, the signature is valid. This proves that the message was not altered in transit (integrity) and was indeed sent by the owner of the private key (authentication and non-repudiation).

Diagram
Figure: Digital Signature Signing and Verification Sequence

Uses of Digital Signatures:

  1. Financial Transactions: Banks, payment gateways, and stock exchanges use digital signatures to authorize high-value transfers, ensuring that transaction instructions are authentic and have not been tampered with by malicious actors.
  2. Software Distribution: Software developers digitally sign their applications and updates. Operating systems and antivirus software verify these signatures to ensure the code originates from a trusted publisher and has not been infected with malware.
  3. Legal and Government Documents: Digital signatures are legally recognized in many jurisdictions for signing contracts, tax filings, and official government records, providing a secure, paperless way to establish non-repudiation.
  4. Blockchain and Cryptocurrencies: In networks like Bitcoin and Ethereum, users use digital signatures to prove ownership of their cryptographic wallets and authorize the transfer of digital assets to other addresses.
(b) Explain how hash functions are used to build Merkle trees in blockchain. (7 marks)

Mark distribution: Merkle tree - 3 marks, hashing for Merkle tree - 4 marks.

Merkle Tree Structure:
A Merkle tree (or hash tree) is a fundamental binary tree data structure used in blockchain technology to efficiently summarize and verify the integrity of a large set of data, specifically the transactions within a block.

  • Leaf Nodes: The bottom-most nodes of the tree represent the individual transactions in the block. Each leaf node contains the cryptographic hash of a specific transaction.
  • Non-Leaf Nodes (Internal Nodes): Every parent node contains the cryptographic hash of its child nodes.
  • Merkle Root: The single node at the very top of the tree is called the Merkle Root. This root hash is stored in the block header and serves as a single, compact summary of all transactions in that block.

Diagram
Figure: Binary Structure of a Merkle Tree in a Blockchain Block

Hashing Process for Merkle Trees:
The construction of a Merkle tree relies entirely on the bottom-up application of cryptographic hash functions (such as SHA-256 in Bitcoin).

  1. Transaction Hashing: First, every transaction in the block is serialized into a byte stream and passed through the hash function. The resulting hashes form the leaf nodes of the tree.
  2. Pairing and Concatenation: The hashing process works level by level from the bottom up. Pairs of adjacent leaf node hashes are concatenated together. If there is an odd number of nodes at any level, the last unpaired hash is duplicated and concatenated with itself.
  3. Iterative Hashing: The concatenated hash pairs are then passed through the hash function again to produce the parent nodes. This pairing, concatenation, and hashing process is repeated iteratively for each level of the tree.
  4. Root Generation: The process continues until all hashes are reduced to a single, unique hash at the top of the tree—the Merkle Root. Because the root is mathematically derived from every single transaction, altering even one transaction will cascade up the tree and completely change the Merkle Root, instantly invalidating the block.
  5. Merkle Proofs (Efficiency): This hashing structure enables "Merkle proofs." A light client (like a mobile wallet) can verify if a specific transaction is included in a block by downloading only the specific "path" of hashes from the leaf to the root, rather than downloading the entire block. This requires only logarithmic space and time complexity, making blockchain verification highly scalable and efficient.

Module II Fundamentals of Blockchain Technology

Q13 (a) Explain how blockchain works using a neat diagram. (b) Compare centralized and decentralized systems. 14 m
(a) Explain how blockchain works using a neat diagram. (7 marks)

Mark distribution: Explanation - 4 marks, diagram - 3 marks

Explanation:
A blockchain is a decentralized, distributed, and immutable digital ledger that records transactions across a peer-to-peer (P2P) network. Unlike traditional databases managed by a central authority, a blockchain operates through a collaborative effort of network nodes. The working mechanism of a blockchain involves a systematic process of transaction creation, validation, and block addition.

  1. Transaction Initiation: A user initiates a transaction (e.g., transferring digital assets or executing a smart contract) and digitally signs it using their private key to prove ownership and authorize the transfer.
  2. Broadcasting to the Network: The signed transaction is broadcasted to the P2P network, where it is received by multiple nodes (participants) across the globe.
  3. Transaction Validation: The receiving nodes validate the transaction against the network's consensus rules. They verify the digital signature, check if the sender has sufficient balance, and ensure the transaction is not a double-spend attempt.
  4. Consensus Mechanism Execution: Validated transactions are grouped into a candidate block. The network nodes then run a consensus algorithm to agree on the validity of the block and the order of transactions. While early blockchains like Bitcoin relied on Proof of Work (PoW) utilizing computational miners, modern networks like Ethereum transitioned to Proof of Stake (PoS) in September 2022, utilizing validators who stake cryptocurrency to achieve consensus efficiently and securely.
  5. Block Creation and Hashing: Once consensus is reached, the new block is cryptographically sealed. The transactions within the block are hashed into a Merkle tree, producing a single Merkle root. The block header is then generated, containing the Merkle root, a timestamp, the nonce (or validator signature), and the cryptographic hash of the previous block's header.
  6. Addition to the Chain: The newly formed block is appended to the existing blockchain. Because each block contains the hash of the preceding block, a secure, chronological chain is formed. Altering any historical transaction would require recalculating the hashes of all subsequent blocks, which is computationally infeasible, thus ensuring immutability.

Diagram
Figure: Step-by-step workflow of how a blockchain processes and secures transactions.

(b) Compare centralized and decentralized systems. (7 marks)

Mark distribution: Comparison with explanation of any 4 points - 7 marks

Comparison and Explanation:
Centralized and decentralized systems represent two fundamentally different approaches to network architecture, control, and data management. The core differences can be understood across the following four key parameters:

  1. Control and Governance:

    • Centralized Systems: Control is concentrated in a single central authority or server (e.g., a traditional bank or a corporate database). This central entity dictates the rules, manages the infrastructure, and has the unilateral power to alter, delete, or restrict access to the data.
    • Decentralized Systems: Control is distributed across a network of peer nodes. There is no single point of authority. Governance is typically achieved through consensus mechanisms and predefined protocols, requiring the majority of the network to agree on any state changes or protocol upgrades.
  2. Trust Model and Verification:

    • Centralized Systems: Operate on a "trust-based" model. Users must trust the central authority to act honestly, secure the data, and process transactions correctly. Verification of transactions is handled internally by the central server.
    • Decentralized Systems: Operate on a "trustless" or "zero-trust" model. Participants do not need to trust each other or a central entity. Trust is established through cryptographic proofs and mathematical consensus. Every node independently verifies transactions against the shared ledger.
  3. Fault Tolerance and Availability:

    • Centralized Systems: Highly vulnerable to a Single Point of Failure (SPOF). If the central server goes offline due to hardware failure, cyberattacks (like DDoS), or maintenance, the entire system becomes unavailable to all users.
    • Decentralized Systems: Highly resilient and fault-tolerant. Because the ledger and processing power are replicated across hundreds or thousands of nodes, the failure of individual nodes does not affect the overall network. The system continues to operate seamlessly as long as a majority of nodes remain active.
  4. Transparency and Auditability:

    • Centralized Systems: Generally opaque. The internal workings, transaction logs, and decision-making processes of the central authority are hidden from the public. Users must rely on third-party audits to verify the system's integrity.
    • Decentralized Systems: Highly transparent. In public blockchains, the entire transaction history and the underlying protocol code are open for anyone to inspect. Any participant can independently audit the ledger to verify the system's state and ensure no fraudulent activities have occurred.

Diagram
Figure: Network topology comparison showing centralized star architecture versus decentralized mesh architecture.

Q14 (a) Enumerate benefits and limitations of using Blockchain Technology? (b) Illustrate the blockchain based decentralized system. 14 m
(a) Enumerate benefits and limitations of using Blockchain Technology? (7 marks)

Mark distribution: Benefits - 3.5 marks, limitations - 3.5 marks (at least 4 points in both)

Benefits of Blockchain Technology:

  1. Decentralization and Disintermediation: Blockchain removes the need for central intermediaries (like banks or clearinghouses). This reduces reliance on third parties, lowers transaction fees, and eliminates the risks associated with a central authority mismanaging funds or data.
  2. Immutability and Data Integrity: Once a transaction is recorded and added to the blockchain, it is cryptographically linked to the previous block. Altering historical data requires changing all subsequent blocks across the majority of the network, which is practically impossible. This guarantees a permanent, tamper-proof audit trail.
  3. Enhanced Transparency: All participants in a public blockchain network have access to the same distributed ledger. This transparency ensures that all transactions are publicly verifiable, fostering trust among anonymous parties and making it easier to track assets or verify compliance.
  4. Robust Security: Blockchain leverages advanced cryptographic primitives (like SHA-256 hashing and elliptic curve cryptography) combined with decentralized consensus. This makes the network highly resistant to cyberattacks, data breaches, and unauthorized alterations, as there is no central honeypot of data for hackers to target.

Limitations of Blockchain Technology:

  1. Scalability and Performance Issues: Because every node must process and store every transaction, and consensus must be reached across the network, blockchains suffer from low throughput. Traditional networks like Visa can handle tens of thousands of transactions per second (TPS), whereas base-layer blockchains typically handle only a fraction of that, leading to network congestion.
  2. High Resource and Energy Consumption: Certain consensus mechanisms, historically Proof of Work (PoW), require massive computational power, leading to significant electricity consumption. Even with the shift to Proof of Stake (PoS), the requirement for every node to maintain a full copy of the ever-growing ledger demands substantial storage and computational resources.
  3. Integration Complexity and Steep Learning Curve: Developing and integrating blockchain solutions requires specialized knowledge of cryptography, distributed systems, and specific smart contract languages (like Solidity). Migrating legacy systems to a blockchain architecture is complex, costly, and requires significant organizational restructuring.
  4. Regulatory and Legal Uncertainty: The decentralized and often pseudonymous nature of blockchain conflicts with existing legal frameworks, particularly concerning data privacy (like GDPR's "right to be forgotten," which contradicts blockchain immutability), taxation, and jurisdictional enforcement. This regulatory ambiguity hinders widespread enterprise adoption.

Diagram
Figure: Mind map illustrating the core benefits and limitations of blockchain technology.

(b) Illustrate the blockchain based decentralized system. (7 marks)

Mark distribution: Decentralisation definition - 3 marks, Explanation - 4 marks

Definition of Decentralisation:
Decentralization is the structural and operational distribution of power, control, and decision-making away from a central, authoritative entity to a distributed network of peers. In the context of computing and systems architecture, it means that no single node, administrator, or server possesses absolute control over the system's state, data, or operational rules. Instead, authority is shared, and the system operates collaboratively based on predefined protocols and consensus.

Explanation of Blockchain-Based Decentralized Systems:
Blockchain technology is the foundational enabler of modern digital decentralization. It achieves a fully decentralized ecosystem through the integration of several core components:

  1. Peer-to-Peer (P2P) Network Architecture: Instead of a client-server model, blockchain operates on a flat P2P topology. Every participant (node) has equal privileges and responsibilities. Each full node maintains a complete, identical copy of the distributed ledger. This ensures that if any subset of nodes fails or is compromised, the network continues to function without data loss.
  2. Distributed Consensus Mechanisms: In the absence of a central coordinator to validate transactions, blockchain uses consensus algorithms (such as Proof of Stake or Practical Byzantine Fault Tolerance). These algorithms allow mutually distrusting nodes to agree on a single, truthful state of the ledger. For example, in PoS, validators are chosen to propose and attest to blocks based on their economic stake, ensuring that the network reaches agreement securely without a central authority.
  3. Cryptographic Identity and Verification: Decentralized systems replace central identity management (like a central KYC database) with cryptographic proofs. Users control their assets and identities via public-private key pairs. Transactions are authenticated mathematically via digital signatures, ensuring that only the rightful owner can authorize actions, eliminating the need for a central gatekeeper.
  4. Smart Contracts and Autonomous Execution: Decentralization extends beyond data storage to logic execution. Smart contracts are self-executing programs stored on the blockchain that automatically enforce and execute business logic when predefined conditions are met. Because they run on the decentralized EVM (Ethereum Virtual Machine) across all nodes, the execution is deterministic, transparent, and immune to central censorship or downtime.

Diagram
Figure: Sequence diagram illustrating decentralized transaction validation and consensus without a central server.

Module III Consensus Algorithms and Bitcoin

Q15 (a) Explain consensus mechanisms used in blockchain. List out any six consensus algorithms used in the context of blockchain. (b) Describe crash fault tolerant algorithms. Compare PoW and PoS 14 m
(a) Explain consensus mechanisms used in blockchain. List out any six consensus algorithms used in the context of blockchain. (7 marks)

Mark distribution: Consensus mechanisms explanation – 4 marks, listing of 6 types – 3 marks

Consensus Mechanisms in Blockchain:

Consensus is the process by which a distributed network of nodes agrees on a single data value or a single state of the network, despite the presence of faulty or malicious nodes. In blockchain, consensus mechanisms are protocols that ensure all participating nodes synchronize their copies of the distributed ledger and agree on the validity and ordering of transactions without requiring a central authority.

The primary objectives of consensus mechanisms in blockchain are:

  1. Agreement: All honest nodes must agree on the same set of valid transactions and the same block to be added to the chain.
  2. Fault Tolerance: The system must continue to function correctly even if some nodes fail, go offline, or act maliciously (Byzantine faults).
  3. Decentralization: No single entity should have the power to dictate which transactions are valid or which blocks are appended.
  4. Security: The mechanism must resist Sybil attacks, double-spending, and other forms of manipulation.
  5. Liveness: The protocol must guarantee that new blocks continue to be produced and the network does not stall.

How Consensus Works in Blockchain:

In a traditional centralized system, a single server validates transactions and maintains the ledger. In a decentralized blockchain, thousands of nodes must independently validate transactions and agree on the order in which they are recorded. Consensus mechanisms provide the rules and incentives that allow this agreement to emerge organically.

Diagram

Figure: Consensus mechanism workflow in blockchain networks

Types of Consensus Mechanisms:

Consensus algorithms can be broadly classified into two categories:

  • Crash Fault Tolerance (CFT): Assumes nodes may fail by crashing but are not malicious. Examples: Paxos, Raft.
  • Byzantine Fault Tolerance (BFT): Assumes nodes may behave arbitrarily, including acting maliciously. Examples: PBFT, PoW, PoS.

Six Consensus Algorithms Used in Blockchain:

# Algorithm Type Description
1 Proof of Work (PoW) BFT Miners compete to solve a computationally difficult puzzle (finding a nonce that produces a hash below a target). The first to solve it proposes the block. Used by Bitcoin. Security relies on the assumption that honest miners control majority of computational power.
2 Proof of Stake (PoS) BFT Validators are selected to propose blocks based on the amount of cryptocurrency they "stake" as collateral. Validators with larger stakes have higher probability of being selected. Malicious behavior results in "slashing" (loss of stake). Used by Ethereum (post-Merge).
3 Practical Byzantine Fault Tolerance (PBFT) BFT A voting-based protocol where nodes exchange messages in multiple rounds (Pre-prepare, Prepare, Commit) to reach agreement. Tolerates up to f faulty nodes in a system of 3f+1 nodes. Used in Hyperledger Fabric.
4 Paxos CFT A classic consensus algorithm for crash-fault-tolerant systems. Uses proposers, acceptors, and learners in a two-phase commit protocol. Not inherently Byzantine fault tolerant but used in permissioned blockchain settings.
5 Raft CFT A simplified alternative to Paxos designed for understandability. Uses a leader-based approach where one node is elected as leader and manages log replication. Used in permissioned blockchains like Quorum.
6 Delegated Proof of Stake (DPoS) BFT Token holders vote for a small number of "witnesses" or "delegates" who are responsible for producing blocks. Combines democratic voting with efficient block production. Used by EOS, Tron, and Steem.

Other notable algorithms include Proof of Authority (PoA), Proof of Elapsed Time (PoET), and Tendermint BFT, each optimized for specific use cases such as enterprise blockchain, IoT, or high-throughput applications.


(b) Describe crash fault tolerant algorithms. Compare PoW and PoS (7 marks)

Mark distribution: Crash fault tolerance algorithms – 3 marks, comparison – 4 marks

Crash Fault Tolerant (CFT) Algorithms:

Crash Fault Tolerant algorithms are designed for distributed systems where nodes may fail by crashing (stopping operation unexpectedly) but are assumed to be honest — they do not behave maliciously, send conflicting messages, or lie about data. CFT algorithms guarantee consensus as long as a majority of nodes remain operational.

Key Assumptions of CFT:

  • Nodes may crash and stop responding, but when they recover, they resume correctly.
  • Nodes do not act maliciously or send incorrect/conflicting data.
  • The system can tolerate up to f failures in a system of 2f + 1 nodes (majority quorum).

Paxos Algorithm:

Paxos, introduced by Leslie Lamport, is a foundational CFT consensus algorithm. It involves three roles:

  1. Proposers: Nodes that propose values to be agreed upon.
  2. Acceptors: Nodes that receive proposals and vote on them.
  3. Learners: Nodes that learn the decided value.

Paxos operates in two phases:

  • Phase 1 (Prepare): A proposer sends a PREPARE request with a proposal number. Acceptors respond with a PROMISE if they haven't already promised a higher-numbered proposal.
  • Phase 2 (Accept): If the proposer receives promises from a majority, it sends an ACCEPT request. Acceptors respond with ACCEPTED if they haven't promised a higher number.

Diagram

Figure: Paxos two-phase consensus protocol

Raft Algorithm:

Raft is a CFT algorithm designed as a more understandable alternative to Paxos. It decomposes consensus into three sub-problems: Leader Election, Log Replication, and Safety.

  • Leader Election: Nodes operate as either Leaders or Followers. Followers elect a leader through randomized timeouts. If a follower doesn't hear from the leader, it becomes a Candidate and requests votes.
  • Log Replication: The leader receives client requests, appends them to its log, and replicates entries to followers. An entry is committed when a majority of nodes acknowledge it.
  • Safety: Ensures that once a log entry is committed, no future leader can have a different entry at the same index.

Comparison: Proof of Work (PoW) vs Proof of Stake (PoS)

Feature Proof of Work (PoW) Proof of Stake (PoS)
Block Selection Miners compete to solve a computational puzzle (hash below target). First to solve proposes the block. Validators are selected pseudo-randomly based on the size of their stake (coins locked as collateral).
Resource Requirement Requires significant computational power (hashing hardware like ASICs) and electricity. Requires staking cryptocurrency; minimal computational resources needed.
Energy Consumption Extremely high. Bitcoin consumes more energy than some countries (~150 TWh/year). Very low. No intensive computation required; Ethereum's energy usage dropped ~99.95% after The Merge.
Security Model Security relies on honest miners controlling >50% of total hash rate. Attackers need massive hardware investment. Security relies on validators having majority of staked tokens. Attackers need to acquire majority of staked coins.
Attack Penalty No direct penalty for failed attacks; attacker wastes electricity and hardware costs. Slashing mechanism: Validators who act maliciously (e.g., double-signing) lose part or all of their staked coins.
Centralization Risk Mining pools can concentrate hash power, leading to centralization (e.g., top 3 pools control >50% of Bitcoin). Wealth concentration risk: large stakeholders have proportionally more influence. Mitigated by delegation mechanisms.
Finality Probabilistic finality — blocks become more secure as more blocks are added on top (typically 6 confirmations for Bitcoin). Can achieve deterministic finality through checkpointing and slashing conditions (e.g., Ethereum's Casper FFG).
Examples Bitcoin, Litecoin, Dogecoin, Bitcoin Cash Ethereum (post-Merge 2022), Cardano, Polkadot, Solana
Q16 (a) Explain the different types of scripts used for transaction validation. (b) Explain the life cycle of a transaction. 14 m
(a) Explain the different types of scripts used for transaction validation. (7 marks)

Mark distribution: Transaction validation – 2 marks, explanation with Script – 5 marks

Transaction Validation in Bitcoin:

Transaction validation is the process by which nodes in the Bitcoin network verify that a transaction is legitimate before including it in a block. Every full node independently validates each transaction against a set of consensus rules. If any rule is violated, the transaction is rejected.

Key Validation Checks:

  1. Syntax Check: Transaction structure must be well-formed (correct fields, proper encoding).
  2. Input Validation: Each input must reference a valid, unspent transaction output (UTXO). The UTXO must not have been spent already (no double-spending).
  3. Script Validation: The locking script (scriptPubKey) from the referenced UTXO and the unlocking script (scriptSig) from the input must execute together and evaluate to TRUE.
  4. Value Check: The sum of input values must be greater than or equal to the sum of output values (difference is the transaction fee).
  5. Signature Verification: Digital signatures must be cryptographically valid, proving the spender owns the private key corresponding to the address.

Diagram

Figure: Transaction validation flow in Bitcoin network

Bitcoin Script:

Bitcoin uses a simple, stack-based scripting language called Script. It is intentionally limited (not Turing-complete) to prevent infinite loops and ensure deterministic validation. Script operates on a Last-In-First-Out (LIFO) stack and consists of opcodes (operations) and data values.

Types of Scripts Used in Bitcoin:

1. Pay-to-Public-Key-Hash (P2PKH) — Legacy:

This is the original and most common transaction type. The locking script requires the spender to provide a public key and a digital signature that match the hash of the public key (the Bitcoin address).

  • scriptPubKey (Locking): OP_DUP OP_HASH160 <PubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
  • scriptSig (Unlocking): <Signature> <PubKey>

Execution:

  1. Push <Signature> and <PubKey> onto the stack.
  2. OP_DUP: Duplicates the top item (<PubKey>).
  3. OP_HASH160: Hashes the top item to get <PubKeyHash_computed>.
  4. Push <PubKeyHash> (from the locking script) onto the stack.
  5. OP_EQUALVERIFY: Compares top two items. If not equal, fail.
  6. OP_CHECKSIG: Uses <PubKey> to verify <Signature>. Returns TRUE or FALSE.

2. Pay-to-Script-Hash (P2SH) — Multisig and Complex Scripts:

P2SH allows the spender to provide the actual redeem script at spend time, rather than embedding it in the output. The output only contains the hash of the redeem script. This is commonly used for multi-signature wallets.

  • scriptPubKey (Locking): OP_HASH160 <ScriptHash> OP_EQUAL
  • scriptSig (Unlocking): <Sig1> <Sig2> ... <RedeemScript>

The redeem script itself contains the actual validation logic (e.g., OP_2 <PubKey1> <PubKey2> <PubKey3> OP_3 OP_CHECKMULTISIG for a 2-of-3 multisig).

3. Pay-to-Witness-Public-Key-Hash (P2WPKH) — SegWit:

Introduced with Segregated Witness (SegWit), P2WPKH separates the signature data (witness) from the main transaction. This reduces transaction size and fixes transaction malleability.

  • scriptPubKey (Locking): OP_0 <PubKeyHash> (version 0 witness program)
  • Witness data: <Signature> <PubKey>

The validation logic is similar to P2PKH but executed in the witness program rather than the script engine.

4. Pay-to-Witness-Script-Hash (P2WSH) — SegWit Multisig:

The SegWit equivalent of P2SH. The witness contains the redeem script and signatures.

  • scriptPubKey (Locking): OP_0 <ScriptHash>
  • Witness data: <Sig1> <Sig2> ... <RedeemScript>

5. Taproot (P2TR) — SegWit v1:

Introduced in the 2021 Taproot upgrade, P2TR uses Schnorr signatures and Merkle trees to enable complex spending conditions while appearing as a simple single-key spend on-chain, improving privacy and efficiency.

  • scriptPubKey (Locking): OP_1 <32-byte-x-only-pubkey> (version 1 witness program)
  • Supports both key path spending (single signature) and script path spending (complex conditions via Merkle tree of scripts).
Script Type Abbreviation Key Feature Use Case
P2PKH Legacy Direct public key hash Simple single-signature payments
P2SH Multisig Hash of redeem script Multi-sig wallets, complex conditions
P2WPKH SegWit v0 Witness-based PKH Standard transactions (lower fees)
P2WSH SegWit v0 Witness-based SH Multisig with lower fees
P2TR Taproot Schnorr + Merkle trees Privacy-preserving complex scripts

(b) Explain the life cycle of a transaction. (7 marks)

Mark distribution: Life cycle with explanation – 7 marks

Life Cycle of a Bitcoin Transaction:

A Bitcoin transaction goes through several distinct stages from creation to final confirmation on the blockchain. Understanding this lifecycle is essential for comprehending how value moves across the Bitcoin network.

Diagram

Figure: Complete lifecycle of a Bitcoin transaction from creation to confirmation

Detailed Explanation of Each Stage:

Stage 1: Transaction Creation

The lifecycle begins when a user (sender) decides to send Bitcoin to a recipient. Using a wallet application, the user specifies:

  • Recipient's Bitcoin address (destination)
  • Amount to send (in BTC)
  • Transaction fee (incentive for miners)

The wallet automatically selects appropriate Unspent Transaction Outputs (UTXOs) from the sender's previous incoming transactions to cover the amount plus fees. If the selected UTXOs exceed the required amount, the wallet creates a change output that returns the excess back to the sender's address.

Stage 2: Transaction Signing

The wallet constructs the raw transaction containing:

  • Inputs: References to UTXOs being spent (transaction ID + output index)
  • Outputs: Recipient address with amount, and change address with remainder
  • scriptSig: Unlocking script containing the sender's digital signature and public key

The sender's private key is used to create a cryptographic signature over the transaction data. This signature proves ownership of the funds without revealing the private key. The signed transaction is now ready for broadcast.

Stage 3: Broadcast to Network

The signed transaction is broadcast to the Bitcoin peer-to-peer network. The sender's wallet sends it to one or more connected full nodes, which then propagate it to their peers. Within seconds, the transaction reaches thousands of nodes across the global network through a gossip protocol.

Stage 4: Validation by Nodes

Each full node that receives the transaction independently validates it against all consensus rules:

  • Verify the transaction format and structure
  • Check that all referenced UTXOs exist and are unspent
  • Verify that the sum of inputs ≥ sum of outputs (fee ≥ 0)
  • Execute the combined script (scriptSig + scriptPubKey) to verify the digital signature
  • Ensure no double-spending (UTXO not already spent by another transaction in the mempool)

If any check fails, the transaction is rejected and not forwarded. If all checks pass, the transaction is considered valid.

Stage 5: Mempool (Memory Pool)

Valid transactions are placed in the node's mempool — a holding area for unconfirmed transactions waiting to be included in a block. The mempool can contain thousands of transactions. Miners typically prioritize transactions with higher fee rates (satoshis per byte) to maximize their mining revenue.

Stage 6: Mining (Transaction Selection)

A miner selects transactions from their mempool to include in a new candidate block. Selection is typically based on:

  • Fee rate: Higher fees per byte are prioritized
  • Block size limit: Total transaction data must fit within the block size limit (~1 MB base, up to ~4 MB with SegWit)
  • Dependency ordering: If transaction B spends an output from transaction A, A must be included first

Stage 7: Block Formation

The miner constructs a candidate block containing:

  • Block header: Previous block hash, Merkle root of transactions, timestamp, difficulty target, nonce
  • Coinbase transaction: Special first transaction that creates new bitcoins as the block reward
  • Selected transactions: From the mempool

The miner then attempts to find a valid nonce such that the block header's SHA-256 hash is below the current difficulty target (Proof of Work).

Stage 8: Block Broadcast

Once a miner successfully finds a valid nonce, the completed block is broadcast to the network. All connected nodes receive the new block.

Stage 9: Block Verification

Each node independently verifies the block:

  • Validate the block header (hash below target, correct previous hash reference)
  • Verify every transaction in the block (same checks as Stage 4)
  • Ensure the coinbase transaction has the correct block reward
  • Verify the Merkle root matches the transactions

Stage 10: Confirmation (1st Confirmation)

If the block passes all verification, nodes add it to their local copy of the blockchain. The transactions within the block now have 1 confirmation. The UTXOs referenced by these transactions are marked as spent, and new UTXOs are created for the outputs.

Stage 11: Additional Confirmations

As subsequent miners build new blocks on top of the confirmed block, each new block adds another confirmation to the transaction. The Bitcoin community generally considers:

  • 1 confirmation: Sufficient for small, low-value transactions
  • 6 confirmations: Standard for most transactions (probability of reversal becomes negligible)
  • Higher confirmations: Used for very large transactions or exchanges

With each additional confirmation, the transaction becomes exponentially more difficult to reverse, as an attacker would need to redo the Proof of Work for the confirmed block and all subsequent blocks — a computationally infeasible task assuming honest miners control the majority of hash power.

Module IV Smart Contracts and Use Cases

Q17 (a) Explain how blockchain technology can impact the health care sector? (b) Explain the Use cases of Blockchain technology in Finance. 14 m
(a) Explain how blockchain technology can impact the health care sector? (7 marks)

Mark distribution: Explanation – 7 marks

The healthcare sector traditionally struggles with fragmented data silos, lack of interoperability between institutions, vulnerable centralized databases, and high administrative costs. Blockchain technology introduces a decentralized, immutable, and cryptographically secure ledger that can fundamentally transform healthcare delivery, data management, and supply chain logistics.

Key Impacts of Blockchain in Healthcare:

  1. Unified Electronic Health Records (EHR) and Interoperability:
    Currently, patient records are scattered across various hospitals and clinics, making it difficult to maintain a comprehensive medical history. Blockchain enables the creation of a Single Source of Truth for patient data. Patients hold the private keys to their records, granting them Self-Sovereign Identity. They can grant temporary, granular access to doctors, specialists, or researchers via smart contracts, ensuring seamless interoperability while maintaining strict privacy and compliance with regulations like HIPAA.

  2. Drug Supply Chain and Provenance:
    The pharmaceutical supply chain is highly vulnerable to counterfeit drugs, which pose severe health risks and financial losses. By recording every step of a drug's journey—from manufacturing to distribution to the pharmacy—on a blockchain, stakeholders can achieve end-to-end traceability and provenance. If a batch of vaccines or medications is compromised, it can be instantly identified and recalled, ensuring patient safety.

  3. Clinical Trials and Medical Research:
    Clinical trial data is often subject to selective reporting or manipulation to achieve desired outcomes. Blockchain provides an immutable audit trail for clinical trials. Every data point, protocol change, and result is timestamped and cryptographically secured before the trial begins. This ensures transparency, prevents data tampering, and increases the credibility and reproducibility of medical research.

  4. Automated Claims and Billing Processing:
    Medical billing is notoriously complex, involving multiple intermediaries (providers, insurers, clearinghouses), leading to delays and high administrative overhead. Smart contracts can automate the claims process. When a medical procedure is verified on the blockchain, the smart contract automatically checks the patient's insurance policy and executes the payment instantly, drastically reducing fraud, denials, and processing time.

  5. Credentialing and Identity Management:
    Verifying the credentials of doctors, nurses, and medical staff is a slow, manual process. A blockchain-based credentialing system allows medical professionals to store their verified degrees, licenses, and certifications on the ledger. Hospitals can instantly verify a practitioner's qualifications without contacting multiple issuing authorities, streamlining the onboarding process.

Diagram
Figure: Blockchain-based healthcare ecosystem enabling secure data sharing and automated processes.

(b) Explain the Use cases of Blockchain technology in Finance. (7 marks)

Mark distribution: Explanation with use case – 7 marks

The traditional financial system relies heavily on centralized intermediaries (banks, clearinghouses, brokers), which results in slow transaction times, high fees, lack of transparency, and counterparty risks. Blockchain technology disrupts this paradigm by enabling peer-to-peer value transfer, programmable money via smart contracts, and transparent ledgers.

Major Use Cases of Blockchain in Finance:

  1. Cross-Border Payments and Remittances:
    Traditional international wire transfers rely on the SWIFT network and correspondent banks, taking 3-5 days and incurring high fees. Blockchain enables real-time, cross-border settlements by bypassing intermediaries. Networks like Ripple (XRP) or Stellar allow financial institutions to transfer value globally in seconds with fractional transaction costs, providing immense benefits to migrant workers sending remittances.

  2. Trade Finance and Supply Chain Finance:
    International trade involves massive paperwork, including Letters of Credit, Bills of Lading, and invoices, leading to delays and fraud risks. Blockchain digitizes these documents onto a shared, immutable ledger. Smart contracts can automate payments; for example, once a shipping container's GPS data (fed via an IoT oracle) confirms arrival at the destination port, the smart contract automatically releases funds to the supplier, eliminating manual verification and reducing settlement times from weeks to hours.

  3. Asset Tokenization and Digital Securities:
    Blockchain allows real-world assets (RWA) such as real estate, fine art, or private equity to be represented as digital tokens on a blockchain. This process, known as tokenization, enables fractional ownership, allowing retail investors to buy small shares of high-value assets. It also introduces 24/7 trading, instant settlement, and increased liquidity to traditionally illiquid markets.

  4. Decentralized Finance (DeFi):
    DeFi recreates traditional financial services (lending, borrowing, trading, yield farming) using smart contracts on public blockchains like Ethereum, entirely without centralized intermediaries. Users can lend their crypto assets to liquidity pools and earn interest, or borrow assets by providing collateral, all governed by transparent, auditable code rather than bank policies.

  5. KYC and AML Compliance:
    Know Your Customer (KYC) and Anti-Money Laundering (AML) processes are duplicated across every financial institution a customer interacts with, costing banks billions annually. A blockchain-based shared KYC registry allows a customer to undergo verification once. The cryptographic proof of verification is stored on the ledger, and other banks can instantly verify the customer's identity with the user's consent, reducing redundancy and improving regulatory compliance.

Diagram
Figure: Cross-border payment flow utilizing blockchain and smart contracts for instant settlement.

Q18 (a) How can Blockchain technology be integrated with artificial intelligence. (b) How can the architecture of BaaS be designed to suite for a decentralised organisation? 14 m
(a) How can Blockchain technology be integrated with artificial intelligence. (7 marks)

Mark distribution: Explanation of AI and blockchain - 4 marks, Integration mechanisms - 3 marks

Explanation of AI and Blockchain (4 marks):
Artificial Intelligence (AI) and Blockchain are two of the most transformative technologies of the modern era, and their integration creates a powerful synergy that addresses the inherent limitations of each.
AI focuses on data processing, pattern recognition, predictive analytics, and automation. However, AI models require massive amounts of data and compute power, often leading to centralized data silos, privacy concerns, and a "black box" nature where the decision-making process is opaque. Furthermore, centralized AI systems are vulnerable to single points of failure and data manipulation.
Blockchain, conversely, is a decentralized, immutable, and transparent ledger. It excels at establishing trust, securing data, and enabling peer-to-peer coordination without a central authority. However, blockchain lacks inherent intelligence and struggles with processing large-scale complex computations efficiently.
By integrating the two, Blockchain provides the trust, security, and decentralized infrastructure that AI needs, while AI provides the intelligence, optimization, and analytical capabilities that blockchain networks require to scale and function efficiently.

Integration Mechanisms (3 marks):

  1. Decentralized Data Marketplaces for AI Training:
    AI models are only as good as the data they are trained on. Blockchain can facilitate decentralized data marketplaces where individuals or organizations can securely share data for AI training. The blockchain tracks data provenance, ensuring that data contributors are fairly compensated via smart contracts and that the data used has not been tampered with, thereby solving the data scarcity and bias problems in AI.

  2. Federated Learning on Blockchain:
    Federated learning allows AI models to be trained across multiple decentralized devices holding local data samples, without exchanging the raw data itself. Blockchain can be used to coordinate this process, securely recording and verifying the model updates (gradients) submitted by each node. This ensures that malicious nodes cannot poison the global model, maintaining the integrity of the AI while strictly preserving user data privacy.

  3. Decentralized Compute Networks:
    Training advanced AI models requires immense GPU power, currently dominated by a few centralized tech giants. Blockchain enables decentralized compute networks where individuals can rent out their idle GPU resources to AI developers. The blockchain handles the verification of compute work and the distribution of token-based payments, creating a distributed, cost-effective supercomputer for AI training.

  4. AI for Smart Contract Auditing and Optimization:
    Conversely, AI can be applied to blockchain operations. AI-driven tools can analyze complex smart contract code to detect vulnerabilities, logical flaws, and gas inefficiencies before deployment. Furthermore, AI can optimize blockchain routing and consensus mechanisms by predicting network congestion and dynamically adjusting parameters.

Diagram
Figure: Integration of AI and Blockchain enabling secure data sharing and decentralized compute for model training.

(b) How can the architecture of BaaS be designed to suite for a decentralised organisation? (7 marks)

Mark distribution: BaaS - 3 marks, architecture diagram - 4 marks

Blockchain as a Service (BaaS) Definition (3 marks):
Blockchain as a Service (BaaS) is a cloud-based, fully managed service model where third-party providers (such as AWS Managed Blockchain, Azure Blockchain Workbench, or IBM Blockchain Platform) offer blockchain infrastructure, node management, and smart contract deployment capabilities.
BaaS abstracts the underlying complexity of setting up and maintaining blockchain networks. Organizations do not need to provision physical servers, configure peer-to-peer networking, manage consensus algorithms, or handle routine security patches. Instead, they can focus entirely on developing their decentralized applications (DApps), business logic, and user interfaces. BaaS provides a scalable, secure, and cost-effective entry point for enterprises looking to leverage distributed ledger technology without the heavy operational overhead.

Architecture of BaaS for a Decentralized Organization (DAO) (4 marks):
A Decentralized Autonomous Organization (DAO) requires a robust, multi-layered architecture to handle decentralized governance, tokenomics, secure voting, and treasury management. When built on a BaaS platform, the architecture is typically divided into four distinct layers:

  1. Infrastructure Layer (Managed by BaaS):
    This is the foundational layer provided by the BaaS vendor. It includes the managed blockchain nodes, the consensus engine (e.g., Proof of Stake or PBFT), peer-to-peer networking, and cryptographic security. The BaaS provider ensures high availability, scalability, and fault tolerance of the underlying ledger.

  2. Smart Contract Layer (Core DAO Logic):
    Deployed on top of the infrastructure, this layer contains the immutable business logic of the DAO. It includes Governance Tokens (representing voting power), Voting Mechanisms (smart contracts that tally votes and execute decisions), and Treasury Management (multi-signature wallets that hold the DAO's funds). This layer ensures that all organizational rules are enforced automatically and transparently.

  3. Middleware and Off-Chain Storage Layer:
    Blockchains are not designed to store large amounts of data efficiently. This layer bridges the on-chain and off-chain worlds. It utilizes Decentralized Storage (like IPFS or Filecoin) to store heavy documents, such as detailed governance proposals or DAO manifestos, storing only the cryptographic hash on-chain. It also includes Oracles to fetch external data (e.g., token prices for treasury valuation) and Web3 APIs (like Infura or Alchemy) to allow the frontend to communicate seamlessly with the blockchain nodes.

  4. Application and User Interface Layer:
    This is the front-end layer where DAO members interact with the organization. It includes Governance Dashboards for viewing proposals and voting, Wallet Integrations (like MetaMask or WalletConnect) for secure authentication and transaction signing, and community forums. The UI reads data from the middleware and sends user intents to the smart contracts.

Diagram
Figure: Four-layer BaaS architecture designed to support a Decentralized Autonomous Organization (DAO).

Module V Ethereum and Solidity

Q19 (a) What are addresses in Ethereum? List and explain the different addresses used in Ethereum. (b) Explain the concept of 'functions' in Solidity. How errors are being handled in Solidity? 14 m
(a) What are addresses in Ethereum? List and explain the different addresses used in Ethereum. (7 marks)

Mark distribution: addresses - 3 marks, list and explanation of addresses - 4 marks

In Ethereum, an address is a unique 20-byte (160-bit) identifier used to represent an account on the blockchain. It is typically represented as a 40-character hexadecimal string, often prefixed with 0x. Addresses serve as the destination or source of transactions and are fundamental to the Ethereum ecosystem for routing funds and invoking smart contracts. Since Ethereum transitioned to Proof of Stake in September 2022, these addresses are associated with validator accounts and user wallets rather than mining operations.

Addresses are derived from the public key using the Keccak-256 hash function, taking the last 20 bytes of the hash.

Diagram
Figure: Derivation of an Ethereum address from a private key.

Types of Accounts/Addresses in Ethereum:
Ethereum utilizes two primary types of accounts, each with its own address type:

  1. Externally Owned Accounts (EOA):

    • Controlled by: A private key (managed by a user via a wallet).
    • Characteristics: Can initiate transactions, send Ether, and interact with smart contracts. They do not contain code.
    • Address Generation: Derived directly from the public key of the user.
    • Use Case: Standard user wallets (e.g., MetaMask) used to send/receive ETH and sign transactions.
  2. Contract Accounts (Smart Contracts):

    • Controlled by: The smart contract code deployed on the blockchain.
    • Characteristics: Contains executable bytecode. Cannot initiate transactions on their own; they can only respond to incoming transactions (messages) from EOAs or other contracts. They have an Ether balance and can store data.
    • Address Generation: Deterministic. It is derived from the address of the creator (EOA) and the nonce (number of transactions sent by the creator) using the Keccak-256 hash.
    • Use Case: Decentralized applications (DApps), token contracts (ERC-20), and automated business logic.

Diagram
Figure: Classification of Ethereum accounts and their associated addresses.

(b) Explain the concept of 'functions' in Solidity. How errors are being handled in Solidity? (7 marks)

Mark distribution: functions - 3 marks, error handling - 4 marks

In Solidity, functions are the executable units of code within a contract. They define the behavior and logic of the smart contract, allowing it to read/write state variables, process inputs, and interact with other contracts. Functions can be called internally (within the same contract) or externally (by other contracts or EOAs).

Key Function Concepts:

  • Visibility: Defines where the function can be called from (public, private, internal, external).
  • State Mutability: Defines how the function interacts with the blockchain state (view, pure, payable).
  • Modifiers: Custom logic applied before/after function execution (e.g., onlyOwner).

Diagram
Figure: Components and attributes of a Solidity function.

Error Handling in Solidity:
Solidity uses a robust error-handling mechanism to ensure that invalid states are caught and the transaction is reverted, preventing unintended state changes. When an error occurs, the EVM reverts all state changes made during the transaction and refunds the remaining gas to the caller.

The primary error-handling statements are:

  1. require():

    • Purpose: Used to validate inputs, conditions, and return values from external calls before or during execution.
    • Behavior: If the condition evaluates to false, it throws an exception and reverts the transaction. It is typically used at the beginning of a function.
    • Example: require(balance >= amount, "Insufficient balance");
  2. revert():

    • Purpose: Used to explicitly abort execution and revert state changes. It can be used anywhere in the function.
    • Behavior: Halts execution and reverts the transaction. Often used in complex conditional logic where require is less readable.
    • Example: if (block.timestamp < deadline) revert("Auction not ended");
  3. assert():

    • Purpose: Used to check for internal errors and invariants that should never be false. It tests for bugs in the code.
    • Behavior: If the condition is false, it causes a Panic error (e.g., division by zero, array out of bounds) and consumes all remaining gas (prior to Solidity 0.8.0).
    • Example: assert(newBalance > oldBalance);

Diagram
Figure: Flow of error handling and transaction reversion in Solidity.

Q20 (a) Explain data types in the Solidity language with proper examples in detail. (b) Using Solidity language, create a simple bank contract that allows a user to deposit, withdraw and view balance. 14 m
(a) Explain data types in the Solidity language with proper examples in detail. (7 marks)

Mark distribution: data types - 2 marks Explanation - 5 marks

Solidity is a statically typed language, meaning the type of every variable must be specified at compile time. Data types define the kind of value a variable can hold, the operations that can be performed on it, and the amount of memory/storage it consumes. Proper use of data types is crucial for gas optimization and preventing vulnerabilities in smart contracts.

Solidity data types are broadly categorized into Value Types (stored directly on the stack) and Reference Types (store a reference to the memory location).

1. Value Types:
These types are passed by value, meaning a copy is made when assigned or passed as arguments.

  • Booleans (bool): Represents true or false.
    • Example: bool public isActive = true;
  • Integers (int / uint): Signed (int) and unsigned (uint) integers. uint8 to uint256 (in steps of 8). uint is an alias for uint256.
    • Example: uint256 public totalSupply = 1000000;
  • Addresses (address / address payable): Holds a 20-byte Ethereum address. address payable allows sending Ether via .transfer() and .send().
    • Example: address public owner = msg.sender;
  • Fixed-size Byte Arrays (bytes1 to bytes32): Holds 1 to 32 bytes of raw data.
    • Example: bytes32 public hashValue;
  • Enums: User-defined types consisting of a finite set of named constants. Useful for state machines.
    • Example: enum State { Pending, Active, Completed }

2. Reference Types:
These types store a reference to the data location (memory, storage, or calldata) rather than the value itself.

  • Arrays ([]): Can be fixed-size (uint[5]) or dynamic (uint[]). Can hold value or reference types.
    • Example: uint[] public scores;
  • Structs: Custom defined structures that group multiple variables of different types.
    • Example:
      struct User {
          string name;
          uint256 age;
      }
  • Mappings (mapping): Hash tables initialized virtually with all possible keys mapped to a zero-value. Declared as mapping(KeyType => ValueType).
    • Example: mapping(address => uint256) public balances;

3. Special Data Types:

  • Literals: Strings, hex numbers, and rational numbers.
  • Function Types: Variables that hold function pointers.

Diagram
Figure: Classification of data types in the Solidity programming language.

(b) Using Solidity language, create a simple bank contract that allows a user to deposit, withdraw and view balance. (7 marks)

Mark distribution: smart contract solidity code - 5 marks, explanation - 2 marks

Below is the complete, runnable Solidity smart contract for a simple bank. It allows users to deposit Ether, withdraw Ether, and check their balance. It includes proper access control, error handling, and event emissions.

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

contract SimpleBank {
    // Mapping to keep track of each user's balance
    mapping(address => uint256) private balances;

    // Event emitted when a deposit is made
    event Deposit(address indexed user, uint256 amount);

    // Event emitted when a withdrawal is made
    event Withdrawal(address indexed user, uint256 amount);

    // Function to deposit Ether into the bank
    function deposit() public payable {
        require(msg.value > 0, "Deposit amount must be greater than zero");

        // Update the user's balance
        balances[msg.sender] += msg.value;

        // Emit the Deposit event
        emit Deposit(msg.sender, msg.value);
    }

    // Function to withdraw Ether from the bank
    function withdraw(uint256 amount) public {
        // Check if the user has sufficient balance
        require(amount > 0, "Withdrawal amount must be greater than zero");
        require(balances[msg.sender] >= amount, "Insufficient balance");

        // Update the balance before transferring to prevent reentrancy attacks
        balances[msg.sender] -= amount;

        // Transfer the Ether to the user
        payable(msg.sender).transfer(amount);

        // Emit the Withdrawal event
        emit Withdrawal(msg.sender, amount);
    }

    // Function to view the balance of the caller
    function getBalance() public view returns (uint256) {
        return balances[msg.sender];
    }

    // Function to view the total Ether held by the contract
    function getContractBalance() public view returns (uint256) {
        return address(this).balance;
    }
}

Explanation of Logic:

  1. State Variable (balances): A private mapping is used to store the balance of each address. This acts as the bank's ledger. It is marked private to enforce encapsulation, though users can still query it via the getBalance() function.
  2. Events (Deposit, Withdrawal): Events are emitted to log actions on the blockchain. This allows off-chain applications (like a frontend UI) to listen for and react to deposits and withdrawals efficiently.
  3. deposit() Function: Marked as payable, allowing it to receive Ether. The msg.value (amount of Ether sent) is added to the sender's balance. A require statement ensures the deposited amount is greater than zero.
  4. withdraw() Function: Takes an amount parameter. It uses require statements to ensure the amount is positive and that the user has sufficient funds. Crucially, the state variable (balances) is updated before the external call (transfer), which is a standard security practice to mitigate reentrancy attacks.
  5. getBalance() & getContractBalance(): Read-only functions (view) that return the user's specific balance and the total Ether held in the contract, respectively. They do not alter the state and cost no gas when called externally.

Diagram
Figure: Sequence diagram illustrating the flow of deposit and withdrawal operations in the SimpleBank contract.