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 maps arbitrary-length input to fixed-length output and must satisfy three fundamental security properties. Preimage resistance (one-way property): Given a hash output , it must be computationally infeasible to find any input such that . Formally, for any probabilistic polynomial-time adversary , . Second preimage resistance: Given , it must be infeasible to find such that . Collision resistance: It must be infeasible to find any two distinct inputs such that . By the birthday paradox, finding a collision requires approximately operations. For SHA-256, this translates to 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 such that , where is the difficulty threshold. If outputs uniformly distributed values in , the probability that a single hash attempt succeeds is . The number of hash attempts required follows a geometric distribution with expected value . This creates profound computational asymmetry: finding a valid nonce requires 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 leading zeros. The threshold becomes , and the expected number of attempts is . For (a modest difficulty), miners expect to compute 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 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 discovers the next block is . Rational miners invest in computational hardware and energy consumption proportional to expected block rewards: . 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: . 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 , the Merkle tree is constructed bottom-up: (1) Compute leaf hashes for each transaction. (2) Pair consecutive hashes: for a pair , compute the parent node as , 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 . Formally, the tree can be described by a recursive function where the leaf layer . For , layer is obtained from by . The root emerges when , where depth . Constructing the Merkle tree requires exactly hash operations, yielding time complexity. Space complexity is also to store the full tree, but can be optimized to 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 , the proof consists of sibling hashes and a bitmask indicating whether each sibling is a left or right node. Verification proceeds as: (1) Set . (2) For each sibling and left/right flag: if flag indicates sibling is left, ; else . (3) Compare the resulting with the known Merkle root . The space and time complexity of proof generation and verification is , compared to for a full recomputation. For , 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 at height is . The inclusion of 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): . 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 and index) and creates new outputs with a locking script. Each output is a tuple . 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: , 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 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 of hash rate ever catches up from blocks behind when is . For and , , 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 such that , where is the target value. The target is a 256-bit number that adjusts to maintain a chosen average block time . If the network's total hash rate is , the expected number of hashes required is , giving an expected time between blocks . The difficulty is defined as , so 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 is measured as the ratio of orphaned blocks to total blocks. The simulator allows tuning of block propagation delay to explore the relationship , 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 is , where is the reward per block. The cost per second is , with the energy cost per hash. The break-even electricity price is . This condition reveals the network's security budget: total miner revenue 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 of aggregate hashrate can, with sufficient patience, produce an alternative chain that overtakes the honest chain. Students parameterize and to compute attack probabilities, observing the exponential decay in attack feasibility as confirmation depth 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 denote the offline transaction limit and the cumulative value cap; the double-spending risk , where is the fraud arrival rate and is the synchronization lag. Policy must set such that remains below a tolerable threshold.
Macroeconomic Implications
Introducing a CBDC alters the composition of the monetary aggregates. Money demand becomes , where is real income, is the deposit rate, is the CBDC remuneration rate, and is the bond rate. If NRB sets , 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: for holdings and for . The shift from cash to CBDC affects seigniorage: , where is the operational cost of the digital infrastructure. Because 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 to , the equivalent variation in income is , where 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 , where 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 . The economic condition for disintermediation occurs when . Because and 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 . Consequently, for high- 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 , where and represent the reserve quantities of two distinct assets. If a neobank routes a customer's transfer of into the pool, the amount of asset dispensed is . The marginal price before the trade is , while the execution price is . The difference is slippage: , which is inversely proportional to the square of the pool's depth (). For retail-sized cross-border transfers (small relative to ), 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 and the loss given default . The risk-adjusted yield is , where is the neobank's profit margin. To minimize , 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 time, regardless of the computational complexity of the batched transactions. By utilizing ZK Rollups, neobanks achieve throughput TPS with sub-second finality, while inheriting the cryptographic security of the underlying Layer-1 blockchain.