Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 41 ยท Building a Toy Blockchain

Difficulty Adjustment and Block Time

See how a proof-of-work chain retargets difficulty so blocks keep a steady pace when hash power changes, with a seeded Python simulation and a plot.

In Proof of Work and Mining you fixed the difficulty by hand. A real network cannot do that. Nobody knows how much mining power will be online next month: new hardware arrives, prices swing, a region cuts off power. If the puzzle never changed, a surge of miners would make blocks come every few seconds, and a mass exit would stretch them to hours.

A blockchain solves this by measuring its own pace and adjusting. Every so often the protocol looks at how long the last batch of blocks took and rescales the difficulty so the average block time returns to the target. In this lesson you will write that rule, simulate a network whose hash power jumps up and down, and plot how the chain responds.

Block time is random, and that is fine

With a puzzle that has a success chance p per hash and a network that computes H hashes per second, blocks arrive like a lottery draw: the time to the next block is random, with an average of 1 / (p * H). Mathematically it follows an exponential distribution. Two consequences matter:

  • A "10-minute" target does not mean one block every 10 minutes. It means 10 minutes on average, and individual gaps range from seconds to over an hour.
  • A single slow or fast block tells you nothing about hash power. Only a large sample does, which is why adjustment looks at a window of many blocks.

In the model below, we call the expected number of hashes needed per block the difficulty D. The average block time is then D / H. If you want a fixed block time T, you need D = H * T, and the protocol must keep nudging D toward the current H without being able to observe H directly. It only sees timestamps.

The retarget rule

After every window of W blocks, compare how long the window took with how long it should have taken (W * T):

TEXT
new_difficulty = old_difficulty * (W * T) / actual_time

If the blocks came twice as fast as planned, actual_time is half of the expected time and the difficulty doubles. If they came twice as slowly, it halves. Bitcoin uses a window of 2,016 blocks and a 10-minute target, so it retargets about every two weeks. It also clamps the change to a factor of 4 up or down per window, which limits the damage from wrong or manipulated timestamps.

Python The retarget rule as a function

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 result is:

TEXT
           on time: difficulty 1000.0 ->   1000.0
     twice as fast: difficulty 1000.0 ->   2000.0
     twice as slow: difficulty 1000.0 ->    500.0
 ten times as fast: difficulty 1000.0 ->   4000.0
 ten times as slow: difficulty 1000.0 ->    250.0

The two extreme rows hit the clamp. A chain whose hash power vanished completely would take several windows to recover, and that is a real weakness of long windows. Some newer chains adjust every block with a moving average. We stick with the windowed approach here because it is the simplest to read.

flowchart LR
    A["Mine W blocks"] --> B["Measure<br/>actual time"]
    B --> C["Compare with<br/>W x target"]
    C --> D["Scale difficulty<br/>(clamped)"]
    D --> A

Difficulty adjustment is a feedback loop: measure the last window, scale the difficulty, mine the next window.

Simulating changing hash power

Now we will test the rule. The simulation keeps the following state: the current time, the current difficulty and the list of blocks. For each block:

  1. Look up the network hash power at the current time.
  2. Draw a random block time from an exponential distribution with mean difficulty / hash_power.
  3. Add it to the clock and record the block.
  4. After every W blocks, retarget.

We use a seeded random generator so the numbers are the same every time you run it. The scenario has three phases: normal power, a tripling when new miners arrive, and a collapse to half of the original power.

Python A chain reacts to hash power changes

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 has 20 rows. Read it from top to bottom:

TEXT
window  start(h)  mean gap(s)  difficulty at start of window
     1       0.0        442.6       600.0
     2       6.1        866.7       813.4
     3      18.2        410.7       563.1
     4      23.9        787.5       822.7
     5      34.8        240.9       626.8
     6      38.2        485.0      1561.5
     7      44.9        677.8      1931.9
     8      54.3        454.9      1710.2
     9      60.6        646.1      2256.0
    10      69.6        656.2      2094.9
    11      78.7       1891.6      1915.6
    12     105.0       1404.0       607.6
    13     124.5        515.5       259.7
    14     131.7        555.6       302.2
    15     139.4        705.0       326.3
    16     149.2        608.9       277.7
    17     157.6        539.9       273.6
    18     165.1        555.4       304.1
    19     172.8        741.4       328.5
    20     183.1        360.8       265.9

Look at what happens in window 5, where the power triples: the mean gap drops to 241 seconds, and the difficulty climbs from 627 to about 1,900 over the next windows until the mean gap is back near 600. The ideal value is 1,800, three times the starting difficulty, and the noisy windows hover around it. When the power collapses in window 11, the mean gap jumps to 1,892 seconds and stays high in window 12 (1,404), until the difficulty has fallen to about 300, the right value for half the original power. The chain never knew the hash power. It only reacted to timestamps.

Plotting the response

A table shows the numbers; a picture shows the shape. Matplotlib works in the browser runner, so we can plot the block gaps (smoothed with a moving average, because single gaps are very noisy) next to the difficulty.

Python Plot block time and difficulty

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 blue line dips below the red target when hash power triples (fast blocks), then rises above it when power collapses (slow blocks). The green staircase underneath is the answer: difficulty rises in steps after the tripling and falls in steps after the collapse, and each step brings the blue line back toward the target. The grey noise is the exponential randomness from earlier: even at perfect calibration, single gaps scatter widely.

Things the simple rule gets wrong

Our model is a teaching tool. Real chains have to deal with extra problems:

  • Timestamp honesty. Miners write the block time themselves. Protocols accept timestamps only within limits (not before the median of recent blocks, not too far in the future), and the clamp stops a cheat from swinging the difficulty wildly.
  • Slow recovery. With a 2,016-block window, a sudden loss of most of the network can leave blocks very slow for days. Chains with smaller windows or per-block adjustment recover faster but can react too strongly to noise.
  • Oscillation. If miners switch hardware on when a chain looks profitable and off when it does not, hash power chases the difficulty while the difficulty chases the hash power.
  • Merging with other chains. Miners can move to whichever chain pays best, so small chains that share an algorithm with big ones can suffer wild swings.

Block time also sets a real limit: a network cannot confirm faster than its blocks arrive, and shortening the target raises the chance that two miners find a block at the same moment. That leads to forks, which is the topic of Longest Chain Rule, Forks and Reorgs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A 50-block window took half the planned time. What does the retarget rule do to the difficulty (assuming no clamp is hit)?

    Blocks came twice as fast, so the puzzle must become twice as hard to bring the average back to the target.
  2. 2. Why does the protocol adjust over a window of many blocks instead of reacting to each block?

    Block gaps follow an exponential distribution, so one gap says almost nothing about hash power. A large sample does.
  3. 3. What is the purpose of clamping the adjustment to a factor such as 4?

    Without a clamp, one false timestamp pair could change the difficulty by an enormous factor.
  4. 4. After a large share of miners switches off, what do you see in a chain with a long retarget window?

    Difficulty only changes at the retarget point, so blocks stay slow in the meantime.

Summary

  • Block arrival is a random process, so a target block time is an average, never a schedule.
  • Difficulty is retargeted per window with new = old * (W * T) / actual_time, usually clamped to a factor like 4.
  • The chain never observes hash power. It infers it from timestamps, so it lags behind sudden changes.
  • Seeded simulations let you test the control loop repeatably and plot how fast it recovers.
  • Timestamps, window size and miner behaviour are the practical weak points of the mechanism.

Next: Transactions and the Mempool, where you will give your blocks real content to carry.