Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 41 ยท Building a Toy Blockchain

Building and Validating the Chain

Create a genesis block, append linked blocks, verify the whole chain and see exactly how tampering is detected, with a runnable Python toy blockchain.

With a block design in hand, you can build the chain itself. A blockchain is just a list of blocks plus a set of rules, and the rules matter more than the list. A node that receives a chain from a stranger does not trust it. It re-checks every block from the start and accepts the chain only if each one passes. That habit, "do not trust, verify", is why no central authority is needed.

In this lesson you will create the first block (the genesis block), append new blocks that link to the tip, write a function that validates a whole chain, and then attack your own chain to see exactly which check catches which kind of tampering. The last experiment shows an uncomfortable truth: with only hashes and links, a determined editor can rewrite history for free. Fixing that is the job of proof of work.

The genesis block

Every other block points to its predecessor, but the first block has none. It is created by hand, with a made-up previous_hash (all zeros by convention), index 0, and often a message. Because it has no parent, nodes do not derive it from anything: every node's software has the same genesis block hard-coded, so they all start from the same root. Bitcoin's genesis block famously embeds a newspaper headline from January 2009.

After genesis, each new block must satisfy four conditions to follow the tip (the latest block):

  1. Its index is the tip's index plus one.
  2. Its previous_hash equals the tip's hash.
  3. Its body_hash matches the transactions it carries.
  4. Its timestamp is not earlier than the tip's.
flowchart LR
    G["Genesis<br/>index 0<br/>prev: 000..."] --> B1["Block 1<br/>prev: hash of 0"]
    B1 --> B2["Block 2<br/>prev: hash of 1"]
    B2 --> B3["Block 3<br/>prev: hash of 2"]

Every block stores the hash of its predecessor; the genesis block is the only one with a hand-written link.

Building the chain

The code below defines the same Header and Block as before, plus a Blockchain class that holds the list. The method add_block creates a block that follows the current tip, which is what a node does when it assembles new transactions.

Python Genesis block and appending blocks

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.

You can read the links directly off the output: each row's prev equals the hash of the row above. That is the whole data structure. Everything that follows is about checking it.

Validating a whole chain

A validator walks from genesis to the tip and checks each block against its predecessor. It returns the first problem it finds, with a reason, so you can see which rule failed. Because a chain is only as strong as its weakest link, checking everything is mandatory: a single bad block makes every later block built on it invalid too.

The checks, in order:

  1. The chain is not empty and block 0 equals the known genesis block (compare its hash with the one hard-coded in the software).
  2. For each later block i: index == i, previous_hash equals block i-1's hash, body_hash matches the recomputed hash of the transactions, and the timestamp is not earlier than block i-1's.

The code below attacks the chain in four ways and runs the validator after each.

Python Validating and tampering

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.

Read the five results as a story:

  • Test 2 is caught by the body check. The header still commits to the old payment.
  • Test 3 is caught one block later. Fixing body_hash changes block 2's hash, so block 3's previous_hash no longer matches. The tampering "spreads" forward until something notices it.
  • Test 4 passes. If you rewrite the tip, nothing comes after it to disagree. The forged tip has a different hash, though, so every other node that already saw the old tip knows the two chains differ and must decide which to believe.
  • Test 5 is caught by the index and link checks.

This is why recent blocks are less final than old ones, and why exchanges wait for several confirmations before treating a payment as settled.

The rewrite problem

Test 4 hints at a deeper issue. Suppose the attacker rewrites block 2 and then recomputes every later block so all links match. That takes a few microseconds with a hash function. The result is a perfectly valid chain, because our validator checks consistency, not effort. Anyone can fabricate an alternative history as fast as the computer can hash.

Python Rewriting history costs nothing without 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 forged chain passes every check. A pure hash chain proves that data has not changed since it was linked, but it cannot tell an honest history from a freshly fabricated one. To make rewriting expensive, real networks require each block to carry costly evidence of effort (proof of work) or to be signed by staked validators (proof of stake), and they follow the chain with the most accumulated effort. The mining lesson adds that missing piece to this same code.

Accepting a new block

A node does not only validate whole chains; it also decides whether to accept one new block that peers announce. That is the same set of checks applied to a single block against the current tip, with a rejection reason when it fails. Keeping rejection reasons is not just for tutorials: real node logs say things like "bad-prevblk" and "bad-txnmrklroot" for the same reasons.

Python Accepting or rejecting a new block

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.

Only the first block was accepted. Everything else fails one specific check, and none of the failures change the chain: a rejected block simply never gets appended. Later lessons add two more kinds of rule on top: consensus rules (proof of work, the heaviest chain wins) and transaction rules (valid signatures, no double spends; see Transactions and the Mempool).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why do all nodes hard-code the same genesis block?

    The genesis block has no parent to check, so the software ships it as a fixed starting point. A chain that begins with a different block is rejected.
  2. 2. You edit a payment in the middle of the chain and also fix that block's body_hash. Which check catches this?

    Changing body_hash changes the block's header, so its hash changes. The following block still stores the old hash in previous_hash, so the link breaks.
  3. 3. Why does a forged chain pass validation if the forger recomputes every later block?

    A hash chain proves data did not change since linking, not that the history is honest. Making rewrites expensive is the job of proof of work or proof of stake.
  4. 4. A node receives a block whose previous_hash is not the hash of its current tip. What should it do?

    The block does not extend the chain the node follows. Real nodes may keep it aside in case a competing branch becomes longer, but they do not append it to the current tip.

Summary

  • A blockchain is a list of blocks plus validation rules; the genesis block is hard-coded and every other block links to its predecessor's hash.
  • A validator walks from genesis and checks index, link, body hash and timestamp for every block, returning the first failure.
  • Editing a block breaks either its own body check or the next block's link; only the newest block can be rewritten without immediate disagreement inside the chain.
  • Consistency checks alone cannot prevent rewrites, because recomputing hashes is cheap; proof of work (next in this chapter) makes it costly.
  • Nodes also validate single blocks on arrival and reject those that fail, without altering their chain.

Next: Proof of Work and Mining