We can build a chain and tamper with it. Today we write the code that catches the tampering — is_valid_chain().
Every block's stored hash must equal what we get when we recalculate it right now. If even one character of the block was changed after it was created, the hash won't match.
Every block's previous_hash must equal the actual hash of the block that came before it. This proves the blocks are in the correct order and none have been inserted or swapped.
def is_valid_chain(chain):
for i in range(len(chain)):
block = chain[i]
# Check 1: stored hash must match recalculated hash
if block["hash"] != hash_block(block):
print(f"Block {i}: hash is invalid!")
return False
# Check 2: previous_hash must match prior block's hash
if i > 0: # skip genesis block
if block["previous_hash"] != chain[i - 1]["hash"]:
print(f"Block {i}: link is broken!")
return False
return True # all checks passed
chain = build_chain()
print(is_valid_chain(chain)) # Truechain = build_chain()
print("Before tamper:", is_valid_chain(chain)) # True
# Secretly change block 1's data
chain[1]["data"] = "Alice sends 9999 DOT to Bob"
print("After tamper:", is_valid_chain(chain))
# Block 1: hash is invalid!
# False
# What about recalculating the hash too?
chain[1]["hash"] = hash_block(chain[1]) # update block 1's hash
print("After hash fix:", is_valid_chain(chain))
# Block 2: link is broken!
# False — block 2 still stores the OLD hash of block 1We check: (1) hash integrity, (2) chain link. Runs in milliseconds on a laptop. Great for understanding the concept.
Also check: digital signatures on every extrinsic (transaction), account balances, runtime logic, state transitions. The concept is the same; the implementation is vastly more complex.
SHA-256 fingerprint of any block's fields.
Creates and links blocks.
Verifies every hash and link.
Instead of returning True/False, return a list of error messages. For each invalid block, include: block index, which check failed, and the two hash values that don't match.