Bitcoin has a scheduled supply and an unscheduled production rate. The supply schedule is fixed in the code: 210,000 blocks between subsidy cuts, a limit of 21 million coins. The production rate is not fixed at all — it depends on how much computing power happens to be pointed at the network this week, which no rule can control. Difficulty adjustment is the mechanism that reconciles the two. It is the single piece of machinery that turns a variable, globally distributed, competitive industry into a roughly constant ten-minute heartbeat.
The whitepaper gives it two sentences. Section 4 says the proof-of-work difficulty is determined by a moving average targeting an average number of blocks per hour, and that if blocks are generated too fast, the difficulty increases. Everything below is what those two sentences expand into once you read the consensus code.
What exactly gets adjusted?
Not “difficulty” — that is a human-facing number. What a block header actually
contains is nBits, a compact 32-bit encoding of a 256-bit target. A block
is valid only if the double-SHA256 of its header, read as a big-endian integer,
is less than or equal to that target. A lower target means fewer acceptable
hashes, which means more work.
The compact encoding is one exponent byte followed by a three-byte mantissa.
The genesis block’s nBits is 0x1d00ffff, which unpacks to a target of
0x00000000FFFF0000…0000. That value is also the network’s maximum permitted
target, the powLimit. Difficulty is then just a ratio expressed against it:
difficulty = max_target / current_target
So difficulty 1 is the easiest the network is allowed to be, and the number you
see quoted is simply how many times harder than that the current target is. The
three-byte mantissa is worth noticing: nBits cannot express every 256-bit
integer, so the retarget result is rounded to what the encoding can hold. The
target is quantised, not continuous.
Why 2,016 blocks, and why fourteen days?
Three constants in consensus/params.h do all the work:
nPowTargetSpacing = 600 seconds (the intended average block interval)
nPowTargetTimespan = 1,209,600 seconds (fourteen days)
interval = nPowTargetTimespan / nPowTargetSpacing = 2,016 blocks
The retarget period is not an independent parameter. It is a consequence of
picking a ten-minute target spacing and a two-week measurement window. Every
2,016th block — heights where height % 2016 == 0 — a node recomputes the
target. At every other height, the rule is that nBits must be identical to
the previous block’s. There is no per-block drift, no smoothing, no partial
adjustment. Difficulty is a staircase, not a curve.
The window length is a deliberate trade between two failures. Too short, and the network over-reacts to ordinary variance in a Poisson process, oscillating instead of converging. Too long, and a genuine collapse in hashrate strands the chain at an unreachable target for months. Fourteen days is not derived from anything; it is a judgement call that has held up for sixteen years, which is a different and weaker claim than being optimal.
The retarget arithmetic
At a retarget height, a node takes the timestamp of the last block of the period and the timestamp of the first block of the period, and subtracts:
actual = last_block_time - first_block_time
expected = 1,209,600
new_target = old_target × (actual / expected)
If the period ran fast, actual is smaller than expected, the ratio is below
one, the target shrinks, and difficulty rises. If it ran slow, the target grows
and difficulty falls. The direction is intuitive. Two details are where the
implementation stops being intuitive.
The clamp. Before the multiplication, actual is clamped to
[expected / 4, expected × 4]. Difficulty therefore cannot move by more than a
factor of four in either direction in a single retarget, no matter what
happened. This bounds the damage from both a hashrate stampede and a
manipulated timestamp, at the cost of making recovery from a genuine 90%
hashrate loss take several consecutive retargets rather than one. The clamp is
a consensus rule, not a client policy: a block claiming a 5x adjustment is
invalid everywhere.
The off-by-one. A period of 2,016 blocks contains 2,015 intervals between
block timestamps, but the code divides by a timespan built from 2,016. The
measured elapsed time is systematically about one interval short, so the
network converges on an average block time of roughly
600 × 2015/2016 ≈ 599.7 seconds rather than 600. This is a known bug, usually
called the off-by-one or 2015/2016 bug, and it has never been fixed because
fixing it would be a hard fork over a 0.05% error. It compounds: Bitcoin’s
block clock runs very slightly ahead of a naive ten-minutes-per-block
projection, and estimates of future halving dates that ignore it drift by days.
How do nodes agree on “how long it took”?
This is the uncomfortable part. The retarget reads raw block timestamps, and a block timestamp is a number the miner chose. The consensus rules constrain it only loosely:
- it must be greater than the median timestamp of the previous eleven blocks (the median-time-past rule), and
- it must not be more than two hours ahead of the validating node’s own network-adjusted time.
Within those bounds a miner is free. The median-time-past floor means timestamps cannot run backwards in aggregate, but an individual block’s timestamp can be earlier than its parent’s. So the difficulty mechanism — the thing that makes Bitcoin’s issuance schedule meaningful — is driven by an input that miners partly supply.
That is the opening for the time-warp attack. An attacker holding a
majority of hashrate can keep most timestamps barely advancing, then set the
first block of each new retarget period far in the past relative to the
previous period’s last block. The measured actual becomes large, difficulty
falls, and across repeated periods it can be driven down far enough to mine the
remaining supply quickly. It requires sustained majority hashrate, so it is not
a live threat to a healthy network, but it is a real defect rather than a
theoretical curiosity, and proposals under the “consensus cleanup” banner would
patch it by requiring the first block of a period to be no more than a few
minutes behind the previous period’s last block.
What difficulty does not tell you
Difficulty is often read as a measure of network security or of hashrate. It is neither, directly.
It is not hashrate. Hashrate is estimated from difficulty, using
hashrate ≈ difficulty × 2³² / 600. That estimate is a backward-looking
inference from how fast blocks arrived, with the variance of a Poisson process
baked in. Short-window hashrate charts are mostly noise; the underlying
quantity is not observable at all.
It is not a price signal, and it is not a prediction. Difficulty follows hashrate, hashrate follows mining profitability, and profitability follows price with a lag set by hardware procurement and energy contracts. The causal arrow runs from price to difficulty, not the other way. Treating a difficulty rise as a forecast inverts the mechanism.
What difficulty does tell you is the cost basis of rewriting history. To reorganise the last n blocks, an attacker must redo their cumulative work at the prevailing target. That is the quantity the energy argument is actually about: not the electricity spent per transaction, but the electricity an attacker would have to spend to make a settled transaction unsettle.
Check it yourself
The retarget is one of the few consensus rules you can fully verify from a laptop, which is why it belongs early in a verification path rather than late. With a synced node:
# 1,008,000 is a retarget height: 2016 x 500.
bitcoin-cli getblockheader "$(bitcoin-cli getblockhash 1008000)" | grep -E '"bits"|"time"'
bitcoin-cli getblockheader "$(bitcoin-cli getblockhash 1007999)" | grep -E '"bits"|"time"'
bitcoin-cli getblockheader "$(bitcoin-cli getblockhash 1005984)" | grep -E '"bits"|"time"'
The useful exercise is to pick a retarget height, pull the timestamps of that
block and of the block 2,016 earlier, compute the ratio, apply the clamp,
multiply the previous target, round it into the nBits encoding, and confirm
that you get exactly the bits field the network accepted. When your arithmetic
matches, you have verified a consensus rule rather than read about one — and you
will have discovered along the way that the quantisation and the clamp are not
footnotes but part of the answer.
What remains uncertain
Several things about this mechanism are genuinely open, and a confident account should say so.
Whether the fourteen-day window survives a different mining industry. The window was chosen when mining was hobbyist and geographically incidental. Today hashrate is capital-intensive, contractually bound to specific power markets, and capable of moving in large correlated blocks. Whether a two-week lag is still the right trade-off under those conditions has not been settled; it has mostly been left alone, which is not the same as having been validated.
Whether the time-warp defect gets fixed. The patch is well understood and narrow, but it is a consensus change, and Bitcoin’s bar for consensus changes is deliberately high. Whether the fix ships, and on what timeline, is a governance question rather than a technical one.
How difficulty behaves when subsidy stops dominating revenue. Every projection of post-subsidy mining assumes a fee market that has not existed yet. Difficulty is downstream of miner revenue, so the honest position is that the long-run equilibrium of this mechanism is unobserved, not that it is reassuring.
What a sustained, deep hashrate loss would look like in practice. The clamp guarantees recovery takes multiple retargets, and the arithmetic of that is simple. What is not known is how the surrounding system — fee markets, exchange confirmation policies, user behaviour — responds to several weeks of slow blocks, because it has not happened at scale.
Sources
- PrimaryBitcoin: A Peer-to-Peer Electronic Cash System ↗
- First-partyBitcoin Core — src/pow.cpp, GetNextWorkRequired and CalculateNextWorkRequired ↗
- First-partyBitcoin Core — src/consensus/params.h, retarget parameters ↗
- TechnicalBitcoin Wiki — Target and the compact nBits encoding ↗
- TechnicalBitcoin Optech — Time warp attack ↗