Skip to content
KALANBLON
Show contents

Chapter 2 of 6 · 15 min

Chained blocks

By the end of this chapter, you'll be able to

  • Describe the content of a block: number, previous block's fingerprint, timestamp, transactions
  • Compute a block's fingerprint from a canonical form of its content
  • Check a complete chain of blocks
  • Explain why the previous block's fingerprint must be part of the block

The anatomy of a block

A block is a small folder that contains:

  • its number (its height in the chain: 0, 1, 2…);
  • the fingerprint of the previous block, which links it to the whole history;
  • a timestamp (the date and time it was created);
  • the list of transactions (the operations) it records;
  • its own fingerprint, computed over everything above.

The first block, with no previous one, is called the genesis block.

Changing a single transaction in block 1 would break the link with block 2.

Step 5 of 5
Text description of the animation
  1. The genesis block opens the chain: its "previous" value is a convention.
  2. The transactions of the same period are grouped in a block.
  3. Each block hooks onto the previous one.
  4. The checker redoes every computation, without trusting the written fingerprints.
  5. Changing a single transaction in block 1 would break the link with block 2.

Computing a block's fingerprint

A block contains several fields and a list. To compute its fingerprint, it must be turned into a sequence of bytes that is always identical for the same content: that is the canonical form. The json module, with sort_keys=True, always writes the fields in the same order.

import hashlib
import json

def block_fingerprint(block):
    content = {key: value for key, value in block.items() if key != "fingerprint"}
    return hashlib.sha256(json.dumps(content, sort_keys=True).encode()).hexdigest()

def new_block(number, previous, timestamp, transactions):
    block = {"number": number, "previous": previous, "timestamp": timestamp, "transactions": transactions}
    block["fingerprint"] = block_fingerprint(block)
    return block

chain = [new_block(0, "0" * 64, "2026-01-05 09:00", ["colleagues' tontine created"])]
for timestamp, transactions in [
    ("2026-02-05 09:00", ["Kofi pays 20000", "Mei pays 20000", "Aicha pays 20000"]),
    ("2026-03-05 09:00", ["Yao pays 20000", "Kofi receives 80000"]),
]:
    previous = chain[-1]
    chain.append(new_block(previous["number"] + 1, previous["fingerprint"], timestamp, transactions))

for block in chain:
    print(f"block {block['number']} | prev. {block['previous'][:10]}… | {len(block['transactions'])} tx | {block['fingerprint'][:10]}…")
block 0 | prev. 0000000000… | 1 tx | ea93d36974…
block 1 | prev. ea93d36974… | 3 tx | 93b2abd9a5…
block 2 | prev. 93b2abd9a5… | 2 tx | a37c777c92…

Checking the whole chain

A participant who receives a copy of the chain trusts nothing: they recompute each fingerprint, check that each block points to the previous one, and that the numbers follow each other.

import hashlib
import json

def block_fingerprint(block):
    content = {k: v for k, v in block.items() if k != "fingerprint"}
    return hashlib.sha256(json.dumps(content, sort_keys=True).encode()).hexdigest()

def new_block(number, previous, timestamp, transactions):
    block = {"number": number, "previous": previous, "timestamp": timestamp, "transactions": transactions}
    block["fingerprint"] = block_fingerprint(block)
    return block

def check_chain(chain):
    for i, block in enumerate(chain):
        if block["number"] != i:
            return f"block {i}: wrong number"
        if block_fingerprint(block) != block["fingerprint"]:
            return f"block {i}: content modified"
        if i > 0 and block["previous"] != chain[i - 1]["fingerprint"]:
            return f"block {i}: link with block {i - 1} broken"
    return "valid chain"

chain = [new_block(0, "0" * 64, "2026-01-05 09:00", ["created"])]
chain.append(new_block(1, chain[0]["fingerprint"], "2026-02-05 09:00", ["Kofi pays 20000", "Mei pays 20000"]))
chain.append(new_block(2, chain[1]["fingerprint"], "2026-03-05 09:00", ["Kofi receives 40000"]))
print(check_chain(chain))

chain[1]["transactions"][1] = "Mei pays 2000"                     # tampering without recomputing
print(check_chain(chain))
chain[1]["fingerprint"] = block_fingerprint(chain[1])              # the fraudster recomputes block 1…
print(check_chain(chain))
valid chain
block 1: content modified
block 2: link with block 1 broken

The fraudster who recomputes block 1's fingerprint breaks the link with block 2: they must then recompute block 2, then 3… to the end of the chain. And every copy held by the other participants keeps the old version.

Mini-lab: your blockPython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: each member's balance

From a chain of the tontine's blocks, write a function balances(chain) that, only if the chain is valid, computes what each member has paid in (positive amounts for "pays", negative for "receives"). If the chain is not valid, it returns the error message. Transactions always have the form "Name pays 20000" or "Name receives 40000".

Hint 1
Split each transaction with name, action, amount = tx.split() then convert the amount with int(amount).
Hint 2
Use a dictionary balances.get(name, 0) + amount to accumulate, and call check_chain first.
Show the solution and common mistakes
import hashlib
import json

def block_fingerprint(block):
    content = {k: v for k, v in block.items() if k != "fingerprint"}
    return hashlib.sha256(json.dumps(content, sort_keys=True).encode()).hexdigest()

def new_block(number, previous, transactions):
    block = {"number": number, "previous": previous, "transactions": transactions}
    block["fingerprint"] = block_fingerprint(block)
    return block

def check_chain(chain):
    for i, block in enumerate(chain):
        if block["number"] != i or block_fingerprint(block) != block["fingerprint"]:
            return f"block {i} invalid"
        if i > 0 and block["previous"] != chain[i - 1]["fingerprint"]:
            return f"block {i}: broken link"
    return None

def balances(chain):
    error = check_chain(chain)
    if error:
        return error
    result = {}
    for block in chain[1:]:                         # the genesis block contains no movement
        for tx in block["transactions"]:
            name, action, amount = tx.split()
            sign = 1 if action == "pays" else -1
            result[name] = result.get(name, 0) + sign * int(amount)
    return result

chain = [new_block(0, "0" * 64, ["created"])]
for txs in (["Kofi pays 20000", "Mei pays 20000", "Yao pays 20000"],
            ["Mei receives 60000", "Kofi pays 20000", "Mei pays 20000", "Yao pays 20000"]):
    chain.append(new_block(len(chain), chain[-1]["fingerprint"], txs))

print(balances(chain))
chain[2]["transactions"][0] = "Mei receives 600000"
print(balances(chain))
{'Kofi': 40000, 'Mei': -20000, 'Yao': 40000}
block 2 invalid

Mei received the first round's pot (60,000) after paying in 40,000: the balance is −20,000, and Mei will keep contributing. As soon as a transaction is forged, the function refuses to compute.

Common mistakes:

  • Computing the balances before checking the chain: forged amounts would be displayed as if they were reliable.
  • Treating the genesis block's transaction ("created") as a payment: split() then returns a single word and the program crashes.
  • Adding strings instead of numbers: "20000" + "20000" gives "2000020000".

Summary

  1. 1A block groups several transactions with its number, a timestamp and the previous block's fingerprint.
  2. 2A block's fingerprint is computed on a canonical form of its content, always identical.
  3. 3Checking a chain means recomputing every fingerprint and checking every link and number.
  4. 4Without the previous block's fingerprint, blocks could be deleted or reordered unseen.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.