Algorithms · Safety nets

Proof of work

Bitcoin’s puzzle: making cheating too expensive. Anyone can add a page to the ledger, but only after solving a lottery that takes real work.

The problem

Picture a shared ledger with no bank in charge: "Alice pays Bob 5", "Bob pays Cy 2". Thousands of strangers keep copies. Anyone can offer a new page of transactions, and some of them would love to quietly edit an old page.

The 2008 whitepaper by Satoshi Nakamoto asks: how can strangers agree on one history, when lying is easy and nobody can be trusted? The answer is to make rewriting the past absurdly expensive.

The obvious way

Just trust whoever writes the next page first, and link pages together so edits are noticeable. The flaw: if linking is free, a cheater edits page 1, recomputes the links for every later page in a blink, and hands you a perfectly consistent fake history. Nothing slowed them down.

The clever idea

Think of a lottery where buying tickets is the only way to win. To add a page, a miner must find a lucky number, called a nonce, that makes the page's fingerprint start with enough zeros. That is proof of work: finding the number takes many tries, but checking it takes one.

Each block also contains the previous block's SHA-256 hash, so blocks form a chain. Change an old block and its hash changes, which breaks every later link. Rewriting history means redoing all that work. The network even adjusts difficulty every 2016 blocks to aim for about ten minutes per block.

How the code does it

The mining loop is the whole trick: bump the nonce, hash again, stop when the hash starts with K zeros. The first chart shows each extra zero makes mining cost far more tries. Meanwhile this line chains each block to the one before it.

After we edit block 1, the check flags the damaged blocks, because the edited hash no longer matches or no longer has its zeros. To hide it, a cheater must redo blocks 1 to 3. The two rewrites show the gap: with K=0 it costs 3 tries, with real work it costs thousands.

Trade-offs

The price of security is wasted effort: honest miners also burn many tries for every block they add, and the difficulty must be retuned (every 2016 blocks in Bitcoin) to keep the pace steady. If everyone already trusts one organization, a plain database is simpler and far faster. Proof of work earns its cost only when strangers must agree without a referee.

Where else you'll see it

Any system where a cheap check protects against an expensive forgery uses the same shape. The real thing lives in the open-source repository at github.com/bitcoin/bitcoin, where you can read how Bitcoin validates blocks.

Someone edits block 1 of a 4-block chain. What must they redo to make the chain valid again?

  • Only block 1
  • Blocks 1, 2 and 3, mining each one
  • Nothing, hashes fix themselves
Show the answer

Blocks 1, 2 and 3, mining each one. Block 1's hash changes, so block 2's stored previous-hash is wrong; re-mining block 2 changes its hash, which breaks block 3, and so on.

Change it and see
  • Change the 3 in build to 2
  • Tamper with block 2 instead
  • Add a fifth transaction to words

The code

Python, with what each line means beside it. It compares the clever way with trusting whoever writes first.

import hashlibLoad the SHA-256 hashing tool
def digest(b):Define a block's fingerprint function
return hashlib.sha256(f"{b['data']}|{b['prev']}|{b['nonce']}".encode()).hexdigest()Mix data, previous hash, nonce; hash them
def mine(data, prev, k):Define mining for a block
block, tries = {"data": data, "prev": prev, "nonce": 0}, 1Start a block at nonce zero, one try
while not digest(block).startswith("0" * k):Until the hash starts with K zeros,
block["nonce"] += 1bump the nonce
tries += 1and count another try
return block, triesReturn the winning block and its tries
def build(datas, k):Define building a whole chain
chain, prev, tries = [], "0" * 64, 0Start empty, with an all-zero previous hash
for d in datas:For each piece of data,
block, t = mine(d, prev, k)mine a block for it
chain.append(block)add it to the chain
prev, tries = digest(block), tries + tremember its hash as the next link
return chain, triesReturn the chain and total tries
def check(chain, k):Define checking a chain
rows = {}Prepare an empty results table
for i, b in enumerate(chain):Walk through every block
linked = i == 0 or b["prev"] == digest(chain[i - 1])Link is good if it matches the prior hash
worked = digest(b).startswith("0" * k)Work is good if the hash has K zeros
rows[f"block {i}"] = "valid" if linked and worked else "BROKEN"Mark valid only if both hold
return rowsReturn the table
words = ["Alice pays Bob 5", "Bob pays Cy 2", "Cy pays Dee 1", "Dee pays Al 1"]Four tiny transactions
show([build(words, k)[1] for k in (1, 2, 3, 4)], "tries to mine 4 blocks, K = 1..4")Chart tries needed for K = 1 to 4
chain, _ = build(words, 3)Build a real chain with K = 3
chain[1]["data"] = "Bob pays Cy 200"Secretly edit block 1's data
show(check(chain, 3), "block links after tampering")Show which links survived
_, obvious = build(words[1:], 0)Cheater redoes blocks 1-3 with no work
_, clever = build(words[1:], 3)Cheater redoes blocks 1-3 with real work
show([obvious, clever], "cost to rewrite blocks 1-3: no work vs work")Chart the two costs side by side

Read more

Run it. Then change it.

The code runs right in the page and draws as it goes. Free, nothing to install.

More on safety nets