Blockchain foundations in Go · 5 MIN READ

Proof of work: finding a nonce takes thousands of hashes, checking it takes one

Mine a toy block against a big.Int target, verify it with one hash, compute its expected work and retarget from observed block times.

A hash chain reveals that history changed, but anyone can rebuild a chain. Proof of work makes rebuilding expensive: a block counts only if its header hashes below a target, and the only known way to find such a header is to try nonces. Bitcoin still works this way; Ethereum left proof of work at the Merge in 2022. The idea to keep is the asymmetry between expensive search and cheap verification.

blockchain · A MAP OF THE IDEA

  1. Commit header fields
  2. Search nonce below target
  3. Verify with one hash
  4. Retarget from timestamps

Useful when

  • Verification cost is constant regardless of difficulty.
  • Cumulative work gives an objective rule for comparing chains.

Watch out

  • Security is probabilistic and assumes an honest hash-rate majority.
  • Timestamps are miner-supplied and need explicit bounds.

Implementation & operation cost: Real proof of work spends energy and hardware in proportion to the security it buys; the toy costs milliseconds only because its difficulty is tiny.

01

A target turns hashing into a lottery

Read a SHA-256 digest as a 256-bit unsigned integer. A header is valid when that number is below a target, and lowering the target makes valid headers rarer. With a target of 2^(256-k), a valid hash starts with k zero bits, so a miner expects about 2^k attempts while a verifier hashes once and compares. The nonce is the field the miner is free to change. Everything else in the header is fixed: the parent hash, the height, the difficulty and a commitment to the body, such as the Merkle root from the second lesson. Finding a nonce therefore proves work spent on this exact header. Change the body and the commitment changes, the old nonce stops working, and the cheap relinking attack from the first lesson now costs a fresh search for every block rewritten.

02

Mine, verify and retarget a toy chain

Header.Hash encodes fixed-width fields in a fixed order, as in the hash-chain lesson, and Valid compares the digest with target(Bits) using math/big. Mine increments the nonce from zero, so the run is deterministic: the same header always yields the same nonce. Work reports the expected number of hashes a target represents, and Retarget scales the target by observed over expected time, clamped to a factor of four. Difficulty stays at 16 bits or less so the run takes milliseconds.

go
package main

import (
	"crypto/sha256"
	"encoding/binary"
	"encoding/hex"
	"fmt"
	"math/big"
)

type Header struct {
	Parent [32]byte
	Height uint64
	Data   [32]byte // commitment to the block body, e.g. a Merkle root
	Bits   uint     // difficulty: the target is 2^(256-Bits)
	Nonce  uint64
}

func (h Header) Hash() [32]byte {
	buf := append([]byte(nil), h.Parent[:]...)
	buf = binary.BigEndian.AppendUint64(buf, h.Height)
	buf = append(buf, h.Data[:]...)
	buf = binary.BigEndian.AppendUint64(buf, uint64(h.Bits))
	buf = binary.BigEndian.AppendUint64(buf, h.Nonce)
	return sha256.Sum256(buf)
}

func target(bits uint) *big.Int { return new(big.Int).Lsh(big.NewInt(1), 256-bits) }

// Valid costs one hash, whatever the difficulty.
func Valid(h Header) bool {
	sum := h.Hash()
	return new(big.Int).SetBytes(sum[:]).Cmp(target(h.Bits)) < 0
}

// Mine is the expensive side: about 2^Bits attempts on average.
func Mine(h Header) (Header, uint64) {
	for attempts := uint64(1); ; attempts++ {
		if Valid(h) {
			return h, attempts
		}
		h.Nonce++
	}
}

// Work is the expected number of hashes a header represents: 2^256 / (target+1).
func Work(bits uint) *big.Int {
	t := target(bits)
	return new(big.Int).Div(new(big.Int).Lsh(big.NewInt(1), 256), t.Add(t, big.NewInt(1)))
}

// Retarget scales the target by actual/expected time, clamped to a factor of 4.
func Retarget(old *big.Int, actual, expected int64) *big.Int {
	actual = max(expected/4, min(actual, expected*4))
	t := new(big.Int).Mul(old, big.NewInt(actual))
	return t.Div(t, big.NewInt(expected))
}

func main() {
	body := sha256.Sum256([]byte("toy block body"))
	var last Header
	for _, bits := range []uint{8, 12, 16} {
		h, attempts := Mine(Header{Height: 1, Data: body, Bits: bits})
		sum := h.Hash()
		fmt.Printf("bits %2d: nonce %6d after %6d attempts, hash %s..., work %d\n",
			bits, h.Nonce, attempts, hex.EncodeToString(sum[:3]), Work(bits))
		last = h
	}

	fmt.Println("verify mined header:", Valid(last))
	last.Data[0] ^= 1 // change one bit of the body commitment
	fmt.Println("verify after edit:", Valid(last))

	// Ten blocks were expected to take 6000 s (fixed numbers, not a clock).
	old := target(16)
	for _, actual := range []int64{6000, 3000, 100} {
		next := Retarget(old, actual, 6000)
		fmt.Printf("span %4ds: new target = old * %s\n", actual, new(big.Rat).SetFrac(next, old).RatString())
	}
}
Read the code

At 8, 12 and 16 bits the expected work is 255, 4095 and 65535 hashes, computed as 2^256 divided by target+1, the formula Bitcoin Core uses for chain work. The 16-bit search took 205064 attempts, about three times the mean; attempt counts are geometrically distributed, so single blocks vary widely. Verification is one Valid call, and flipping one bit of the body commitment makes the same nonce fail. Retarget keeps the target when ten blocks take the expected 6000 seconds, halves it when they take half as long, and clamps a 60-fold speed-up to a factor of four. The spans are fixed numbers, not clock readings.

03

Difficulty adjustment keeps block time, not security, constant

Hash rate rises and falls as hardware joins or leaves, so a fixed target would let block intervals drift from seconds to days. Bitcoin recomputes its target every 2016 blocks from the time those blocks took, aiming at ten minutes per block, and limits each adjustment to a factor of four in either direction; Retarget is that rule in miniature. Timestamps are written by miners, so real rules also bound them: Bitcoin rejects a header whose time is not later than the median of the previous eleven blocks or lies more than two hours in the future. A toy that reads the wall clock is neither deterministic nor representative. Treat timestamps as untrusted data, as the program does, and test the rules that bound them.

04

What proof of work does and does not secure

Because work is costly to produce, nodes follow the valid chain with the most cumulative work, and rewriting a block buried under k later blocks means outpacing the rest of the network for k blocks. That security is probabilistic: an attacker with a minority of hash rate can still win a short race, and one with a majority can rewrite at will. Bitcoin's real header is 80 bytes hashed with double SHA-256, its target is packed into a 4-byte bits field, and it accepts a hash equal to the target, where this toy uses a strict comparison so that Bits reads as leading zero bits. Ethereum's proof-of-work era ended with the Merge (EIP-3675); validators now propose blocks and stake finalizes them, which the next lesson relies on. And do not reinvent proof of work as an API rate limiter: puzzles cost honest low-end devices more than attackers with GPUs.

05

Testing work-based code

Keep difficulty tiny in tests and pin the expected nonce for a fixed header as a known answer, so a changed encoding changes the nonce and fails loudly. Test Valid at the boundary: under a strict comparison a hash equal to the target must fail, and a target of zero or above 2^256 must be refused before use; real chains also enforce a maximum target, the proof-of-work limit. Test Retarget at, above and below both clamps, and check integer division, whose rounding compounds over many periods. Benchmark mining separately from unit tests, and never let a test search at a difficulty whose runtime depends on luck you have not measured: the 16-bit search here already needed three times its average.

TAKE THIS WITH YOU

Proof of work is asymmetric: a nonce below a 2^(256-k) target takes about 2^k hashes to find and one hash to check, so chains compare cumulative work and retarget from timestamps treated as data.

Check your understanding

A miner needed about 2^16 attempts to find a valid nonce. How much work does a node spend verifying that header's proof of work?

Go to the source

Progress stays in this browser. No account needed.