Sem 7

Past Exam Questions

Every question from the IOE411 Mid Sem October 2025 and End Sem November 2025 papers (batch 2022) and the Mid Sem September 2026 paper (batch 2023), with model answers sized to the marks and links to the lecture notes.

Three papers are covered. Open each answer only after you have tried the question. Links point to the lecture that covers the topic.

PaperPattern
Mid Sem, October 2025 (batch 2022)5 questions × 10 marks = 50
End Sem, November 2025 (batch 2022)Part A 8 × 5 = 40, Part B 4 × 15 = 60
Mid Sem, September 2026 (batch 2023)5 questions × 10 marks = 50

Questions are scenario-based ("a land records department", "a central bank", "a smart city"). Name the concept first, then map each part of the scenario to it. Draw the block structure, the PoW flowchart and the P2PKH stack whenever a question allows a figure.

Mid Sem, October 2025 (batch 2022)Search on YouTube

Dr Panchami V. Answer all questions; each carries 10 marks.

Q1. Land records on a blockchainSearch on YouTube

The National Land Records Department plans a blockchain to store and verify land ownership records. Each transaction (land transfer or sale) is recorded as a block.

(a) Summarize what a block represents in a blockchain-based land record system. (2 marks)

A block is a tamper-evident page of the land ledger. It holds a batch of land transactions (transfer or sale of a parcel: parcel ID, seller, buyer, date, the parties' digital signatures). It also stores the hash of the previous block and its own hash, so it fixes when those transfers happened and links them to the full ownership history of each parcel back to the genesis block.

See L01.

(b) Interpret the key components of a block and show how each contributes to securely storing land transaction data. (3 marks)
ComponentContribution
Previous block hashLinks the block to the one before; any change to an older record breaks the link
Transaction data (signed transfers)The actual land records; signatures prove the seller authorised the transfer
Merkle rootOne hash that commits to all transfers in the block; any edit changes it
TimestampProves when the transfer was recorded, settling disputes about order
NonceValue found by Proof of Work so the hash meets the target; makes rewriting costly
Block hashFingerprint of the whole block; stored in the next block

See L01.

(c) An attacker tries to alter a past land record. Explain with an example how each block makes tampering detectable, making the blockchain immutable. (5 marks)

Example chain:

BlockDataPrevious hashHash
101Plot 45: A sells to B9F2C1Z8F
102Plot 45: B sells to C1Z8F6BQ1
103Plot 77: D sells to E6BQ13H4Q

The attacker edits block 101 so plot 45 goes to himself instead of B.

  1. The changed transaction has a new hash (avalanche effect). The Merkle root of block 101 changes.
  2. The header hash of block 101 changes, say from 1Z8F to 7K2D.
  3. Block 102 still stores 1Z8F as its previous hash. The link breaks, and every node sees the mismatch.
  4. The new hash 7K2D almost certainly does not meet the PoW target, so block 101 is invalid by itself.
  5. To hide the edit, the attacker must re-mine block 101 and then 102, 103 and every later block, faster than the honest network adds new blocks. With honest nodes holding most of the computing power, this is computationally impractical (Bitcoin white paper: the chance of catching up falls exponentially with the number of blocks).
  6. Every node holds its own copy. The tampered copy disagrees with the longest valid chain and is rejected.

So any change to a past record is detected at once and cannot be made to stick: the chain is immutable.

See L01, L02, L04.

Q2. A central bank digital currencySearch on YouTube

The central bank wants all participants to agree on one valid ledger even if some nodes act maliciously.

(a) Apply Bitcoin's consensus mechanism to this situation and identify the algorithm used in Bitcoin. (2 marks)

Bitcoin uses Proof of Work (Nakamoto consensus). Nodes compete to find a nonce so the block hash is below a target; the longest valid chain (most work) is the agreed ledger. Applied to the bank: transactions are broadcast to all nodes, any node can propose a block only after doing the work, and every node independently checks it, so malicious nodes cannot impose a false ledger unless they control most of the computing power.

See L04.

(b) Illustrate the consensus algorithm and explain how it maintains trust and agreement among nodes. (8 marks)

Steps (Bitcoin white paper, Section 5):

  1. New transactions are broadcast to all nodes (flooding).
  2. Each node collects new transactions into a candidate block.
  3. Each node works on a difficult proof-of-work: find nonce N such that BH = Hash(PH : MR : N) starts with the required zeros (hash at most the target).
  4. The node that finds it broadcasts the block to all nodes.
  5. Nodes accept the block only if all transactions are valid (correct signatures) and not already spent.
  6. Nodes show acceptance by mining the next block with the accepted block's hash as the previous hash.
Transactions broadcast -> Collect into candidate block -> Try nonce, hash header
      ^                                                        |
      |                                         hash <= target? -- no --> nonce+1
      |                                                        | yes
Mine next block on its hash <- Nodes validate (txs, PoW) <- Broadcast block

How it maintains trust and agreement:

  • Asymmetry: finding the nonce is hard, checking it takes one hash, so every node verifies every block cheaply.
  • Longest chain rule: if two blocks appear at once, nodes keep both branches and switch to whichever becomes longer. All honest nodes converge on one ledger.
  • Tamper resistance: changing a past block means redoing its work and all later work.
  • Double spending: each transaction is checked against the chain; a second spend of the same funds is rejected.
  • Malicious nodes: voting is one-CPU-one-vote, so creating fake identities (Sybil) gives no power. Attackers need more than half the total hash power.
  • Incentive: the winner earns new coins plus fees, so honest mining pays more than attacking.

For a central bank, a PoS or permissioned variant may save energy, but the agreement logic is the same: independent validation plus a rule that picks one chain.

See L04, L02, L01.

Q3. Alice sends 10 BTC to BobSearch on YouTube

Alice owns 10 bitcoins and broadcasts a transaction T to send them to Bob's wallet address.

(a) Demonstrate how Bob can confirm the transaction was genuinely initiated by Alice and not an imposter. (3 marks)

Through Alice's digital signature (ECDSA):

  1. Alice hashes transaction T and signs the hash with her private key. She includes the signature and her public key in the input (scriptSig).
  2. Bob (and every node) hashes T again and verifies the signature with Alice's public key.
  3. Bob also checks that the HASH160 of that public key equals the address the coins were locked to (P2PKH).

If both checks pass, only the holder of Alice's private key could have created T, and T has not been altered. An imposter does not have the private key and cannot produce a valid signature.

See L05, L01.

(b) Using examples and figures, illustrate the steps by which this transaction is verified, validated and recorded in the Bitcoin network. (7 marks)
  1. Request: Bob sends his address to Alice. Alice's wallet creates T: input = her 10 BTC UTXO, output = 10 BTC locked to Bob's address (minus any fee).
  2. Authenticate: Alice signs T with her private key and attaches her public key.
  3. Broadcast: T floods to all nodes and waits in the transaction pool.
  4. Verify: each node runs scriptSig + scriptPubKey (P2PKH) and checks the signature, checks the input is unspent (no double spend) and that inputs ≥ outputs.
  5. Candidate block: miners put T in a candidate block with other transactions and compute the Merkle root.
  6. Proof of Work: miners search for a nonce until the header hash is at most the target.
  7. Broadcast block: the winner sends the block to all nodes.
  8. Validate block: nodes check the PoW, the previous hash and all transactions.
  9. Record: the block is appended; the winner gets 3.125 BTC plus fees.
  10. Confirm: later blocks bury T; after about 6 confirmations Bob treats it as final.
Alice signs T -> broadcast -> nodes verify -> tx pool -> candidate block
-> PoW -> block broadcast -> nodes validate -> block added -> confirmations

See L01 (how a transaction gets into the blockchain), L04, L05.

Q4. Bitcoin ScriptSearch on YouTube

Alice wants to send 2 BTC to Bob so that only Bob can spend it and it follows network rules. Explain how Bitcoin Script validates the transaction, highlighting the script structure and the stack-based execution model. (10 marks)

Bitcoin Script: a simple, compact, stack-based language processed left to right. It is not Turing complete (no loops), so every script ends quickly.

Structure (P2PKH):

  • Alice's output to Bob carries the locking script (scriptPubKey): OP_DUP OP_HASH160 <Bob_pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG.
  • When Bob spends, he supplies the unlocking script (scriptSig): <Bob_sig> <Bob_pubKey>.
  • Validation runs scriptSig then scriptPubKey on an empty stack:
<sig> <pubKey> OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG

Execution:

StepOperationStack (top first)
1Push <sig>, push <pubKey>pubKey, sig
2OP_DUPpubKey, pubKey, sig
3OP_HASH160pubHash, pubKey, sig
4Push <pubKeyHash>pubKeyHash, pubHash, pubKey, sig
5OP_EQUALVERIFY (fails if different)pubKey, sig
6OP_CHECKSIGTRUE

Why only Bob can spend: step 5 ensures the key supplied hashes to Bob's address; step 6 ensures the signature was made with the matching private key over this transaction. Only Bob has that key.

Network rules: nodes also check that the inputs are unspent and that input value ≥ output value. Alice's own input passes the same script check against her earlier output.

See L05.

Q5. Escrow smart contractSearch on YouTube

Write a simple Solidity smart contract for the above scenario: Alice deposits 1 Ether; Alice or the Arbiter can release the payment to Bob; the Arbiter can refund Alice if there is a dispute. (10 marks)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract Escrow {
    address public alice;           // buyer, deploys the contract
    address payable public bob;     // seller
    address public arbiter;         // trusted third party
    bool public funded;

    constructor(address payable _bob, address _arbiter) {
        alice = msg.sender;
        bob = _bob;
        arbiter = _arbiter;
    }

    // Alice deposits exactly 1 ether
    function deposit() external payable {
        require(msg.sender == alice, "Only Alice can deposit");
        require(!funded, "Already funded");
        require(msg.value == 1 ether, "Deposit must be 1 ether");
        funded = true;
    }

    // Alice or the arbiter releases the payment to Bob
    function release() external {
        require(msg.sender == alice || msg.sender == arbiter, "Not authorised");
        require(funded, "Nothing to release");
        funded = false;                       // update state before transfer
        (bool ok, ) = bob.call{value: address(this).balance}("");
        require(ok, "Transfer failed");
    }

    // Arbiter refunds Alice in a dispute
    function refund() external {
        require(msg.sender == arbiter, "Only arbiter");
        require(funded, "Nothing to refund");
        funded = false;
        (bool ok, ) = payable(alice).call{value: address(this).balance}("");
        require(ok, "Refund failed");
    }

    function balance() external view returns (uint256) {
        return address(this).balance;
    }
}

Explanation:

  • The constructor records Alice (the deployer), Bob and the arbiter.
  • deposit is payable; require checks the caller and that msg.value is 1 ether.
  • release and refund use require for access control. They set funded = false before sending ether, which prevents re-entrancy and double payout.
  • call with value sends the ether; the returned flag is checked.

See L13 (functions, constructors, require), L12 (address payable, data types), L11 (testing on Anvil).

End Sem, November 2025 (batch 2022)Search on YouTube

Dr Panchami V. Part A: 8 questions × 5 marks. Part B: 4 questions × 15 marks.

Part ASearch on YouTube

A1. A smart city project connects traffic sensors, pollution monitors and public utilities to a blockchain. Explain how Ethereum 2.0 can enhance efficiency and support large-scale IoT deployments, mentioning the consensus used. (5 marks)
  • Consensus: Proof of Stake. Validators stake ETH and propose and attest to blocks instead of mining. No hash race, so energy use is far lower than PoW, which suits always-on city infrastructure.
  • Two layers: the execution layer runs smart contracts in the EVM (for example, a contract that records sensor readings or triggers utility payments); the consensus layer (Beacon Chain) gives agreement and finality, so recorded data cannot be reverted.
  • Predictable throughput: blocks every 12-second slot and gas pricing give steady inclusion times and fees for sensor data.
  • Scalability: rollups (Layer 2) batch thousands of IoT readings off-chain and post a compact proof or summary to Layer 1; data sharding increases data capacity.
  • Automation and trust: smart contracts enforce rules (for example, pay a utility when meter data arrives, or flag a pollution threshold) without a central operator; every reading is signed, timestamped and tamper-evident.

See L06.

A2. Explain how Ethereum measures and regulates the cost of smart contract execution, and how this cost model influences transaction cost and time to be added to the blockchain. (5 marks)
  • Gas measures computational work. Every EVM operation has a fixed gas cost (a plain ETH transfer is about 21,000 gas; contract calls cost more).
  • The sender sets a gas limit (STARTGAS) and a gas price (GASPRICE, in Gwei).
  • Fee = gas used × effective gas price. Unused gas is refunded. If execution runs out of gas, all state changes revert but the fee is still paid. This bounds execution and stops infinite loops.
  • Example: 29,010 gas used × 0.882463951 Gwei ≈ 0.0000256 ETH.
  • Effect on cost: complex contracts use more gas and cost more; network demand raises the gas price.
  • Effect on time: each block has a gas limit, so space is limited. Validators pick transactions offering higher prices first. A higher gas price gets faster inclusion; a low price may wait in the pool.

See L06.

A3. A decentralized storage platform plans a burn-based mechanism to prevent spam uploads and ensure resource commitment. Name the consensus algorithm and describe how it gives long-term security and prevents abuse. (5 marks)

Proof of Burn (PoB).

  • A participant proves they burned coins by sending them to a verifiably unspendable address. The burn is recorded on-chain and anyone can check it.
  • The right to upload or to produce blocks is proportional to the amount burned.
  • Spam prevention: each upload costs a real, permanent loss, so mass spam becomes expensive.
  • Resource commitment: burned coins cannot be recovered, so participants are committed long term; an attacker must destroy a large amount of value to gain influence.
  • Efficiency: unlike PoW, it uses no physical resources (CPU, power), only digital ones. It is power efficient.
  • PoB usually burns PoW-mined coins, so its security is anchored in the PoW chain.

See L04.

A4. Discuss the different categories of blockchain wallets. (5 marks)

Wallets store private keys. Two types: hot (online, convenient) and cold (offline, more secure).

CategoryDescriptionExample
DesktopRuns on Windows or Mac OS; some security disadvantagesElectrum, Bitcoin Core
MobileRuns on iOS or Android; easy and simpleMycelium
WebRuns in a browser; keys on a third-party server; not for large amountsCoinbase
HardwareSelf-contained wallet on special-purpose hardwareTrezor Model T, Ledger Nano X
PaperKeys printed for long-term storagePrinted key pair

Desktop, mobile and web are hot; hardware and paper are cold.

See L03, L10 (MetaMask).

A5. In a lightweight blockchain client, explain how transactions are represented and efficiently verified without downloading the entire block data. (5 marks)

Simplified Payment Verification (SPV), Bitcoin white paper Section 8.

  • Transactions in a block are hashed into a Merkle tree; only the Merkle root goes in the 80-byte block header.
  • The light client keeps only the block headers of the longest PoW chain (about 4.2 MB per year).
  • To verify a payment, it asks a full node for the Merkle branch: the sibling hashes on the path from the transaction to the root.
  • It hashes up the branch and checks the result equals the root in the header. This needs only log⁡2n\log_2 n hashes (10 hashes for 1024 transactions).
  • Blocks built on top show the network accepted it.
  • Limitation: it trusts that the longest chain is honest; it can be fooled if an attacker overpowers the network. Alerts from full nodes help.

See L02.

A6. Illustrate how digital signatures are used in a blockchain: how a sender signs a transaction and how a validator verifies it to ensure authenticity and integrity. (5 marks)

Signing (sender):

  1. Hash the transaction data.
  2. Sign (encrypt) the hash with the sender's private key (ECDSA in Bitcoin). This is the signature.
  3. Attach the signature and the public key to the transaction and broadcast it.

Verifying (validator):

  1. Hash the received transaction data.
  2. Verify (decrypt) the signature with the sender's public key to recover the signed hash.
  3. Compare the two hashes. Equal means valid. In Bitcoin, also check the public key hashes to the address (P2PKH OP_CHECKSIG).

Authenticity: only the private-key holder can make a valid signature. Integrity: any change to the data changes the hash and the check fails. Non-repudiation: the sender cannot deny signing.

See L01, L05.

A7. One network supports digital currency transactions; the other enables smart contracts and dApps. Name them and compare their consensus, key features and design. (5 marks)

Bitcoin (digital currency) and Ethereum (smart contracts and dApps).

FeatureBitcoinEthereum
PurposePeer-to-peer electronic cashProgrammable platform
ConsensusProof of Work (miners)Proof of Stake (validators)
Block timeAbout 10 minutes12-second slots
Ledger modelUTXOAccounts and global state
LanguageBitcoin Script: stack-based, not Turing completeEVM bytecode (Solidity): Turing complete, bounded by gas
FeesInputs minus outputsGas used × gas price
StackWallet/exchange on the Bitcoin protocolSmart contracts and end-user applications on the EVM
SupplyFixed 21 million BTCETH, no fixed cap

See L06, L03.

A8. Write a zk-SNARK program proving that a user knows two numbers whose sum equals a public value S, without revealing the numbers. (5 marks)

Zero-knowledge proofs are in the syllabus (Unit 1, base technologies) but not in the theory decks available. This answer uses Circom and snarkjs, the common zk-SNARK toolchain.

Circuit sum.circom:

pragma circom 2.0.0;

template SumCheck() {
    signal input a;     // private
    signal input b;     // private
    signal input S;     // public
    a + b === S;        // constraint: a + b must equal S
}

component main {public [S]} = SumCheck();

Input input.json (known only to the prover): {"a": "3", "b": "4", "S": "7"}.

Workflow (Groth16):

circom sum.circom --r1cs --wasm --sym                     # compile to R1CS + witness generator
snarkjs powersoftau new bn128 12 pot12_0000.ptau
snarkjs powersoftau contribute pot12_0000.ptau pot12_0001.ptau --name="first"
snarkjs powersoftau prepare phase2 pot12_0001.ptau pot12_final.ptau
snarkjs groth16 setup sum.r1cs pot12_final.ptau sum.zkey  # proving key
snarkjs zkey export verificationkey sum.zkey vkey.json    # verification key
node sum_js/generate_witness.js sum_js/sum.wasm input.json witness.wtns
snarkjs groth16 prove sum.zkey witness.wtns proof.json public.json
snarkjs groth16 verify vkey.json public.json proof.json   # prints OK

public.json contains only S = 7. The verifier learns that the prover knows some a and b with a + b = 7, but not their values.

Part BSearch on YouTube

B1. Alice transfers 2 BTC to Bob. Explain how the Bitcoin Script system verifies this transaction, describing the script structure and how stack-based execution ensures only Bob can spend the funds. (15 marks)

Write the Mid Sem Q4 answer above in full, and expand it for 15 marks:

  1. Context (2): Alice signs with her private key, announces her public key, broadcasts; Bitcoin transfers scripts rather than bare signatures. Script is simple, compact, stack-based, left to right, not Turing complete.
  2. Structure (3): output of Alice's transaction holds scriptPubKey OP_DUP OP_HASH160 <Bob_pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG; Bob's later input holds scriptSig <Bob_sig> <Bob_pubKey>. Combined input then output on an empty stack.
  3. Execution table (6): the six steps (push sig and pubKey, DUP, HASH160, push pubKeyHash, EQUALVERIFY, CHECKSIG gives TRUE), with a stack drawing at each step.
  4. Why only Bob (2): hash check binds the key to Bob's address; CHECKSIG proves Bob's private key signed this transaction; an attacker's key fails EQUALVERIFY.
  5. Other checks and recording (2): input unspent, inputs ≥ outputs, Alice's own scriptSig verified against her earlier output, then mined into a block and confirmed.

See L05.

B2. (a) Define zero-knowledge proofs with an example. (b) Describe the types of zk-proofs and which is best for blockchain. (c) List the properties of a zk-proof. (d) Write the algorithm for a zero-knowledge proof based on the Diffie-Hellman assumption. (2 + 3 + 4 + 6 marks)

These topics are not in the theory decks available; answers follow standard definitions.

(a) Definition (2). A zero-knowledge proof lets a prover convince a verifier that a statement is true without revealing anything beyond its truth. Example: Ali Baba's cave. Peggy proves she knows the password to a door inside a ring-shaped cave by coming out of whichever side Victor shouts, many times, without telling him the password. Blockchain example: Zcash proves a shielded transaction is valid without revealing sender, receiver or amount.

(b) Types (3).

TypeDescription
InteractiveSeveral rounds of challenge and response between prover and verifier (for example Schnorr identification)
Non-interactive (NIZK)One message from prover to verifier; often built with the Fiat-Shamir heuristic (hash replaces the verifier's challenge)
zk-SNARKSuccinct non-interactive argument of knowledge: tiny proofs, fast verification; needs a trusted setup
zk-STARKScalable transparent argument: no trusted setup, hash-based, post-quantum, larger proofs
BulletproofsShort proofs with no trusted setup; used for range proofs (Monero)

Best for blockchain: non-interactive proofs, since every node must verify without talking to the prover. zk-SNARKs are the most widely used (Zcash, zk-rollups) because proofs are a few hundred bytes and cheap to verify on-chain; zk-STARKs are preferred when a trusted setup must be avoided.

(c) Properties (4).

  1. Completeness: if the statement is true, an honest prover convinces an honest verifier.
  2. Soundness: if the statement is false, a cheating prover convinces the verifier only with negligible probability.
  3. Zero-knowledge: the verifier learns nothing except that the statement is true (a simulator could produce an indistinguishable transcript).
  4. For SNARKs also: succinctness (small proof, fast verification) and knowledge soundness (the prover really knows a witness).

(d) ZKP under the Diffie-Hellman assumption (6): Chaum-Pedersen protocol. Public: group of prime order q, generators g and h, and u=gxu = g^x, v=hxv = h^x. Prover knows x and proves (g,h,u,v)(g, h, u, v) is a Diffie-Hellman tuple (log⁡gu=log⁡hv\log_g u = \log_h v) without revealing x.

  1. Commit: prover picks random r∈Zqr \in \mathbb{Z}_q and sends a=gra = g^r, b=hrb = h^r.
  2. Challenge: verifier sends random c∈Zqc \in \mathbb{Z}_q.
  3. Response: prover sends z=r+c x mod qz = r + c\,x \bmod q.
  4. Verify: accept if gz=a⋅ucg^z = a \cdot u^c and hz=b⋅vch^z = b \cdot v^c.

Why it works: gz=grgcx=a ucg^z = g^{r} g^{cx} = a\,u^c (completeness). Two accepting answers for different c reveal x (soundness). z is uniformly random because r is, so it leaks nothing about x (zero-knowledge). Security rests on the hardness of discrete log and Diffie-Hellman problems. With c=H(g,h,u,v,a,b)c = H(g, h, u, v, a, b) (Fiat-Shamir), it becomes non-interactive. With h removed, the same steps give the Schnorr proof of knowledge of x.

B3. A healthcare consortium wants to share patient records across hospitals with high throughput, no congestion, and failure isolation. Propose scalable blockchain solutions with mechanisms for scalability, privacy, integrity and cross-hospital transfer, with architecture diagrams. (15 marks)

This is a design question; the course lists scalability issues and blockchain on clouds under Applications. A model design:

1. Platform: permissioned consortium blockchain (for example Hyperledger Fabric). Only member hospitals run nodes, identities come from a membership service (certificates), so no costly PoW is needed.

2. Consensus: crash or Byzantine fault tolerant ordering (Raft or PBFT) run by an ordering service with nodes from several hospitals. Gives fast finality and thousands of transactions per second.

3. Scalability mechanisms

  • Off-chain storage: full records (scans, reports) stay in each hospital's database or IPFS. Only the record hash, pointer and access log go on-chain, so blocks stay small.
  • Channels / sharding: separate channels per region or specialty; each processes its own transactions in parallel.
  • Layer 2 batching: bulk updates (lab results) are batched and committed as one Merkle root.
  • Execute-order-validate pipeline lets endorsing peers run in parallel.

4. Privacy

  • Private data collections: patient data shared only with hospitals that need it; others see only the hash.
  • Encryption of records; access granted by smart contract (chaincode) based on patient consent.
  • Role-based access with certificates; audit trail of every access.
  • Optionally zero-knowledge proofs (for example prove eligibility without revealing diagnosis).

5. Integrity: record hash on-chain, Merkle roots, digital signatures by doctors; any change to the off-chain file breaks the hash match.

6. Failure isolation: each hospital runs its own peers; consensus tolerates crashed or faulty nodes (Raft: f of 2f+1; PBFT: f of 3f+1). A failed hospital only loses its own peers; others keep working and it resyncs from the ledger when back.

7. Cross-hospital transfer: a consent smart contract records the request; the receiving hospital fetches the encrypted file off-chain via an API gateway (HL7 FHIR), verifies its hash against the chain, and decrypts with a key shared under consent.

 Hospital A            Hospital B            Hospital C
 [EHR DB/IPFS]         [EHR DB/IPFS]         [EHR DB/IPFS]
 [Peer + chaincode]    [Peer + chaincode]    [Peer + chaincode]
        \                    |                     /
         \------ Channel / private data -----------/
                         |
               [Ordering service: Raft/PBFT]
                         |
         [Shared ledger: hashes, consent, access log]
   Patient app -> consent contract -> API gateway (FHIR)

Why it performs better: small on-chain data and parallel channels give high throughput and no congestion; permissioned BFT consensus gives fast finality; replication across hospitals gives reliability; off-chain encrypted storage plus on-chain hashes gives privacy and integrity together.

B4. Define a Non-Interactive Argument System. Illustrate the high-level architecture of a SNARK software system and identify the major tools for generating and verifying proofs. (15 marks)

Not in the theory decks available; standard answer.

Definition. A non-interactive argument system for a relation R (statement x, witness w) has three algorithms:

  • Setup(1^λ, C) produces public parameters: a proving key pk and a verification key vk.
  • Prove(pk, x, w) produces a proof π in one message.
  • Verify(vk, x, π) accepts or rejects.

It is an argument (not a proof) because soundness holds only against computationally bounded provers. It must be complete and sound; it is zero-knowledge if π reveals nothing about w. A SNARK (Succinct Non-interactive ARgument of Knowledge) adds: π is very short and verification is fast (polylogarithmic or constant), and the prover must "know" w.

High-level architecture:

Program / statement (high-level language: Circom, ZoKrates, Noir)
          |  compile
Arithmetic circuit over a finite field
          |  flatten
Constraint system (R1CS: A·w ∘ B·w = C·w)
          |  encode
Polynomial form (QAP / PLONK polynomials)
          |  setup (trusted ceremony or universal / transparent)
Proving key  ------------------------  Verification key
     |                                        |
Prover: witness w + pk -> proof π       Verifier: x + π + vk -> accept / reject
                                               (off-chain or as a smart contract)
  1. Front end: write the computation in a circuit language; compile to an arithmetic circuit and constraints.
  2. Witness generation: run the circuit on the private inputs to get all wire values.
  3. Setup: create pk and vk (Groth16 needs a per-circuit trusted setup; PLONK uses a universal one; STARKs are transparent).
  4. Back end prover: produces π using elliptic curve pairings and polynomial commitments.
  5. Verifier: checks π with vk; on Ethereum a generated Solidity verifier contract does this.

Major tools:

ToolRole
CircomCircuit language and compiler (R1CS, WASM witness generator)
snarkjsSetup, proving and verifying (Groth16, PLONK); exports Solidity verifiers
ZoKratesHigh-level language and toolbox for Ethereum SNARKs
libsnarkC++ library (used by early Zcash)
bellmanRust Groth16 library (Zcash)
gnark, arkworks, Halo2Go and Rust proving libraries

See L06 for the EVM side and L11 for deploying a verifier contract locally.

Mid Sem, September 2026 (batch 2023)Search on YouTube

Dr Panchami V and Dr S. Jai Ganesh. Answer all questions; each carries 10 marks. These answers were checked against the student's Blockchain_MidSem_QA.pdf.

Q1. Block structure for a banking applicationSearch on YouTube

(a) Draw and explain the structure of a blockchain block. (5 marks)
            Block j-1                 Block j                       Block j+1
                         +-----------------------------------+
  hash(header j-1) ----> | Header (80 bytes)                 |
                         |  Version | Previous block hash    |
                         |  Merkle root | Timestamp          |
                         |  Target (nBits) | Nonce           | --hash(header j)--> stored in j+1
                         +-----------------------------------+
                         | Body: tx count, Tx0 (coinbase),   |
                         |       Tx1, Tx2, Tx3 ...           |
                         +-----------------------------------+
  • Header (hashed and mined): version; previous block hash (links to the parent, back to the genesis block with previous hash 0); Merkle root of all transactions; timestamp; target (difficulty); nonce varied in PoW.
  • Body: transaction counter and the signed transactions (for the bank: transfers). The first is the coinbase transaction paying the miner.
  • Block hash = SHA-256(SHA-256(header)), written in the slides as BH = Hash(PH : MR : N). It must be at most the target.
  • The simple model from the slides: previous hash, transaction data, nonce, hash.

See L01.

(b) Identify the data structure that organizes transactions in a block and explain how it supports efficient verification of integrity. (2 marks)

A Merkle tree. Transactions are hashed (H0 to H3), pairs are hashed together (H01, H23) until one Merkle root remains in the header. Changing any transaction changes the root, so the root commits to all of them. To prove one transaction is included you need only its Merkle branch, log⁡2n\log_2 n hashes (10 for 1024 transactions). This enables SPV and pruning.

See L01, L02.

(c) An attacker modifies a transaction after the block is added. Using the block structure, explain how the blockchain detects it and keeps integrity. (3 marks)
  1. The changed transaction gets a different hash (avalanche effect), so the recomputed Merkle root no longer matches the header. Nodes detect it at once.
  2. If the attacker also updates the Merkle root, the block hash changes. It fails the PoW target and no longer equals the previous-hash field in block j+1, so the chain breaks.
  3. To hide it, the attacker must re-mine this block and all later ones faster than the honest network. Nodes follow the longest valid chain held by everyone else, so the change is rejected.

See L01, L04.

Q2. Bitcoin consensus flowchartSearch on YouTube

Identify the consensus mechanism in Bitcoin and draw a flowchart of how it validates and adds a new block. (10 marks)

Proof of Work (Nakamoto consensus): miners find a nonce so the double SHA-256 header hash is at most the target. Hard to find, one hash to verify (asymmetry, from Hashcash). The winner gets 3.125 BTC plus fees; nodes follow the longest valid chain.

            [Start]
               |
   New transactions broadcast (flooding)
               |
   Miner verifies signatures, no double spend -> mempool
               |
   Build candidate block: coinbase + txs, Merkle root
               |
   Header: version, prev hash, Merkle root, time, target, nonce = 0
               |
   H = SHA256(SHA256(header)) <------------------+
               |                                  |
        H <= target? --- No ---> nonce = nonce + 1 +
               | Yes
   Broadcast block to all nodes
               |
   Nodes check: PoW valid, prev hash, all txs valid and unspent
               |
         Valid? --- No ---> reject block, keep current chain
               | Yes
   Append block (longest chain); miner rewarded;
   nodes mine next block on its hash  ---> repeat

The six white paper steps: broadcast transactions; collect into a block; find PoW; broadcast the block; accept only if all transactions are valid and unspent; build the next block on its hash.

Why it secures the network: rewriting history requires redoing more work than the honest chain (blocks tampering and double spending); work cost makes Sybil identities useless; difficulty adjustment keeps blocks near 10 minutes. Weaknesses: power consumption and mining monopoly (51% attack), which motivate PoS and PoB.

See L04, L01, L02.

Q3. Difficulty adjustmentSearch on YouTube

A mining pool sees blocks being generated faster than the intended interval.

(a) How often does Bitcoin adjust its mining difficulty, and why is the adjustment needed when computational power changes? (4 marks)
  • Every 2016 blocks. At 10 minutes per block, 2016 × 10 = 20,160 minutes = 14 days (about 2 weeks). Every node recomputes the target from the timestamps of the last 2016 blocks.
  • Rule: new target = old target × (actual time for 2016 blocks / 20,160 minutes). The change is limited to a factor of 4 either way.
  • Why: block time depends on total hash power. When miners join or hardware improves, blocks come too fast; when miners leave, too slow. Without adjustment:
    • coins would be issued faster than planned (halvings every 210,000 blocks would come early);
    • short block times cause more forks and orphaned blocks, wasting work and weakening security;
    • if hash power drops, confirmations become very slow.
  • The white paper: difficulty follows a moving average targeting an average number of blocks per hour; if blocks are too fast, difficulty increases. Here the network will raise the difficulty (lower the target).

See L02.

(b) Given a difficulty-1 target of 2^224 and a current target of 2^212, calculate the current difficulty. (3 marks)Difficulty=difficulty-1 targetcurrent target=22242212=212=4096\text{Difficulty} = \frac{\text{difficulty-1 target}}{\text{current target}} = \frac{2^{224}}{2^{212}} = 2^{12} = 4096

A valid hash is 4096 times harder to find than at difficulty 1. The chance one hash succeeds is 2212/2256=2−442^{212}/2^{256} = 2^{-44}, so about 244≈1.76×10132^{44} \approx 1.76 \times 10^{13} hashes are needed per block.

(c) The average block time in the last period was 8 minutes against an intended 10. Calculate the new target. (3 marks)New target=old target×actual timeexpected time=2212×2016×82016×10=0.8×2212\text{New target} = \text{old target} \times \frac{\text{actual time}}{\text{expected time}} = 2^{212} \times \frac{2016 \times 8}{2016 \times 10} = 0.8 \times 2^{212}

0.8×2212=2214/5≈5.27×10630.8 \times 2^{212} = 2^{214}/5 \approx 5.27 \times 10^{63}.

The target falls by 20% and the difficulty rises by 10/8 = 1.25, to 4096×1.25=51204096 \times 1.25 = 5120. With the same hash power, block time returns to 8×1.25=108 \times 1.25 = 10 minutes. The factor 0.8 is within the ×¼ to ×4 limit.

Q4. Containerizing a Flask appSearch on YouTube

app.py listens on port 5000 and shows "Blockchain Learning Portal".

(a) Write a Dockerfile to create a Docker image for this application. (4 marks)
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt   # requirements.txt contains: flask
COPY app.py .
EXPOSE 5000
CMD ["python", "app.py"]
  • FROM: base image with Python; pin a version tag rather than latest.
  • WORKDIR /app: creates and switches to /app for later instructions.
  • COPY + RUN pip install: install Flask at build time; each instruction is an image layer (dependencies first, so the layer is cached).
  • EXPOSE 5000: documentation only. "Expose command is just for information"; the mapping is done with -p at run time.
  • CMD (exec form): Python runs as PID 1 and receives stop signals directly.
  • The app must listen on all interfaces: app.run(host="0.0.0.0", port=5000).

See L07.

(b) Write the Docker command to build the image named blockchain-app. (2 marks)
docker build -t blockchain-app .

-t tags (names) the image (default tag latest); . is the build context containing the Dockerfile and app.py. Check with docker images.

See L07.

(c) Write the command to run the container so port 5000 in the container is reachable on host port 8080. (2 marks)
docker run -d --name blockchain-container -p 8080:5000 blockchain-app

-p host_port:container_port forwards host 8080 to container 5000; -d runs detached; --name names the container. Open http://localhost:8080.

See L07.

(d) Explain what happens when the container is stopped and then removed. Is the image deleted? Justify. (2 marks)
  • docker stop: the main process gets SIGTERM (then SIGKILL); the container is in the Exited state. It still exists (docker ps -a) and keeps its writable layer, so docker start can restart it. Stopping does not delete data.
  • docker rm: the container and its writable layer are deleted; data written inside it (not in a volume) is lost.
  • The image is not deleted. An image is a read-only template; a container is a runtime instance with a thin writable layer on top. Removing the instance does not touch the template. Delete the image only with docker rmi blockchain-app.

See L07, L08.

Q5. Flask and PostgreSQL containersSearch on YouTube

Container A runs Flask; Container B runs PostgreSQL, which must not be exposed to the host.

(a) Design a Docker network so A reaches B by container name without exposing PostgreSQL's port. Explain the communication. (4 marks)
Host :8080 --(-p 8080:5000)--> [flask-app :5000] ---- user-defined bridge "blockchain-net" ---- [postgres-db :5432]
                                                                    (embedded DNS)            no -p, volume pgdata
  • Create a user-defined bridge network and attach both containers. Publish only Flask (-p 8080:5000). Run PostgreSQL with no -p.
  • On a user-defined bridge, Docker's embedded DNS resolves container names to IPs. Flask connects to postgres-db:5432. The lab slides show the default bridge has DHCP but not DNS, which is why a custom network is needed.
  • Containers on the network reach each other's internal ports, but 5432 is not published, so nothing on the host or outside can reach the database directly.

See L08.

(b) If Container B is deleted and recreated without a volume, what happens to its data? Why use a volume? (3 marks)
  • Data is lost. PostgreSQL stores data in /var/lib/postgresql/data inside the container's writable layer, which docker rm deletes. The new container starts with an empty database.
  • A named volume (for example pgdata) is Docker-managed storage independent of the container lifecycle. Mounted at /var/lib/postgresql/data, it survives deletion, upgrades and recreation; the new container reattaches it and finds the data intact. Volumes are the recommended choice for databases and can be backed up or shared.

See L08.

(c) Write the essential commands to create a custom network, run PostgreSQL on it, and run Flask on the same network. (3 marks)
docker network create blockchain-net
docker volume create pgdata

docker run -d --name postgres-db --network blockchain-net \
  -e POSTGRES_USER=bcuser -e POSTGRES_PASSWORD=bcpass -e POSTGRES_DB=bcdb \
  -v pgdata:/var/lib/postgresql/data \
  postgres:16

docker run -d --name flask-app --network blockchain-net \
  -e DATABASE_URL=postgresql://bcuser:bcpass@postgres-db:5432/bcdb \
  -p 8080:5000 \
  flask-app-image

docker network inspect blockchain-net   # both containers attached

--network attaches each container only to the custom network; -e passes settings; Flask reaches the DB by hostname postgres-db. A running container can be added with docker network connect blockchain-net <container>.

See L08.