- Recalculate block 5's hash to meet the difficulty target — costs lots of work.
- Recalculate block 6, 7, 8... all the way to block 1000 — each costs work.
- Do all this faster than the whole honest network is adding new blocks.
Our chain is tamper-detectable. But detecting tampering isn't enough — we need it to be too costly to tamper. Today: Proof of Work.
Nobody owns the blockchain. There's no boss. Thousands of computers all want to add the next block. If it's free to add a block, anyone can spam the chain with fake transactions.
A nonce is just a number we add to the block. We keep changing it until the block's hash starts with enough zeros — that's the "difficulty target."
import hashlib
def hash_with_nonce(data, nonce):
content = data + str(nonce)
return hashlib.sha256(content.encode()).hexdigest()
# Try different nonces:
print(hash_with_nonce("block data", 0))
# → 5d7b9a... (doesn't start with 0)
print(hash_with_nonce("block data", 1))
# → a3c21f... (doesn't start with 0)
print(hash_with_nonce("block data", 42))
# → 0c74bd... (starts with 0 — with difficulty=1 this is valid!)def mine_block(index, data, previous_hash, difficulty=3):
target = "0" * difficulty # e.g. "000" for difficulty 3
nonce = 0
while True:
block = {
"index": index,
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
"data": data,
"previous_hash": previous_hash,
"nonce": nonce,
"hash": "",
}
block["hash"] = hash_block(block)
if block["hash"].startswith(target):
print(f"Mined! nonce={nonce}, hash={block['hash'][:16]}...")
return block
nonce += 1
# Mine a block:
b = mine_block(1, "Alice → Bob: 10 DOT", "0" * 64, difficulty=3)Takes 1–16 guesses on average. Instant.
Takes ~65,536 guesses on average. A few seconds.
Takes ~16 million guesses. Minutes on a laptop.
def is_valid_chain(chain, difficulty=3):
target = "0" * difficulty
for i, block in enumerate(chain):
# Check 1: hash integrity
if block["hash"] != hash_block(block):
return False, f"Block {i}: hash invalid"
# Check 2: proof of work
if not block["hash"].startswith(target):
return False, f"Block {i}: insufficient proof of work"
# Check 3: chain link
if i > 0 and block["previous_hash"] != chain[i-1]["hash"]:
return False, f"Block {i}: broken link"
return True, "Chain is valid"Mine the same block at difficulty 1, 2, 3, and 4. Record how many nonce attempts each took. Print a simple table comparing them.