Skip to content
KALANBLON
Show contents

Chapter 1 of 6 · 15 min

The shared ledger problem

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

  • Describe the problem of a ledger kept by a single person
  • Explain the idea of a ledger copied by every participant
  • Seal each line to the previous one with a SHA-256 fingerprint
  • Detect a change in a chained ledger

One ledger, several problems

A ledger is a list of operations, in order: "Kofi paid 20,000", "Mei received 200,000". When a single person keeps it, three problems arise:

  • that person can modify a past line without anyone noticing;
  • if the notebook is lost (or the computer breaks down), everything disappears;
  • everyone must trust that person, even when they are unavailable.

First idea: everyone keeps a copy of the ledger. If someone modifies theirs, the other copies contradict it. But if the copies diverge, which one is right? And how do you easily spot which line was changed? For that, we will seal the lines together.

Sealing each line to the previous one

You know the SHA-256 fingerprint: it changes completely as soon as one character changes. The blockchain trick is to include, in each line, the fingerprint of the previous line. That way, each line "seals" the whole history before it: modifying an old line changes its fingerprint, so the next line no longer matches, and so on to the end.

Line 2 no longer matches: the tampering is spotted, at the exact place.

Step 5 of 5
Text description of the animation
  1. The first line has no previous one: we put zeros.
  2. Line 1 contains the fingerprint of line 0.
  3. Line 2 contains the fingerprint of line 1.
  4. Someone reduces Mei's payment: the fingerprint of line 1 changes completely.
  5. Line 2 no longer matches: the tampering is spotted, at the exact place.
import hashlib

def fingerprint(text):
    return hashlib.sha256(text.encode()).hexdigest()[:12]   # 12 characters are enough for display

ledger = []
previous = "0" * 12
for operation in ["Kofi pays 20000", "Mei pays 20000", "Aicha pays 20000", "Mei receives 60000"]:
    line = {"operation": operation, "previous": previous}
    line["fingerprint"] = fingerprint(line["operation"] + line["previous"])
    ledger.append(line)
    previous = line["fingerprint"]

for i, line in enumerate(ledger):
    print(i, line["operation"].ljust(19), "prev.", line["previous"], "→", line["fingerprint"])
0 Kofi pays 20000     prev. 000000000000 → c4c1b95a5c9e
1 Mei pays 20000      prev. c4c1b95a5c9e → d87883b59712
2 Aicha pays 20000    prev. d87883b59712 → 03da90048924
3 Mei receives 60000  prev. 03da90048924 → fdd70f1dc16e

Each line starts with the fingerprint of the one before: it is a chain. To check the ledger, we recompute each fingerprint and check each link.

import hashlib

def fingerprint(text):
    return hashlib.sha256(text.encode()).hexdigest()[:12]

def build(operations):
    ledger, previous = [], "0" * 12
    for op in operations:
        line = {"operation": op, "previous": previous, "fingerprint": fingerprint(op + previous)}
        ledger.append(line)
        previous = line["fingerprint"]
    return ledger

def check(ledger):
    previous = "0" * 12
    for i, line in enumerate(ledger):
        if line["previous"] != previous:
            return f"broken link before line {i}"
        if fingerprint(line["operation"] + line["previous"]) != line["fingerprint"]:
            return f"line {i} modified"
        previous = line["fingerprint"]
    return "ledger intact"

ledger = build(["Kofi pays 20000", "Mei pays 20000", "Aicha pays 20000", "Mei receives 60000"])
print(check(ledger))

ledger[1]["operation"] = "Mei pays 2000"              # someone "corrects" a line
print(check(ledger))
ledger intact
line 1 modified

Mini-lab: try to cheatPython 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: comparing two copies

Kofi and Mei each have a copy of the tontine's ledger. Write a function first_difference(copy_a, copy_b) that returns the index of the first line whose fingerprints differ, or None if both copies are identical. Test it with two identical copies, then with a copy where line 2 was modified.

Hint 1
Go through both copies at once with zip and enumerate, and compare line_a["fingerprint"] and line_b["fingerprint"].
Hint 2
Thanks to chaining, as soon as one fingerprint differs, all the following ones differ too: the first difference shows where to look.
Show the solution and common mistakes
import hashlib

def fingerprint(text):
    return hashlib.sha256(text.encode()).hexdigest()[:12]

def build(operations):
    ledger, previous = [], "0" * 12
    for op in operations:
        line = {"operation": op, "previous": previous, "fingerprint": fingerprint(op + previous)}
        ledger.append(line)
        previous = line["fingerprint"]
    return ledger

def first_difference(copy_a, copy_b):
    for i, (a, b) in enumerate(zip(copy_a, copy_b)):
        if a["fingerprint"] != b["fingerprint"]:
            return i
    return None

operations = ["Kofi pays 20000", "Mei pays 20000", "Aicha pays 20000", "Yao pays 20000"]
kofi_copy = build(operations)
mei_copy = build(operations)
print("identical copies:", first_difference(kofi_copy, mei_copy))

modified = operations.copy()
modified[2] = "Aicha pays 2000"
print("modified copy   :", first_difference(kofi_copy, build(modified)))
identical copies: None
modified copy   : 2

The function finds line 2, exactly where history was changed. With chaining, comparing the last fingerprint is even enough to know whether two copies are identical, without rereading everything.

Common mistakes:

  • Comparing the operations instead of the fingerprints: you miss a change in the previous field.
  • Forgetting that one copy may be shorter than the other: zip stops at the shorter one, so the lengths must be compared too.
  • Building the second copy from the first list modified in place: both copies are then the same list in memory.

Summary

  1. 1A ledger kept by a single person can be modified or lost, and forces everyone to trust that person.
  2. 2In a chained ledger, each line contains the fingerprint of the previous one: a change breaks all the following links.
  3. 3Recomputing the whole chain is easy: it only protects if others keep an independent copy.
  4. 4Comparing the last fingerprint of two copies is enough to know whether they tell the same story.

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