Linking blocks — and breaking them
We have a block. Today we chain them together — and then deliberately tamper with one to see the chain shatter.
Every block stores the hash of the block before it in a field called previous_hash. This single rule creates the unbreakable link.
def build_chain():
chain = []
# Block 0 — genesis
genesis = make_block(0, "Genesis Block", "0" * 64)
chain.append(genesis)
# Block 1 — points to genesis
block1 = make_block(1, "Alice sends 10 DOT to Bob",
previous_hash=chain[-1]["hash"])
chain.append(block1)
# Block 2 — points to block 1
block2 = make_block(2, "Bob sends 4 DOT to Carol",
previous_hash=chain[-1]["hash"])
chain.append(block2)
return chain
chain = build_chain()
for b in chain:
print(b["index"], b["hash"][:12], b["previous_hash"][:12])chain = build_chain()
# Secretly change Block 1's data
chain[1]["data"] = "Alice sends 1000 DOT to Bob" # TAMPER!
# Now check: does Block 1's hash still match?
print("Block 1 hash (stored) :", chain[1]["hash"][:20])
print("Block 1 hash (recalc) :", hash_block(chain[1])[:20])
# These two are different! Block 1 has been tampered with.
# And Block 2's link is now broken too:
print("Block 2 expects prev :", chain[2]["previous_hash"][:20])
print("Block 1 hash now is :", chain[1]["hash"][:20])
# Also different — the chain is invalid.Every Polkadot block contains the hash of its parent block in the parent_hash field. This is visible on every block on Subscan. The chain of 22+ million blocks all link back to block 0.
In Polkadot, validators don't just trust the previous hash — they run complex state transition checks. But the core principle is the same: verify the link, detect any tampering.
Go to subscan.io right now → click any block → look at the "Parent Hash" field. That value matches the "Hash" of the block numbered one less. Same chain, production scale.
def add_block(chain, data):
previous_hash = chain[-1]["hash"]
index = len(chain)
new_block = make_block(index, data, previous_hash)
chain.append(new_block)
return new_block
# Usage:
chain = [make_block(0, "Genesis Block", "0" * 64)]
add_block(chain, "Alice → Bob: 10 DOT")
add_block(chain, "Bob → Carol: 4 DOT")
add_block(chain, "Carol → Alice: 2 DOT")
print(f"Chain length: {len(chain)} blocks")Linked chain
Write add_block() and use it to build a chain of at least 3 blocks (genesis + 2 transactions). Print the index, hash (first 16 chars), and previous_hash (first 16 chars) of each block.
Tamper and detect
After building the chain, manually change the data in block 1. Print the stored hash vs the recalculated hash and show they differ. Extra: add an is_tampered(block) function.