Laboratory Works and Case Studies


Practical implementations: SHA-256 and PoW, Merkle trees, blockchain structure, mining simulation; and case studies on CBDC for Nepal and neobanking blockchain applications.

Topics in this chapter

  • Lab 1: Implement SHA-256 to understand the concept of PoW in blockchain technology
  • Lab 2: Implement the concept of Merkle Tree and Merkle root concepts
  • Lab 3: Build the fundamental structure of a blockchain
  • Lab 4: Implement mining within a blockchain environment
  • Case Study I: CBDC identifying appropriate policy goals and design for Nepal
  • Case Study II: Neobank: An application of a Blockchain Technology

Lab 1: SHA-256 and PoW

Cryptographic Hash Functions: Formal Properties

A cryptographic hash function H:{0,1}{0,1}nH: \{0,1\}^* \rightarrow \{0,1\}^n maps arbitrary-length input to fixed-length output and must satisfy three fundamental security properties. Preimage resistance (one-way property): Given a hash output yy, it must be computationally infeasible to find any input xx such that H(x)=yH(x) = y. Formally, for any probabilistic polynomial-time adversary A\mathcal{A}, Pr[A(y)=x such that H(x)=y]negl(n)\Pr[\mathcal{A}(y) = x \text{ such that } H(x) = y] \leq \text{negl}(n). Second preimage resistance: Given xx, it must be infeasible to find xxx' \neq x such that H(x)=H(x)H(x) = H(x'). Collision resistance: It must be infeasible to find any two distinct inputs x1x2x_1 \neq x_2 such that H(x1)=H(x2)H(x_1) = H(x_2). By the birthday paradox, finding a collision requires approximately O(2n/2)\mathcal{O}(2^{n/2}) operations. For SHA-256, this translates to 21282^{128} operations — computationally infeasible with current technology. Additionally, hash functions exhibit the avalanche effect: a single-bit change in input should alter approximately 50% of output bits, ensuring that hash outputs appear pseudorandom and uncorrelated.

The Proof of Work Mechanism and Nonce Discovery

Proof of Work (PoW) leverages the computational asymmetry of hash functions to achieve distributed consensus. The protocol requires miners to find a cryptographic nonce η{0,1}32\eta \in \{0,1\}^{32} such that H(block_headerη)<TH(\text{block\_header} \| \eta) < T, where TT is the difficulty threshold. If HH outputs uniformly distributed values in [0,22561][0, 2^{256}-1], the probability that a single hash attempt succeeds is p=T2256p = \frac{T}{2^{256}}. The number of hash attempts NN required follows a geometric distribution with expected value E[N]=1p=2256T\mathbb{E}[N] = \frac{1}{p} = \frac{2^{256}}{T}. This creates profound computational asymmetry: finding a valid nonce requires E[N]\mathbb{E}[N] hash computations (computationally expensive), while verification requires only a single hash evaluation (computationally trivial). This asymmetry is the cornerstone of PoW security.

Implementation: Simulating Nonce Discovery

Consider a simplified PoW implementation where miners must find a nonce such that the SHA-256 hash begins with kk leading zeros. The threshold becomes T=2256kT = 2^{256-k}, and the expected number of attempts is E[N]=2k\mathbb{E}[N] = 2^k. For k=20k = 20 (a modest difficulty), miners expect to compute 2201062^{20} \approx 10^6 hashes. The algorithm iterates a nonce from 0 upward, computing SHA-256 of (block_header || nonce) each iteration, and checking if the hash begins with the target prefix of kk zeros. This brute-force search exemplifies the energy economics of PoW: miners expend computational resources (and consequently electrical energy) to perform essentially arbitrary calculations with no intrinsic value beyond securing the network.

Economic Implications and Security Trade-offs

The PoW mechanism creates a direct mapping between computational power and consensus influence. The probability that miner ii discovers the next block is P(miner i wins)=hiHtotalP(\text{miner } i \text{ wins}) = \frac{h_i}{H_{total}}. Rational miners invest in computational hardware and energy consumption proportional to expected block rewards: Expected Revenuei=hiHtotal×(R+F)\text{Expected Revenue}_i = \frac{h_i}{H_{total}} \times (R + F). Miners continue investing until marginal cost equals marginal expected revenue. The security of PoW blockchains derives from the cost of attack. To execute a 51% attack, an adversary must control majority hash rate, requiring investment: Attack CostHtotal2×Cost per hash\text{Attack Cost} \geq \frac{H_{total}}{2} \times \text{Cost per hash}. For Bitcoin, this translates to billions of dollars in hardware and ongoing energy costs, rendering attacks economically irrational. The energy intensity of PoW has motivated alternative consensus mechanisms, particularly Proof of Stake (PoS), where validators commit cryptocurrency rather than computational resources. Ethereum's transition to PoS in 2022 reduced its energy consumption by approximately 99.95%.

Lab 2: Merkle Trees

The Data Integrity Challenge in Distributed Ledgers

Blockchain-based distributed ledgers must store and verify an ever-growing sequence of transactions while preserving data integrity and supporting independent auditability by nodes with widely varying computational capacities. The Merkle tree — a binary hash tree — addresses this tension by providing a compact, tamper-evident commitment to an arbitrarily large set of transactions, enabling light clients to verify transaction inclusion without downloading entire blocks.

Recursive Hash Commitment: Constructing the Merkle Tree

Given an ordered set of transactions {T1,T2,,Tn}\{T_1, T_2, \dots, T_n\}, the Merkle tree is constructed bottom-up: (1) Compute leaf hashes hi=H(Ti)h_i = H(T_i) for each transaction. (2) Pair consecutive hashes: for a pair (ha,hb)(h_a, h_b), compute the parent node as hab=H(hahb)h_{ab} = H(h_a \| h_b), where \| denotes concatenation. (3) If the number of hashes is odd, duplicate the last hash. (4) Iterate until a single hash remains — the Merkle root MRM_R. Formally, the tree can be described by a recursive function where the leaf layer L0=(h1,,hn)L_0 = (h_1, \dots, h_n). For k>0k > 0, layer LkL_k is obtained from Lk1L_{k-1} by Lk[j]=H(Lk1[2j]Lk1[2j+1])L_k[j] = H(L_{k-1}[2j] \| L_{k-1}[2j+1]). The root emerges when Ld=1|L_d| = 1, where depth d=log2nd = \lceil \log_2 n \rceil. Constructing the Merkle tree requires exactly n1n-1 hash operations, yielding O(n)O(n) time complexity. Space complexity is also O(n)O(n) to store the full tree, but can be optimized to O(1)O(1) if only the root is needed.

Merkle Proofs: Logarithmic Verification of Inclusion

A Merkle proof (or audit path) provides the minimal sibling hashes required to recompute the root from a leaf. For leaf hih_i, the proof consists of log2n\lceil \log_2 n \rceil sibling hashes and a bitmask indicating whether each sibling is a left or right node. Verification proceeds as: (1) Set current=hicurrent = h_i. (2) For each sibling ss and left/right flag: if flag indicates sibling is left, current=H(scurrent)current = H(s \| current); else current=H(currents)current = H(current \| s). (3) Compare the resulting currentcurrent with the known Merkle root MRM_R. The space and time complexity of proof generation and verification is O(logn)O(\log n), compared to O(n)O(n) for a full recomputation. For n=1024n=1024, the proof contains only 10 hashes (320 bytes) and 10 hash operations — a dramatic reduction.

Economic and Computational Trade-offs

The Merkle tree trades a small increase in full-node computation (hashing transactions into a tree) for an enormous reduction in verification costs for light clients. A light client (SPV) stores only block headers, each containing the 32-byte Merkle root alongside other metadata (~80 bytes per block). With Bitcoin's block count exceeding 800,000, the header chain is ~64 MB, compared to the full blockchain exceeding 500 GB. This makes participation possible on mobile devices, IoT endpoints, and browsers. While a light client trusts that the majority of hash power has produced a valid header, the Merkle proof guarantees inclusion consistency — if the header is valid, a correct proof incontrovertibly shows the transaction is part of that block. The full node providing the proof cannot forge a valid path for a non-existent transaction without breaking the hash function's collision resistance.

Lab 3: Blockchain Structure

Block Structure and Cryptographic Hashing

A block in a typical proof-of-work blockchain consists of a header and a body. The body contains an ordered list of transactions; the header packs together the protocol version, previous block hash, timestamp, difficulty target, nonce, and the Merkle root of the transaction set. Formally, a block BB at height ii is Bi=(version,H(Bi1),ti,difficulty,nonce,merkle_root)B_i = (\text{version}, H(B_{i-1}), t_i, \text{difficulty}, \text{nonce}, \text{merkle\_root}). The inclusion of H(Bi1)H(B_{i-1}) creates a hash-linked list that guarantees immutability: altering any bit of an earlier block forces a recalculation of all subsequent block headers, a task made deliberately expensive by the consensus mechanism. The hash is computed by concatenating the header fields and applying SHA-256 twice (the standard for Bitcoin): h=SHA-256(SHA-256(header_bytes))h = \text{SHA-256}(\text{SHA-256}(\text{header\_bytes})). Even a single-byte change in the nonce, timestamp, or a transaction inside the Merkle tree yields an entirely different hash value (the avalanche effect), making tampering immediately detectable.

State Management and Addresses

A blockchain is more than an append-only log; it must maintain a consistent ledger state. In the UTXO model, a transaction consumes previous outputs (referenced by txidtxid and index) and creates new outputs with a locking script. Each output is a tuple (value,locking_script)(\text{value}, \text{locking\_script}). The set of all unspent outputs constitutes the UTXO set, which is updated atomically with each block. Addresses are derived from public keys using a cryptographic hash function: address=Base58Check(RIPEMD-160(SHA-256(Kpub)))\text{address} = \text{Base58Check}(\text{RIPEMD-160}(\text{SHA-256}(K_{pub}))), optionally prepending a version byte and appending a checksum. When a transaction is verified, the node: (1) checks the digital signature against the public key revealed in the unlocking script; (2) ensures the referenced UTXOs exist and are unspent; (3) confirms that the sum of input amounts \ge sum of output amounts (the difference being the transaction fee); and (4) computes the transaction hash and verifies it is not already mined (to prevent replay).

Security Against Double Spending and Tampering

The paradigmatic attack on a digital currency is double spending — attempting to use the same coins in two conflicting transactions. PoW blockchains resolve this through the longest chain rule: honest miners always extend the chain with the most accumulated work. The probability that an attacker controlling fraction α\alpha of hash rate ever catches up from zz blocks behind when α<0.5\alpha < 0.5 is P(z,α)=(α1α)zP(z, \alpha) = \left(\frac{\alpha}{1-\alpha}\right)^z. For α=0.1\alpha = 0.1 and z=6z = 6, P0.0009P \approx 0.0009, motivating the conventional six-confirmation heuristic. The Sybil attack vector — fabricating multiple pseudonymous identities to influence consensus — is rendered economically equivalent to hashrate acquisition by PoW's resource-based weighting, collapsing identity-based manipulation into the costlier computational attack.

Lab 4: Mining Simulation

Building the Simulation Framework

This laboratory exercise deploys a minimalist, Python-based blockchain environment in which each student configures a node — an instance that can generate transactions, validate blocks, and participate in the consensus mechanism. The simulation abstracts network propagation using a shared event queue but retains the core computational steps: hashing, nonce search, and chain selection. All cryptographic primitives rely on SHA-256. The miner's task is to find a nonce η\eta such that SHA-256(SHA-256(block_header))T\text{SHA-256}(\text{SHA-256}(\text{block\_header})) \leq T, where TT is the target value. The target TT is a 256-bit number that adjusts to maintain a chosen average block time τ\tau. If the network's total hash rate is HH, the expected number of hashes required is 2256T\frac{2^{256}}{T}, giving an expected time between blocks τ2256TH\tau \approx \frac{2^{256}}{T \cdot H}. The difficulty DD is defined as D=TmaxTD = \frac{T_{\max}}{T}, so DD is proportional to the average work per block.

The Consensus Protocol and Fork Resolution

Once a miner finds a valid block, it broadcasts the block to all peers. Nodes validate the block by checking the hash inequality, transaction signatures, and the inclusion of a valid reference to the previous block. The consensus rule is the longest-chain rule. In the simulator, nodes maintain a tree of blocks and select the tip with the greatest total difficulty. Students intentionally introduce network latency to create competing blocks. When two miners find a block at approximately the same height, a temporary fork occurs. The subsequent arrival of a third block resolves the fork — the branch with more work becomes canonical. The stale rate ss is measured as the ratio of orphaned blocks to total blocks. The simulator allows tuning of block propagation delay Δ\Delta to explore the relationship s11+τΔs \approx \frac{1}{1 + \frac{\tau}{\Delta}}, which shows that shorter block times increase the orphan rate, reducing the efficiency of the network's security budget.

Computational Economics: Profitability and Hashpower Allocation

Each simulated miner has a hardware efficiency (hashes per joule) and an electricity cost (cents per kWh). The expected revenue per second for miner ii is Ri=hiHBτR_i = \frac{h_i}{H} \cdot \frac{B}{\tau}, where BB is the reward per block. The cost per second is ci=hiec_i = h_i \cdot e, with ee the energy cost per hash. The break-even electricity price is ebreak-even=BHτe_{\text{break-even}} = \frac{B}{H \tau}. This condition reveals the network's security budget: total miner revenue Bτ\frac{B}{\tau} secures the blockchain against double-spend attacks. The lab also introduces mining pool dynamics. If miners pool their resources and share rewards proportionally, students examine the Nash equilibrium when pools charge fees. They observe that concentration can arise if large pools offer lower variance, a classic centralisation pressure. The security analysis extends to the 51% attack threshold: an attacker controlling fraction α\alpha of aggregate hashrate can, with sufficient patience, produce an alternative chain that overtakes the honest chain. Students parameterize α\alpha and zz to compute attack probabilities, observing the exponential decay in attack feasibility as confirmation depth zz increases.

Case Study I: CBDC for Nepal

Strategic Policy Objectives

Central Bank Digital Currency (CBDC) refers to a digital form of sovereign fiat money, issued and fully backed by the central bank, constituting a direct claim on the monetary authority. For emerging economies such as Nepal, a CBDC is not merely a technological novelty but a tool to address structural distortions in payments, financial inclusion, and monetary policy transmission. The strategic objectives can be grouped into four pillars: (1) Financial inclusion and cost reduction: Over 60% of Nepal's adult population lacks access to formal banking services, and cash in circulation exceeds 25% of GDP. A well-designed CBDC can serve as a low-cost digital payment rail, allowing even the poorest households to store and transfer value using basic mobile phones, without needing a bank account. (2) Macroeconomic and monetary sovereignty: Nepal's economy is highly dollarized via the informal use of Indian rupees (INR) in border areas. A CBDC denominated in NPR could strengthen the domestic unit of account and offer an alternative to crypto-asset adoption. (3) Remittance efficiency: With annual remittance inflows of roughly $8.5 billion (around 25% of GDP), Nepal is one of the world's most remittance-dependent nations. Average fees for sending $200 to Nepal remain near 5–7%. A CBDC could slash these costs by enabling near-instant, peer-to-peer cross-border transfers. (4) Fiscal transparency: Programmable features of a CBDC can reduce leakage in social transfer programs.

Architectural Design Choices

A foundational decision is whether the CBDC is token-based (validity depends on the verifiability of the digital object itself, analogous to cash) or account-based (validity depends on the identity of the account holder). For Nepal, a hybrid architecture is optimal: small-value transactions operate on a token basis with pseudonymous identifiers, while transactions above a threshold require full KYC-linked accounts. A two-tier architecture, in which the central bank issues CBDC to intermediaries (commercial banks, licensed payment service providers, and the Postal Service) who then distribute it to end users, preserves the Nepal Rastra Bank's balance-sheet control while leveraging private-sector distribution. Nepal's topography — with significant portions of the population in mountainous regions lacking reliable connectivity — necessitates offline functionality. This can be achieved through secure element hardware in mobile devices that permits a bounded number of offline transactions before requiring synchronization. Let noffn_{off} denote the offline transaction limit and voffv_{off} the cumulative value cap; the double-spending risk DλnoffE[v]τD \approx \lambda \cdot n_{off} \cdot \mathbb{E}[v] \cdot \tau, where λ\lambda is the fraud arrival rate and τ\tau is the synchronization lag. Policy must set (noff,voff)(n_{off}, v_{off}) such that DD remains below a tolerable threshold.

Macroeconomic Implications

Introducing a CBDC alters the composition of the monetary aggregates. Money demand becomes Md=PL(Y,id,iCBDC,ib)M^d = P \cdot L(Y, i_d, i_{CBDC}, i_b), where YY is real income, idi_d is the deposit rate, iCBDCi_{CBDC} is the CBDC remuneration rate, and ibi_b is the bond rate. If NRB sets iCBDC>0i_{CBDC} > 0, it creates a floor for deposit rates, compressing bank net interest margins. In Nepal, where the banking sector is already characterized by high spreads, an interest-bearing CBDC could trigger disintermediation — depositors migrating from bank deposits to CBDC — particularly during periods of financial stress. This "digital run" risk argues for a zero-remuneration or tiered-remuneration design: iCBDC(h)=0i_{CBDC}(h) = 0 for holdings hhˉh \leq \bar{h} and iCBDC(h)<idi_{CBDC}(h) < i_d for h>hˉh > \bar{h}. The shift from cash to CBDC affects seigniorage: S=ΔMCBDC+iresMCBDCCopsS = \Delta M_{CBDC} + i_{res} \cdot M_{CBDC} - C_{ops}, where CopsC_{ops} is the operational cost of the digital infrastructure. Because CopsC_{ops} for a distributed digital system can exceed the cost of printing and distributing cash, NRB must ensure that adoption generates sufficient scale to amortize fixed costs. Nepal maintains a fixed peg to the Indian rupee (1 INR = 1.6 NPR). An NPR-CBDC that is easily convertible on international corridors could increase capital mobility, potentially testing the peg. A careful phasing, initially limiting cross-border use to remittances in partnership with Indian and Gulf-state central banks, would mitigate such stress.

Welfare Gains from Remittance Cost Reduction

The welfare gains from CBDC-driven inclusion can be modeled through a household's consumption-smoothing problem. If a CBDC corridor reduces the effective remittance fee from ϕ0\phi_0 to ϕ1\phi_1, the equivalent variation in income is EV(ϕ0ϕ1)R1βEV \approx \frac{(\phi_0 - \phi_1) \cdot R}{1 - \beta}, where RR is the annual remittance flow. For Nepal, with R \approx \8.5$ billion annually, even a 2-percentage-point fee reduction yields welfare gains on the order of hundreds of millions of dollars in present-value terms. The mBridge project, involving the BIS and several Asian central banks, provides a template for multi-CBDC platforms. Nepal's digital infrastructure presents binding constraints: mobile penetration exceeds 130% (with multiple SIMs per user), 4G/LTE covers about 90% of the population, and electricity access is over 93%. The National ID system deployment is ongoing; by integrating with the CBDC registration, the government could accelerate digital ID uptake, using the digital wallet as a de facto identity authenticator for e-government services.

Case Study II: Neobank

The Economics of Disintermediation and Transaction Costs

The emergence of neobanks — digital-only financial institutions operating without traditional physical branch networks — has fundamentally altered the retail and commercial banking landscape. The integration of blockchain technology has catalyzed a transition from mere front-end innovators to core infrastructure disruptors within Web 3.0 financial ecosystems. In a traditional correspondent banking network, the total cost of a transaction is CT=Corigination+i=1NCintermediary,i+CFX+CsettlementC_T = C_{origination} + \sum_{i=1}^{N} C_{intermediary, i} + C_{FX} + C_{settlement}, where NN represents the number of correspondent banks required to bridge the originator and beneficiary institutions. Each intermediary node imposes a marginal cost including compliance checks, ledger reconciliation, and profit margins. Conversely, a blockchain-integrated neobank utilizes a decentralized settlement layer, transforming the cost function to CB=Conramp+Cgas+Cliquidity+Csmart_contractC_B = C_{on-ramp} + C_{gas} + C_{liquidity} + C_{smart\_contract}. The economic condition for disintermediation occurs when CB<CTC_B < C_T. Because CgasC_{gas} and Csmart_contractC_{smart\_contract} are largely independent of geographic distance and number of traditional borders crossed, the blockchain cost curve is remarkably flat compared to the linearly scaling traditional cost curve CT(N)C_T(N). Consequently, for high-NN corridors (e.g., remittances from the US to emerging markets), the neobank achieves a massive structural cost advantage.

AMM-Based Cross-Border Settlement

Traditional neobanks rely on wholesale FX markets requiring substantial capital reserves and pre-funded nostro/vostro accounts. Web 3.0 neobanks bypass this by integrating Automated Market Makers (AMMs). The most prevalent AMM model utilizes the constant product formula xy=kx \cdot y = k, where xx and yy represent the reserve quantities of two distinct assets. If a neobank routes a customer's transfer of Δx\Delta x into the pool, the amount of asset yy dispensed is Δy=yΔxx+Δx\Delta y = \frac{y \cdot \Delta x}{x + \Delta x}. The marginal price before the trade is P=y/xP = y/x, while the execution price is Pexec=yx+ΔxP_{exec} = \frac{y}{x + \Delta x}. The difference is slippage: S=yΔxx(x+Δx)S = \frac{y \cdot \Delta x}{x(x + \Delta x)}, which is inversely proportional to the square of the pool's depth (x2x^2). For retail-sized cross-border transfers (small Δx\Delta x relative to xx), slippage approaches zero. By aggregating global liquidity into decentralized pools, neobanks can offer FX spreads that are mathematically tighter than those of traditional banks.

Hybrid Custody Architecture and DeFi Integrations

To offer these advantages while maintaining a user experience comparable to traditional banking, modern neobanks employ hybrid custody architectures. Pure DeFi protocols require users to manage private keys and interact directly with complex smart contracts — a friction point limiting mainstream adoption. Neobanks solve this via smart contract orchestration and Multi-Party Computation (MPC) wallets. In this architecture, the neobank acts as the regulated fiat on/off ramp and the custodian of the user's cryptographic keys via MPC, which shards the private key across multiple secure enclaves. When a user requests a high-yield savings product, the neobank's backend orchestrates a sequence of on-chain transactions: it converts fiat to a regulated stablecoin, routes the stablecoin through a decentralized lending protocol (e.g., Aave or Compound) to generate yield, and abstracts the gas fees from the end-user. This creates a "CeFi-DeFi bridge," where the frontend provides the regulatory compliance and UX of centralized finance (CeFi), while the backend captures the capital efficiencies of DeFi.

Challenges and Risk Management

Integrating blockchain into neobanking introduces severe regulatory, security, and scalability challenges. Regulatory and Compliance Frictions: The pseudonymous nature of public blockchains conflicts with KYC/AML mandates. Neobanks must comply with the Travel Rule (FATF), requiring financial institutions to pass originator and beneficiary information alongside crypto-asset transfers. To reconcile this, neobanks utilize permissioned decentralized identifiers (DIDs) and zero-knowledge compliance proofs. The EU's Markets in Crypto-Assets (MiCA) regulation imposes strict capital reserve requirements on stablecoin issuers. Security and Smart Contract Risk: Unlike traditional databases, smart contracts are immutable and publicly accessible, making them prime targets for adversarial exploits. A neobank cannot pass theoretical DeFi yield directly to consumers without pricing in the probability of a smart contract exploit pep_e and the loss given default LGDLGD. The risk-adjusted yield is radj=rdefi(pe×LGD)πneor_{adj} = r_{defi} - (p_e \times LGD) - \pi_{neo}, where πneo\pi_{neo} is the neobank's profit margin. To minimize pep_e, neobanks employ formal verification of smart contracts and utilize decentralized oracle networks to prevent price manipulation attacks. Scalability and the Blockchain Trilemma: Base-layer networks prioritize security and decentralization, resulting in low throughput and high latency unacceptable for high-frequency retail neobanking. To resolve this, neobanks route their backend transactions through Layer-2 scaling solutions, specifically ZK Rollups that generate cryptographic validity proofs for every batch of transactions. The mathematical verification of a ZK proof on the base layer takes O(1)O(1) time, regardless of the computational complexity of the batched transactions. By utilizing ZK Rollups, neobanks achieve throughput >2,000> 2,000 TPS with sub-second finality, while inheriting the cryptographic security of the underlying Layer-1 blockchain.