Show contents
Chapter 5 of 6 · 20 min
Project: the tontine ledger
By the end of this chapter, you'll be able to
- Assemble blocks, chaining and proof of work into a complete ledger
- Check the tontine's business rules in addition to the chain's integrity
- Determine the next beneficiary from the history
- Apply a decision grid to know whether a project needs a blockchain
The tontine's ledger
We also check the tontine's rules, not just the fingerprints.
Text description of the animation
- The month's contributions are collected.
- The beneficiary is the first member, in the agreed order, who has not yet received the pot.
- The block is mined and linked to the previous one.
- Each member keeps the chain; comparing the last fingerprint is enough to know whether the copies agree.
- We also check the tontine's rules, not just the fingerprints.
import hashlib
import json
MEMBERS = ["Awa", "Kofi", "Mei", "Yao"]
CONTRIBUTION, DIFFICULTY = 20000, 3
def 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 mine(block):
block = dict(block, nonce=0)
while not fingerprint(block).startswith("0" * DIFFICULTY):
block["nonce"] += 1
block["fingerprint"] = fingerprint(block)
return block
def add_month(chain, month, beneficiary):
contributions = [{"from": m, "amount": CONTRIBUTION} for m in MEMBERS]
payout = {"to": beneficiary, "amount": CONTRIBUTION * len(MEMBERS)}
block = {"number": len(chain), "previous": chain[-1]["fingerprint"], "month": month,
"contributions": contributions, "payout": payout}
chain.append(mine(block))
genesis = {"number": 0, "previous": "0" * 64, "month": "created", "rule": "order " + ", ".join(MEMBERS)}
genesis["fingerprint"] = fingerprint(genesis)
chain = [genesis]
for month, beneficiary in [("2026-01", "Awa"), ("2026-02", "Kofi")]:
add_month(chain, month, beneficiary)
for b in chain[1:]:
print(f"{b['month']}: {b['payout']['to']} receives {b['payout']['amount']} | nonce {b['nonce']} | {b['fingerprint'][:10]}…")
2026-01: Awa receives 80000 | nonce 581 | 0001257c90…
2026-02: Kofi receives 80000 | nonce 1822 | 0002f8a0b6…
The chain's integrity is not enough: the tontine's rules must also be checked. Each block must contain a contribution from every member, and the pot must equal the sum of the contributions.
import hashlib
import json
MEMBERS = ["Awa", "Kofi", "Mei", "Yao"]
CONTRIBUTION, DIFFICULTY = 20000, 3
def 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 mine(block):
block = dict(block, nonce=0)
while not fingerprint(block).startswith("0" * DIFFICULTY):
block["nonce"] += 1
block["fingerprint"] = fingerprint(block)
return block
def month_block(chain, month, beneficiary, contributors):
return mine({"number": len(chain), "previous": chain[-1]["fingerprint"], "month": month,
"contributions": [{"from": m, "amount": CONTRIBUTION} for m in contributors],
"payout": {"to": beneficiary, "amount": CONTRIBUTION * len(contributors)}})
def check(chain):
for i, b in enumerate(chain):
if fingerprint(b) != b["fingerprint"]:
return f"block {i}: wrong fingerprint"
if i == 0:
continue
if b["previous"] != chain[i - 1]["fingerprint"] or not b["fingerprint"].startswith("0" * DIFFICULTY):
return f"block {i}: invalid link or proof of work"
if sorted(c["from"] for c in b["contributions"]) != sorted(MEMBERS):
return f"block {i} ({b['month']}): incomplete contributions"
if b["payout"]["amount"] != sum(c["amount"] for c in b["contributions"]):
return f"block {i} ({b['month']}): wrong pot"
return "valid ledger"
genesis = {"number": 0, "previous": "0" * 64, "month": "created"}
genesis["fingerprint"] = fingerprint(genesis)
chain = [genesis]
chain.append(month_block(chain, "2026-01", "Awa", MEMBERS))
print(check(chain))
chain.append(month_block(chain, "2026-02", "Kofi", ["Awa", "Kofi", "Mei"])) # Yao did not contribute
print(check(chain))
valid ledger
block 2 (2026-02): incomplete contributions
February's block is perfectly mined and chained… but it breaks a rule: the check refuses it anyway. A real blockchain works this way: every participant applies the same validation rules, and refuses blocks that do not follow them, even if they required a lot of work.
Mini-lab: each member's copyPython 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
Do you really need a blockchain?
A blockchain provides a ledger that several parties who do not trust each other can keep together, without an intermediary, and that remains checkable by all. It also has costs: slowness, energy or complexity, data that is hard to correct (even in the case of a legitimate error), and no guarantee about the truth of the information entered. A grid of questions helps decide.
Your turn
Worked exercise
Project: the next beneficiary
Write a function next_beneficiary(chain, members) that, if the ledger is valid, returns the first member of the list (in the agreed order) who has never received the pot yet, or "cycle complete" if everyone has received it. If the ledger is invalid, it returns the error message. Build a two-month ledger (Awa then Kofi), call the function, add the following months until the end of the cycle, then test a forged ledger.
Hint 1
{b["payout"]["to"] for b in chain[1:]}.Hint 2
members in order and return the first one who is not in that set.Show the solution and common mistakes
import hashlib
import json
MEMBERS = ["Awa", "Kofi", "Mei", "Yao"]
CONTRIBUTION, DIFFICULTY = 20000, 2
def 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 mine(block):
block = dict(block, nonce=0)
while not fingerprint(block).startswith("0" * DIFFICULTY):
block["nonce"] += 1
block["fingerprint"] = fingerprint(block)
return block
def add_month(chain, month, beneficiary):
chain.append(mine({"number": len(chain), "previous": chain[-1]["fingerprint"], "month": month,
"contributions": [{"from": m, "amount": CONTRIBUTION} for m in MEMBERS],
"payout": {"to": beneficiary, "amount": CONTRIBUTION * len(MEMBERS)}}))
def check(chain):
for i, b in enumerate(chain):
if fingerprint(b) != b["fingerprint"]:
return f"block {i}: wrong fingerprint"
if i and (b["previous"] != chain[i - 1]["fingerprint"] or not b["fingerprint"].startswith("0" * DIFFICULTY)):
return f"block {i}: invalid link or proof of work"
return None
def next_beneficiary(chain, members):
error = check(chain)
if error:
return error
already = {b["payout"]["to"] for b in chain[1:]}
return next((m for m in members if m not in already), "cycle complete")
genesis = {"number": 0, "previous": "0" * 64, "month": "created"}
genesis["fingerprint"] = fingerprint(genesis)
chain = [genesis]
add_month(chain, "2026-01", "Awa")
add_month(chain, "2026-02", "Kofi")
print("March:", next_beneficiary(chain, MEMBERS))
add_month(chain, "2026-03", "Mei")
add_month(chain, "2026-04", "Yao")
print("May :", next_beneficiary(chain, MEMBERS))
chain[1]["payout"]["to"] = "Yao" # someone rewrites January for their own benefit
print("forged:", next_beneficiary(chain, MEMBERS))
March: Mei
May : cycle complete
forged: block 1: wrong fingerprint
The function reads the checked history to decide: impossible to pass yourself off as a member who has not yet received by rewriting an old month, because the modified block no longer matches its fingerprint.
Common mistakes:
- Choosing the beneficiary with a
setwithout respecting the agreed order: the order of a set is not guaranteed. - Reading
chain[0]["payout"]: the genesis block has no payout, which raises aKeyError. - Choosing the beneficiary without checking the chain first: a forged history would change the result.
Summary
- 1A complete ledger combines chained blocks, proof of work and a copy for each participant.
- 2Every participant applies the same business validation rules, in addition to the fingerprint checks.
- 3Decisions (such as the next beneficiary) are made from the checked history.
- 4A blockchain is only useful if several parties without mutual trust must write without an intermediary; otherwise, a simpler tool fits better.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.