Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 40 ยท Projects

Project: A Tiny Blockchain and Merkle Proofs

Build a hash-chained ledger in Python: link blocks with SHA-256, add proof of work, detect tampering and verify Merkle inclusion proofs like a light client.

A blockchain sounds exotic, but its core is a small idea you already know: a list of records where each record contains the hash of the previous one. Change anything in the past and every later hash stops matching. In this project you build that structure in about sixty lines of Python, add proof of work so that rewriting history becomes expensive, and finish with Merkle proofs so a "light client" can check one transaction without downloading the whole block.

This is a teaching model. It has no network, no signatures on transactions and no consensus between many nodes. What it does have are the three hashing ideas that real systems depend on: chaining, work and Merkle trees. You met the last one in using hashes; here it becomes part of a working data structure.

How the pieces fit together

Each block stores a few fields. The header holds the previous block's hash, a Merkle root summarizing the transactions, a timestamp and a nonce. The block's own hash is the SHA-256 of that header. The transactions themselves are not hashed directly into the header; only their Merkle root is.

flowchart LR
    G["Block 0 (genesis)<br/>prev: 000...<br/>root: R0"] --> B1["Block 1<br/>prev: hash of block 0<br/>root: R1"]
    B1 --> B2["Block 2<br/>prev: hash of block 1<br/>root: R2"]
    B2 --> B3["Block 3<br/>prev: hash of block 2<br/>root: R3"]

Each block commits to its predecessor. Altering block 1 changes its hash, which no longer matches the prev field in block 2.

Step 1: chain blocks with hashes

The first version has no work and no Merkle tree, so you can see the linking idea on its own. A block is a dictionary; block_hash serializes the header to canonical JSON (sorted keys, no spaces) so the same header always gives the same bytes. Canonical encoding matters: if two programs serialize the same data differently, they compute different hashes and the chain breaks for no good reason.

validate walks the chain from the start. For every block it checks two things: the stored prev equals the real hash of the block before it, and the data has not changed since that hash was linked.

Python Hash-chained blocks and tamper detection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last two lines show the key property. Patching the damaged link fixes block 2's prev, but block 2 itself changed, so block 3's prev is now wrong. To hide a change, the attacker must recompute every block after it. With only chaining, that is trivial for a computer. That is why the next step adds a cost.

Step 2: proof of work

Proof of work makes producing a block expensive and checking it cheap. The rule here: a block is valid only if its hash, written in hex, starts with a given number of zeros. The miner changes a counter called the nonce and hashes again and again until the rule holds. There is no shortcut, because a good hash behaves like a random function (hash functions).

Each extra hex zero multiplies the expected work by 16. Verification is a single hash, no matter how hard the puzzle was.

flowchart TD
    S["Build header with nonce = 0"] --> H["Hash the header"]
    H --> Q{"Starts with enough zeros?"}
    Q -- "no" --> N["nonce = nonce + 1"]
    N --> H
    Q -- "yes" --> D["Block found: anyone verifies with one hash"]

Mining is a loop of guesses; verification is one hash.

Python Mining blocks with proof of work

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The attempt counts you see are specific to this data, but the pattern is always the same: roughly 16 times more attempts for each added zero. Real networks pick a difficulty that needs astronomical numbers of hashes per block, and they let many miners race, so an attacker would have to out-compute the honest majority to rewrite recent history. Our single-process model only shows the cost mechanism.

Proof of work is only one way to agree on a chain. It is also the reason these systems consume large amounts of energy. The hash chain itself (tamper evidence) is useful without any mining, as in Git, certificate transparency logs and audit trails.

Step 3: Merkle roots for the transactions

Putting every transaction text into the block header would make headers huge. Instead each block carries a list of transactions and a single Merkle root. The header commits to the root; the root commits to every transaction.

The benefit shows up when someone only cares about one transaction. A wallet on a phone can download just the headers (small) and ask a server for one transaction plus its Merkle proof, the sibling hashes along its path. The wallet recomputes the path and compares the result with the root in a header it already trusts. It never needs the other transactions.

The code below builds a block with eight transactions, produces a proof for one of them, verifies it as a light client would, and then shows two forgeries failing: a changed transaction and a proof for the wrong position.

Python A light client verifying a Merkle proof

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two details keep the tree sound. The 0x00 and 0x01 prefixes (domain separation) prevent a leaf from being passed off as an inner node. And the proof stores, for each level, whether the current node is the right child, so the verifier knows in which order to combine the hashes.

Putting it together

A complete block now carries index, prev, merkle_root, difficulty and nonce, plus the list of transactions. Mining hashes the header only; transactions are covered through the root. Validating a chain means checking, for each block, that the proof of work is present, that prev matches, and that the Merkle root recomputed from the transactions equals the stored one.

Here is a good way to extend the project on your own, using the editors above:

  • Combine step 2 and step 3 so that add_block takes a list of transactions and mines the header.
  • Add a rule that the difficulty may change only by one step between blocks.
  • Sign each transaction with the toolkit from the mini crypto library project, and reject unsigned ones.
  • Implement a "longest valid chain wins" rule that picks between two competing chains by total work.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does changing an old block break the whole chain after it?

    The prev field of block i+1 is the hash of block i. A changed block hashes to something else, so every later link must be recomputed.
  2. 2. How does the work needed grow when the difficulty goes from 3 to 4 leading hex zeros?

    Each hex digit has 16 values, so one more required zero makes a valid hash about 16 times rarer.
  3. 3. What does a Merkle proof for one transaction in a block of 8 contain?

    A tree with 8 leaves has 3 levels above the leaves, so the proof needs one sibling hash per level: log2(8) = 3.
  4. 4. Verifying proof of work is cheap because:

    Mining searches for a nonce; checking only requires hashing the finished block once and looking at the leading zeros.
  5. 5. Why is canonical JSON (sorted keys, fixed separators) used for hashing headers?

    Hashes depend on exact bytes. Without a fixed encoding, two honest programs could disagree about a block's hash.

Summary

  • A hash chain links each record to the hash of the previous one, so any change to history is detected.
  • Proof of work makes block creation expensive (many hashes) and verification cheap (one hash); each extra hex zero multiplies the work by 16.
  • A block header commits to its transactions through a single Merkle root.
  • A Merkle inclusion proof lets a light client verify one transaction using only about log2(n) hashes and a trusted header.
  • Use canonical serialization and domain separation so hashes are unambiguous.
  • Tamper evidence (chaining) is useful on its own; mining and consensus are only needed when mutually distrusting parties must agree on one history.

Next: Project: Break Weak Crypto.