Chapter 15 // Protocols

Cryptocurrency
and Blockchain

Every cryptographic primitive you have learned so far, hash functions, digital signatures, public-key cryptography, was designed to solve a specific problem. Cryptocurrency is what happens when you combine them all to solve the oldest problem in finance: how to trust a stranger.

Scroll to explore
01 // The Problem

Trust without a middleman

When you send money through a bank, the bank keeps the ledger. It decides whether you have enough balance, it deducts from your account, and it credits the recipient. You trust the bank to do this honestly. Cryptocurrency asks: what if you could remove the bank entirely?

The double-spend problem

Physical cash cannot be copied. If you hand someone a banknote, you no longer have it. Digital data does not work this way. A file can be copied perfectly and sent to a thousand recipients at once. Without a central authority keeping track, nothing stops you from spending the same digital coin twice.

This is the double-spend problem, and it blocked every attempt at digital cash for decades. The solution is a shared, public ledger where every transaction is recorded and verified by the entire network. The trick is making that ledger tamper-proof without anyone in charge.

The building blocks you already know

Cryptocurrency does not introduce new cryptographic primitives. It assembles the ones you have already learned into a system where no single participant needs to be trusted.

Hash Functions (Ch 2)

Link blocks into tamper-evident chains and compress transactions into Merkle trees.

Digital Signatures (Ch 9)

Authorize transactions. Only the holder of the private key can spend funds from an address.

Asymmetric Keys (Ch 8)

Generate wallet addresses. Your public key is your identity on the network.

Randomness (Ch 4)

Create private keys. The security of every wallet starts with a good random number generator.

This chapter focuses on the cryptographic foundations of blockchain systems, not on any specific cryptocurrency, token, or investment. The goal is to show how the primitives from earlier chapters combine to create a trustless ledger.

02 // Hash Chains

Linking the past

A hash chain is the simplest data structure that makes history tamper-evident. Each entry includes the hash of the previous entry, so modifying any past record breaks every link that follows it.

Chaining hashes

You learned in Chapter 2 that hash functions are deterministic (the same input always produces the same output) and collision-resistant (it is practically impossible to find two different inputs with the same hash). A hash chain exploits both properties.

The first block (the genesis block) is hashed on its own. Every subsequent block includes the previous block's hash as part of its own input:

H0=Hash(data0)H_0 = \text{Hash}(data_0)
Hn=Hash(Hn1datan)H_n = \text{Hash}(H_{n-1} \| data_n)

If someone changes datakdata_k, the hash HkH_k changes. But HkH_k is an input to Hk+1H_{k+1}, which is an input to Hk+2H_{k+2}, and so on. One tampered block invalidates every block after it. To hide the change, the attacker would need to recompute every hash from block kk to the end of the chain.

Hash Chain Explorer

Each block's hash depends on the previous block's hash. Edit any block's data to see how tampering breaks every block after it.

A hash chain is the backbone of a blockchain. Every block header includes the hash of the previous block header, creating a single unbroken chain from the genesis block to the most recent one. If you trust the latest hash, you implicitly trust every block before it.

03 // Blocks

Anatomy of a block

A block is more than just a container for transactions. Its header is a carefully structured set of fields that tie the block to the chain, summarize its contents, and prove the work that went into creating it.

Block header fields

1
Previous Block Hash

The SHA-256 hash of the previous block's header. This is the link in the chain. Changing any prior block changes this value.

2
Merkle Root

A single 32-byte hash that summarizes every transaction in the block. Built from a Merkle tree (explained in the next section).

3
Timestamp

When the miner started working on this block. Used by the network to adjust mining difficulty over time.

4
Difficulty Target

A threshold that the block's hash must fall below to be considered valid. Lower targets mean more work is required.

5
Nonce

A 32-bit number that the miner varies until the block hash meets the difficulty target. This is the “work” in proof of work.

Double hashing

Bitcoin hashes block headers with SHA-256 applied twice:

BlockHash=SHA-256(SHA-256(header))\text{BlockHash} = \text{SHA-256}(\text{SHA-256}(\text{header}))

This is a defense against length extension attacks, which you encountered in Chapter 3. A raw SHA-256 hash can be extended without knowing the original input. Double hashing closes that vulnerability. The outer hash takes the fixed-length output of the inner hash as its input, so there is nothing to extend.

The block header is only 80 bytes, but it commits to the entire block's contents through the Merkle root. This compact commitment is what makes it possible for lightweight clients to verify the chain without downloading every transaction.

04 // Merkle Trees

Efficient proof of inclusion

A block can contain thousands of transactions. Merkle trees let you prove that a specific transaction is included in a block by providing just a handful of hashes, not the entire block.

A tree of hashes

A Merkle tree is a binary tree where every leaf is the hash of a transaction and every internal node is the hash of its two children:

Leaf: Hi=Hash(txi)\text{Leaf: } H_i = \text{Hash}(tx_i)
Parent: Hparent=Hash(HleftHright)\text{Parent: } H_{parent} = \text{Hash}(H_{left} \| H_{right})

The root of the tree, a single 32-byte hash, is stored in the block header. It uniquely represents every transaction in the block. If any transaction changes, the root changes.

The power of a Merkle tree is in verification. To prove that a transaction is included, you only need the sibling hash at each level of the tree. The proof size is logarithmic: log2(n)\lceil \log_2(n) \rceil hashes for nn transactions. For a block with 4,000 transactions, that is about 12 hashes (384 bytes), not the full block.

SPV Verification

A lightweight wallet does not download every transaction in a block. It only needs the block header and a short proof to verify that a specific transaction is included. Click a transaction to see how.

Block #847,291 Header
Prev Hash
0000000000000953...
Merkle Root
...
Timestamp
2024-01-15 14:32:07
Nonce
2,083,236,893
Click a transaction to verify

Merkle proofs are what make lightweight wallets (SPV clients) possible. A phone wallet does not need to download every transaction in every block. It only needs the block headers and a Merkle proof for its own transactions.

05 // Transactions

Signing value transfers

A cryptocurrency transaction is a digitally signed message that says: 'I, the owner of this address, authorize sending X coins to that address.' The signature is the proof of ownership, and everyone on the network can verify it.

Transactions are signed, not encrypted

Digital signatures from Chapter 10 prove that a message came from the holder of a specific private key. In a blockchain, they prove ownership: only the person who controls the private key for an address can authorize a spend from it.

The sender hashes the transaction data and signs the hash with their private key:

signature=Sign(sk,Hash(tx_data)){\color{#00e5a0}\text{signature}} = \text{Sign}({\color{#8b5cf6}sk}, \text{Hash}({\color{#f59e0b}tx\_data}))

Anyone on the network can verify it using the sender's public key:

Verify(pk,Hash(tx_data),signature)=?true\text{Verify}({\color{#8b5cf6}pk}, \text{Hash}({\color{#f59e0b}tx\_data}), {\color{#00e5a0}\text{signature}}) \stackrel{?}{=} \text{true}

The transaction is not encrypted. Everyone on the network can read its contents. The signature provides authentication and integrity, not confidentiality. It proves who sent it and that the data has not been altered.

Inputs and outputs

A transaction does not move a balance from one account to another like a bank. Instead, it references previous transaction outputs that have not yet been spent (called UTXOs, unspent transaction outputs) and creates new outputs.

Think of UTXOs as individual coins of various denominations. To pay someone, you select enough coins to cover the amount, sign each one to prove ownership, and create new outputs: one for the recipient and one “change” output back to yourself if you overpaid. The selected UTXOs are marked as spent and cannot be used again. This is how the double-spend problem is solved at the transaction level.

Transaction Signing

Sign a transaction with ECDSA, then tamper with it to see the signature become invalid.

Every node on the network independently verifies every signature before accepting a transaction. If the signature is invalid, the transaction is rejected. No central authority is needed because the math is the authority.

06 // Proof of Work

The cost of trust

Anyone can create a valid transaction. But who decides which transactions get added to the ledger, and in what order? Proof of work is the consensus mechanism that answers this question by making it computationally expensive to propose new blocks.

The mining puzzle

To add a block to the chain, a miner must find a nonce (a number they can freely choose) such that the hash of the block header falls below a target value:

SHA-256(block header with nonce)<target\text{SHA-256}(\text{block header with } {\color{#00e5a0}\text{nonce}}) < {\color{#f59e0b}\text{target}}

The target is a 256-bit number. A lower target means the hash must have more leading zeros, which means more attempts are needed on average. The expected number of attempts is:

E[attempts]=2256targetE[\text{attempts}] = \frac{2^{256}}{\text{target}}

Pre-image resistance (Chapter 2) is what makes this hard. You cannot work backwards from a desired hash to find the nonce. The only strategy is brute force: try billions of nonces until one works. But verifying is trivial. Anyone can hash the block once and check that the result is below the target.

Proof-of-Work Mining Simulator

Find a nonce that makes the block hash start with a certain number of zeros. Increase difficulty to see how the search time grows exponentially.

Block Data
Block #7 | prev:a1b2c3d4 | tx:Alice->Bob:5BTC
Difficulty (leading hex zeros)
2
Expected attempts: ~256 (162)

Difficulty adjustment

The network adjusts the target every 2,016 blocks (roughly two weeks) to maintain an average block time of about 10 minutes. If miners are finding blocks too quickly because more computing power has joined the network, the target decreases (more leading zeros required). If blocks are too slow, the target increases.

This self-adjusting mechanism ensures that the cost of adding a block stays proportional to the network's total computing power, regardless of how much hardware is deployed.

Why rewriting history is impractical

To alter a transaction in block 100 of a chain that is now at block 150, an attacker must:

1

Change the transaction in block 100 and recompute its hash.

2

Redo the proof of work for block 100 (find a new valid nonce).

3

Redo the proof of work for every block from 101 to 150 (because each depends on the previous hash).

4

Do all this faster than the rest of the network is extending the honest chain.

This requires controlling more than 50% of the network's total hash rate, known as a 51% attack. For large networks, the energy and hardware cost makes this economically irrational.

Proof of work vs. proof of stake

Proof of work is not the only consensus mechanism. Proof of stake replaces computational cost with economic cost.

Proof of Work

Security comes from energy expenditure. Miners compete to find valid hashes. Attacking the network requires outspending all honest miners combined.

Used by: Bitcoin

Proof of Stake

Security comes from locked capital. Validators stake cryptocurrency as collateral. Misbehaving validators lose their stake (slashing).

Used by: Ethereum

Proof of work is a Sybil resistance mechanism. Without a cost to creating blocks, an attacker could flood the network with fake identities and fake blocks. The computational cost is the price of participation.

07 // Wallets & Addresses

From keys to identity

A wallet is, at its core, a private key. From that single secret, elliptic curve math derives a public key, and hashing derives an address. This pipeline is your identity on the network.

The derivation pipeline

Creating a blockchain address is a one-way pipeline. Each step is irreversible: you can go forward (private key to address) but never backward (address to private key).

1
Random number

Generate 256 random bits using a cryptographically secure RNG (Chapter 4). This is your private key.

2
Elliptic curve multiplication

Multiply the generator point on the elliptic curve by your private key (Chapter 9). The result is your public key. This is computationally easy forward and infeasible to reverse.

3
Hash the public key

Apply SHA-256, then RIPEMD-160, to compress the public key into a 20-byte hash. This adds a layer of protection: even if elliptic curve cryptography were weakened, your funds remain safe as long as you have not spent from that address (which reveals the public key in the signature).

4
Base58Check encoding

Encode the hash with a version byte and a checksum into a human-readable string. Base58 omits easily confused characters (0, O, l, I) to reduce transcription errors.

address=Base58Check(RIPEMD-160(SHA-256(pubkey)))\text{address} = \text{Base58Check}(\text{RIPEMD-160}(\text{SHA-256}({\color{#8b5cf6}\text{pubkey}})))
Wallet Address Derivation

See how a private key becomes a blockchain address through a pipeline of elliptic curve math and hashing.

This demo uses P-256 and SHA-256. Real Bitcoin uses secp256k1 and RIPEMD-160, which are not available in browsers.

Your wallet's security starts and ends with your private key. If someone obtains it, they control your funds. If you lose it, your funds are permanently inaccessible. There is no password reset, no customer support, no recovery process. The cryptography that protects your wallet from attackers also protects it from you.

08 // Best Practices

Building on blockchain responsibly

Blockchain security is only as strong as the cryptographic primitives underneath it. These guidelines reflect the lessons learned from over a decade of real-world cryptocurrency systems.

🎲

Generate Keys with Strong Randomness

Use a cryptographically secure RNG. Never use Math.random() or predictable seeds. The Android SecureRandom bug of 2013 caused real Bitcoin losses because wallets generated duplicate private keys.

🔄

Never Reuse Addresses

Each transaction should use a fresh address. Reusing an address reveals the public key (from the spending signature) and makes it easier to link transactions to a single identity.

🌳

Verify Merkle Proofs, Not Headers Alone

Light clients must verify proofs of inclusion. Trusting a block header without checking the Merkle proof means trusting without verifying, which defeats the purpose of a trustless system.

⚖️

Understand the Consensus Model

Proof of work and proof of stake have different security properties and trust assumptions. Know what your system guarantees and where its security budget comes from.

Blockchain is a specific application of cryptographic primitives, not a magic trust machine. Its security rests entirely on the correctness of the hash functions, signature schemes, and randomness generators underneath it. Get any of those wrong and the entire system fails.

09 // What You Learned

From primitives to protocol

This chapter showed how the cryptographic primitives from earlier chapters combine into a trustless, decentralized ledger. Each piece solves a specific problem, and together they eliminate the need for a central authority.

The full picture

Hash chains make the ledger tamper-evident. Modifying any past block breaks every block after it, making forgery immediately detectable.

Merkle trees compress thousands of transactions into a single root hash, enabling efficient proof of inclusion without downloading entire blocks.

Digital signatures authorize transactions. Only the holder of the private key can spend funds, and everyone can verify the signature independently.

Proof of work creates consensus. The computational cost of adding blocks prevents spam, establishes ordering, and makes rewriting history impractical.

Strong randomness generates private keys. The entire security of every wallet depends on the quality of the random number generator that created it.

The cryptographic tools you have learned can do more than secure communications and build blockchains. Next, we explore the frontier: post-quantum algorithms that resist quantum computers, zero-knowledge proofs that prove statements without revealing data, and multi-party computation that computes on secret inputs.

Up Next

Chapter 16 // Frontier Cryptography

Continue Learning