Show contents
Chapter 4 of 6 · 15 min
Proof of work
By the end of this chapter, you'll be able to
- Explain the principle of proof of work and the role of the nonce
- Program "mining" that looks for a fingerprint starting with zeros
- Measure the effect of difficulty on the number of attempts
- Explain why rewriting an old block becomes very expensive, and name the energy cost
A computing lottery
Rule of the game: a block is only accepted if its fingerprint starts with a certain number of zeros. Since the fingerprint is unpredictable, the only way to get there is to try: we add a nonce field to the block (a number we can change at will) and recompute the fingerprint, again and again, until we hit a fingerprint that fits. That is mining.
Finding takes long; checking is instant: a single fingerprint computation is enough to see that the block follows the rule. This asymmetry is the whole point of proof of work.
Anyone checks the block with a single computation, without redoing the attempts.
Text description of the animation
- The block's content is fixed; only the nonce will change.
- We start at 0 and add 1 at each attempt.
- Each attempt gives an unpredictable fingerprint.
- With three hexadecimal zeros required, it takes 4,096 attempts on average.
- Anyone checks the block with a single computation, without redoing the attempts.
import hashlib
import json
def fingerprint(block):
return hashlib.sha256(json.dumps(block, sort_keys=True).encode()).hexdigest()
def mine(block, difficulty):
"""Looks for a nonce such that the fingerprint starts with `difficulty` hexadecimal zeros."""
block = dict(block, nonce=0)
while not fingerprint(block).startswith("0" * difficulty):
block["nonce"] += 1
return block
block = {"number": 1, "previous": "0" * 64, "transactions": ["Kofi pays 20000", "Mei pays 20000"]}
for difficulty in range(1, 5):
mined = mine(block, difficulty)
print(f"{difficulty} zero(s): nonce = {mined['nonce']:>6}, fingerprint = {fingerprint(mined)[:16]}…")
1 zero(s): nonce = 10, fingerprint = 0f8572c4d5b8287c…
2 zero(s): nonce = 171, fingerprint = 0026211fa07919f2…
3 zero(s): nonce = 1631, fingerprint = 000fa5d93403a0ff…
4 zero(s): nonce = 121468, fingerprint = 0000172be84c506e…
Each extra hexadecimal zero multiplies the average work by 16. Bitcoin adjusts its difficulty every 2,016 blocks so that a block is found about every 10 minutes, whatever the network's total power. In 2024, that represented on the order of hundreds of billions of billions of attempts per second, across all miners.
Why rewriting history becomes prohibitively expensive
The miner who finds a block receives a reward (new units of the currency and fees): that is what motivates the work. And the rule for honest participants is simple: they follow the chain that required the most work in total.
To modify a transaction from 6 blocks ago, a fraudster must re-mine that block and the 5 following ones, then catch up with and overtake the honest chain, which keeps moving forward in the meantime. With less than half of the network's computing power, the fraudster falls behind on average, and the chances of success drop very fast with the number of blocks to catch up.
# Probability that a fraudster ever catches up with the honest chain from z blocks behind
# ("gambler's ruin" reasoning: (q/p)^z if q < p).
for fraudster_share in (0.10, 0.30, 0.45):
p, q = 1 - fraudster_share, fraudster_share
chances = [(q / p) ** z for z in (1, 6, 20)]
print(f"fraudster at {fraudster_share:.0%}: " + " ".join(f"{z} blocks → {c:.4%}" for z, c in zip((1, 6, 20), chances)))
fraudster at 10%: 1 blocks → 11.1111% 6 blocks → 0.0002% 20 blocks → 0.0000%
fraudster at 30%: 1 blocks → 42.8571% 6 blocks → 0.6196% 20 blocks → 0.0000%
fraudster at 45%: 1 blocks → 81.8182% 6 blocks → 29.9985% 20 blocks → 1.8072%
Hence the practical rule of waiting for several confirmations (blocks added after the transaction's block) before treating a payment as final. But if one actor controls more than half of the computing power, they can rewrite recent history: that is the 51% attack, which has already hit small blockchains.
The price of this security is energy: all these attempts consume a lot of electricity, comparable to that of whole countries for Bitcoin. That is why other blockchains, such as Ethereum since 2022, use proof of stake: the right to propose a block depends on the funds each participant locks up as collateral, not on computation. This mechanism is studied in a more advanced course.
Mini-lab: difficultyPython 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
Your turn
Worked exercise
Worked exercise: a small mined chain
Write a program that mines a chain of 3 blocks (in addition to the genesis block) with a difficulty of 3, each block containing the previous one's fingerprint. Then write check(chain, difficulty) that checks the links and that each fingerprint really starts with the required number of zeros. Test it on the honest chain, then after modifying a transaction of block 2 and recomputing its fingerprint without re-mining.
Hint 1
block["fingerprint"] = fingerprint(block), and remove it before recomputing during the check.Hint 2
previous equal to the previous block's fingerprint.Show the solution and common mistakes
import hashlib
import json
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, difficulty):
block = dict(block, nonce=0)
while not fingerprint(block).startswith("0" * difficulty):
block["nonce"] += 1
block["fingerprint"] = fingerprint(block)
return block
def check(chain, difficulty):
for i, block in enumerate(chain):
if fingerprint(block) != block["fingerprint"]:
return f"block {i}: wrong fingerprint"
if i > 0 and not block["fingerprint"].startswith("0" * difficulty):
return f"block {i}: no proof of work"
if i > 0 and block["previous"] != chain[i - 1]["fingerprint"]:
return f"block {i}: broken link"
return "valid chain"
D = 3
chain = [{"number": 0, "previous": "0" * 64, "transactions": ["created"]}]
chain[0]["fingerprint"] = fingerprint(chain[0])
for txs in (["Kofi pays 20000"], ["Mei pays 20000", "Yao pays 20000"], ["Kofi receives 60000"]):
chain.append(mine({"number": len(chain), "previous": chain[-1]["fingerprint"], "transactions": txs}, D))
for b in chain[1:]:
print(f"block {b['number']}: nonce {b['nonce']:>5}, {b['fingerprint'][:12]}…")
print(check(chain, D))
chain[2]["transactions"][0] = "Mei pays 2000"
chain[2]["fingerprint"] = fingerprint(chain[2]) # recomputed, but not re-mined
print(check(chain, D))
block 1: nonce 456, 0008460dd1f3…
block 2: nonce 2498, 00008da4f66d…
block 3: nonce 7972, 000ccf2260ba…
valid chain
block 2: no proof of work
The fraudster who recomputes the fingerprint without re-mining gets a fingerprint that does not start with three zeros: refused. To be accepted, they would have to re-mine block 2 and block 3, then go faster than the whole network.
Common mistakes:
- Including the
fingerprintfield in the fingerprint computation: the value changes as soon as it is written, and the check always fails. - Forgetting to check the proof of work: a fraudster could then make blocks for free.
- Requiring proof of work for the genesis block, which was not mined in this example.
Summary
- 1Proof of work requires finding a nonce that gives a fingerprint starting with zeros: long to find, instant to check.
- 2Each extra hexadecimal zero multiplies the average work by 16; the network adjusts the difficulty.
- 3Rewriting an old block means re-mining all the following ones faster than the network: hence waiting for several confirmations.
- 4A blockchain prevents recorded data from being changed, but does not guarantee it was true.
- 5Proof of work consumes a lot of energy; proof of stake is an alternative.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.