Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 41 ยท Building a Toy Blockchain

Proof of Work and Mining

Learn how proof of work turns hashing into a cost: leading-zero difficulty, nonce search, the probability maths and the energy trade-off, with live Python.

A chain of hashes is easy to forge on its own. Anyone can rewrite a block, recompute every hash after it and present the result as the truth, because hashing is cheap. To stop that, a public blockchain makes adding a block expensive, so that rewriting history costs more than anybody can afford. That requirement is called proof of work, and the people who spend the effort are called miners.

In this lesson you will build the miner for your toy chain. You will search for a nonce, see why the number of attempts is random but predictable on average, check a block's work in a single hash, and put rough numbers on what the work costs. The block and chain code from Designing a Block and Building and Validating the Chain plugs straight into what you write here, and the hashing basics are in Cryptographic Hash Functions.

The puzzle: find a hash that starts with zeros

A proof-of-work puzzle has three properties. It is hard to solve, because the only known method is trial and error. It is easy to check, because verifying a claimed solution takes one hash. And it is tunable, so the network can make it harder or easier.

The classic puzzle is this: take the block's data, add a number called the nonce ("number used once"), hash the pair, and keep changing the nonce until the digest starts with a required number of zeros. Because SHA-256 output looks random, the only way to land on a hash with leading zeros is to try nonce after nonce until you get lucky.

Python Mine a block at four difficulties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The output is:

TEXT
difficulty 1: nonce=    13  hash=07b9bb5b2f31c9019921...
difficulty 2: nonce=   110  hash=00092fd2da374503c312...
difficulty 3: nonce=   110  hash=00092fd2da374503c312...
difficulty 4: nonce= 66854  hash=0000f5ff42e6c5dd4ad5...

Notice two things. The nonce for difficulty 4 is far bigger than for difficulty 1. And difficulties 2 and 3 found the same nonce: hash number 110 happened to start with three zeros, which also satisfies the weaker two-zero rule. Nothing wrong there. A smaller difficulty just accepts everything a larger one accepts.

flowchart LR
    A["Block data"] --> B["Add nonce"]
    B --> C["SHA-256"]
    C --> D{"Starts with<br/>enough zeros?"}
    D -- "no" --> E["nonce + 1"]
    E --> B
    D -- "yes" --> F["Block found"]

Mining is a loop: change the nonce, hash, test, repeat until the digest meets the difficulty.

Why the number of attempts is predictable

Each hex digit of a SHA-256 digest is effectively random, with 16 possible values. The chance that a digest starts with one particular digit (say 0) is 1 in 16. For d leading zeros the chance is 1 / 16**d. Every attempt is an independent trial with that fixed chance, which makes the number of attempts follow a geometric distribution:

  • The expected number of attempts is 16**d.
  • The spread is huge: sometimes you are lucky and finish in a handful of tries, sometimes you need several times the average.
  • Past failures don't help. After 60,000 failed attempts the next try still has the same tiny chance. This "memorylessness" is what makes mining a lottery rather than a race with a predictable finish.

Let's check the theory by mining 40 different blocks at each difficulty.

Python Average attempts match 16 to the power d

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A real run prints:

TEXT
difficulty 1: expected     16  mean      14.8  min     1  max     58
difficulty 2: expected    256  mean     260.4  min     3  max   1457
difficulty 3: expected   4096  mean    4488.7  min   162  max  26877
difficulty 4: expected  65536  mean   64491.1  min  1255  max 351295

The means land close to 16**d, but look at the extremes. At difficulty 4 the luckiest block took 1,255 attempts while the unluckiest took more than 351,000. A miner has no way to know which kind of block it is working on. This randomness is a feature: it means no miner can be sure of winning the next block without having a large share of the total effort.

If you want the chance of finishing within n attempts, it is 1 - (1 - p)**n where p = 1 / 16**d. After 16**d attempts you have only a 63 percent chance of having succeeded, not 100 percent.

A finer dial: the numeric target

Counting leading hex zeros is a coarse dial. Each step multiplies the work by 16. Real chains treat the digest as one huge number and require it to be below a target. Lowering the target a little makes the puzzle a little harder, so the difficulty can move smoothly.

If the target is 2**(256 - bits), a hash qualifies when its first bits bits are zero. Each extra bit doubles the expected work.

Python Mining against a numeric target

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The output:

TEXT
 8 bits: expected ~   256 tries, nonce found    113, hash < target: True, leading zero bits: 8
10 bits: expected ~  1024 tries, nonce found    228, hash < target: True, leading zero bits: 11
12 bits: expected ~  4096 tries, nonce found  13162, hash < target: True, leading zero bits: 15
14 bits: expected ~ 16384 tries, nonce found  13162, hash < target: True, leading zero bits: 15
16 bits: expected ~ 65536 tries, nonce found  30803, hash < target: True, leading zero bits: 17

The 12-bit and 14-bit searches stopped at the same nonce because that hash had 15 leading zero bits, enough for both. Bitcoin stores its target in a compact field in the block header and compares the 256-bit hash with it exactly as this code does. How the network chooses the target is the subject of Difficulty Adjustment and Block Time.

The bit counts above are tiny on purpose, so they run in a browser in seconds. A real network runs at a level where the expected work is a number with more than 20 digits, found by specialised hardware computing trillions of hashes per second.

Checking is cheap, redoing is expensive

Work is only useful if everybody else can verify it quickly. Verifying a block means hashing it once with its stored nonce and testing the result. Forging a block means redoing the whole search.

Python Verify in one hash, forge in tens of thousands

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

You should see:

TEXT
mined: 58745 000025c0c196e358
verify honest: True
verify edited: False
redo work: 79908

Changing 2 to 200 invalidates the old nonce, so the forger has to search again (79,908 attempts here, against 58,745 for the honest miner). On a chain, the forger must do this for the edited block and for every later block, because each stores the previous hash. And while they redo the work, the honest network keeps adding new blocks. Rewriting history therefore only works for an attacker who commands a large share of all the mining power in the world, an idea you will make precise in Longest Chain Rule, Forks and Reorgs.

Mining rewards and fees

Why would anyone spend electricity on this? Because the winner of a block is paid. A special first transaction in the block, the coinbase, creates new coins for the miner, and the miner also collects the fees of the transactions it includes (see Transactions and the Mempool). Mining is a business: income is the reward, cost is hardware and power. Competition pushes miners to spend roughly what the reward is worth.

That is also the reason difficulty must adapt. If hardware gets faster or more miners join, blocks would arrive sooner unless the puzzle gets harder.

The energy trade-off

Proof of work buys security with real-world cost, and that cost is an ongoing electricity bill. The more the block reward is worth, the more power miners burn, and the more expensive an attack becomes. This is the central trade-off:

  • For: security rests on physics and money, not on trusting any identity. Anyone can join mining without permission.
  • Against: the energy use is large, mining tends to concentrate in cheap-power regions and in groups of professional operators, and throughput is limited by the block interval.

A tiny model shows how the maths of cost works. The numbers below are made up for illustration; they are not measurements of any real network.

Python A cost model with assumed numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The output is:

TEXT
expected hashes per block: 1,208,925,819,614,629,174,706,176
energy per block: 6,716,254.6 kWh
electricity cost per block: $537,300.36
rewriting the last   1 blocks costs about $537,300 of electricity
rewriting the last   6 blocks costs about $3,223,802 of electricity
rewriting the last 100 blocks costs about $53,730,036 of electricity

Rewriting k blocks costs k times as much as one. Each extra confirmation multiplies the attacker's bill, which is why exchanges wait for several blocks before they treat a deposit as final.

Later in this track, Proof of Stake replaces the electricity bill with locked-up capital, and you will compare the two approaches directly.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A miner needs a hash starting with 5 zero hex digits. About how many attempts are expected on average?

    Each attempt succeeds with probability 1/16 per required digit, so five digits means a 1 in 16**5 = 1,048,576 chance per try.
  2. 2. What is the main reason a node can verify a mined block quickly?

    Finding the nonce takes many trials, but checking a claimed nonce takes one hash.
  3. 3. A miner has failed 100,000 times in a row. How does that change the chance that the next attempt succeeds?

    Every attempt is an independent trial with the same probability. Past failures give no advantage.
  4. 4. Why does an attacker who edits an old block have to redo so much work?

    Changing a block changes its hash, which breaks the link stored in the next block, so all later blocks must be mined again.

Summary

  • Proof of work asks miners to find a nonce that makes the block's hash fall below a target, usually shown as leading zeros.
  • The puzzle is hard to solve, trivial to verify and tunable by changing the target.
  • Attempts follow a geometric distribution: the average is 16**d for d hex zeros (2**bits for a bit target), but individual blocks vary widely and past failures do not help.
  • Rewriting an old block means redoing its work and the work of every later block while the honest chain keeps growing.
  • Miners are paid with a coinbase reward plus fees, and the cost of the work is the electricity and hardware behind the security.

Next: Difficulty Adjustment and Block Time, where you will see how a network keeps blocks arriving at a steady pace as mining power changes.