Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 41 ยท Building a Toy Blockchain

Designing a Block

Design a blockchain block in Python: header versus body, index, timestamp, previous hash and nonce, with deterministic JSON serialization and dataclasses.

You now have the cryptographic parts: hash functions, tamper evidence, Merkle trees and signatures. From here on you assemble them into a working toy blockchain, one piece per lesson. The first piece is the block: the unit that groups a batch of transactions, stamps it with metadata and fixes its place in the chain.

Designing a block sounds like a data-structure exercise, and it is, with one twist. A block's identity is its hash, and a hash only works if every node computes the same bytes from the same block. So the central design question is not "which fields?" but "how do we turn fields into bytes in exactly one way?" This lesson answers both.

Header and body

Real blockchains split a block into two parts:

  • The header holds a small, fixed set of fields that identify the block and link it to its predecessor.
  • The body holds the actual payload, usually the list of transactions.

The header contains a commitment to the body, for example the Merkle root of the transactions or, in our simple version, a hash of them. Because the block's hash is computed from the header only, the header can be tiny while still being bound to megabytes of transactions. A light client can download just the headers and still trust the chain's history.

Field Where Purpose
index (height) header Position in the chain: genesis is 0
timestamp header Approximate creation time (whole seconds)
previous_hash header Hash of the previous block's header: the link in the chain
body_hash header Commitment to the transactions in the body
nonce header A number miners vary during proof of work
transactions body The data being recorded
flowchart LR
    subgraph H["Header (hashed)"]
        I["index"]
        T["timestamp"]
        P["previous_hash"]
        BH["body_hash"]
        N["nonce"]
    end
    subgraph B["Body (not hashed directly)"]
        TX["transactions"]
    end
    TX -->|"hash"| BH
    H -->|"hash"| ID["block hash"]

The block hash covers the header; the header covers the body through body_hash, so changing any transaction changes the block hash indirectly.

Bytes must be reproducible

A hash function takes bytes. A block is made of numbers, strings and lists, so we need a serialization: a rule that maps the block to bytes. JSON is a convenient choice, but plain json.dumps is not guaranteed to be canonical. Two Python dictionaries that are equal can serialize in different orders, because dictionaries remember insertion order:

Python
{"from": "alice", "to": "bob"} == {"to": "bob", "from": "alice"}   # True

Equal data, different text, different hash. If two nodes build the same block with fields in a different order, they disagree about its hash, and the network splits. The cure is a strict recipe that every node follows:

  1. Sort the keys (sort_keys=True).
  2. Fix the separators so no optional spaces appear (separators=(",", ":")).
  3. Encode as UTF-8 so the byte sequence is defined, not just the text.
  4. Avoid floats where possible, because 5 and 5.0 serialize differently. Real systems store money as integers in the smallest unit (satoshis, wei).
Python Why serialization must be deterministic

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.

Notice that the two plain hashes differ even though the dictionaries are equal, while the canonical hashes match. Real blockchains avoid the question by defining a binary format. Bitcoin serializes fields as fixed-size little-endian bytes, and Ethereum uses RLP encoding. For a teaching chain, canonical JSON is easy to read and debug, which is why we use it.

A block as a dataclass

Python's dataclasses module is a natural fit: a block is a bundle of named fields with no behavior beyond hashing. Two choices make the class safer:

  • frozen=True makes instances immutable. Assigning to a field raises FrozenInstanceError. A recorded block should never change; to "edit" one you must build a new block, which gets a new hash.
  • Tuples instead of lists for the transactions, since tuples cannot be modified in place either.

Hashing uses only the header. dataclasses.asdict turns the header into a dictionary, and the canonical serializer turns that into bytes.

Python A block with header and body

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 block hash depends on all five header fields and, through body_hash, on every transaction. Any change anywhere gives a completely different hash because of the avalanche effect covered in Cryptographic Hash Functions.

Why the header commits to the body

Because the block hash covers only the header, you might ask what stops someone from swapping the transactions in the body while leaving the header alone. The answer is that the header contains body_hash, and any node can recompute it from the body. A swapped body produces a different recomputed hash, which no longer matches the committed value. The block's own hash stays the same (the header did not change), so the swap is caught by a separate consistency check, not by the block hash.

Python Detecting a swapped body

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.

This is the same trick Merkle trees use at larger scale: a short, fixed-size value commits to a large set of data. The next lesson uses both checks, the link check and the body check, to validate a whole chain.

Design choices to remember

  • Hash the header, not the whole block. It keeps hashing cheap and lets proof of work try millions of nonces without re-hashing the transactions.
  • Timestamps are claims, not facts. Nodes only check that a timestamp is plausible (not far in the future, not before recent blocks). Our toy uses fixed integers so outputs repeat.
  • Include the index even though position implies it. It makes validation errors easier to explain and adds a cheap consistency check.
  • Never store computed hashes you could recompute. Our hash property calculates it on demand. A stored hash can silently go stale.
  • Fix the hash algorithm in the format. Real chains version their headers so that they can change rules later.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does a blockchain need a deterministic (canonical) serialization?

    Hashes are computed from bytes. If two nodes serialize equal data differently, they compute different hashes and disagree about the block.
  2. 2. In our design, which part of a block does the block hash cover directly?

    The hash is computed from the header. Because the header contains body_hash, the transactions are covered indirectly.
  3. 3. What is the role of the previous_hash field?

    Each block points back to its predecessor by hash. Changing an earlier block changes its hash and breaks this link in every later block.
  4. 4. Why use frozen=True on the dataclasses?

    Immutability matches the idea of an append-only ledger: you do not edit history, you can only create a new block with a new hash.
  5. 5. Why do real systems store money as integers instead of floats?

    5 and 5.0 give different bytes, and floating-point rounding errors accumulate. Integer amounts in the smallest unit avoid both problems.

Summary

  • A block has a header (index, timestamp, previous hash, body hash, nonce) and a body (transactions); the block hash covers the header.
  • The header commits to the body through body_hash, so changing any transaction changes the header's content and breaks consistency.
  • Hashing needs a canonical serialization: sorted keys, fixed separators, UTF-8 and no ambiguous number types.
  • Frozen dataclasses and tuples model an append-only ledger in which blocks cannot be edited in place.
  • Compute hashes on demand instead of storing them, and treat timestamps as plausible claims.

Next: Building and Validating the Chain