1

So I've been trying to figure out how the nBits of a block is calculated, but I can't seem to come up with an answer. I know (think) that it's based off the difficulty of the block, but I'm still not sure exactly how it works. The Genesis Block for example has a difficulty of 1.0, yet the nBits for that block was 486,604,799 (0x1d00ffff). Then if we look at the most recent block, it has a difficulty level of 21,434,395,961,348.92, yet an nBits of 386,736,569 (0x170d21b9).

So my question is, how exactly is the nBits of a block calculated and what is its relation to the difficulty of a block?

Thanks

L M
  • 79
  • 1
  • 5

1 Answers1

5

nBits is a compressed representation of the target value that the block's hash must be less than. Bitcoin does not actually care about difficulty. Difficulty is just for humans to think about how much work is actually being done. Bitcoin only cares about nBits and the target value it represents. A block's hash must be less than that target value. nBits is recalculated every time the difficulty changes. The calculation takes the previous target (previous nBits) and scales it by the ratio of the actual timespan it took for that difficulty period to the timespan that is targeted for a difficulty period.

What it code does is (in pseudocode):

new_target = last_block.nBits.uncompress();
new_target *= actual_timespan;
new_target /= target_timespan;
this_block.nBits = new_target.compress();

So nBits starts at the value of the genesis block, and then scales up and down depending on how quickly blocks are being mined.


The relationship between nBits and difficulty is inverted. As nBits represents a smaller and smaller target, the difficulty value goes up. The computation is essentially just the ratio between the current target value and the maximum target value, which also happens to be the target value found in the genesis block. The difficulty is the current target divided by the the maximum target.

Pieter Wuille
  • 105,497
  • 9
  • 194
  • 308
Ava Chow
  • 70,382
  • 5
  • 81
  • 161
  • So how did the Genesis Block gets its nBit value if it relies on the previous block? Is it similar to the previous hash in the Genesis Block where it was just given a random value? – L M Feb 10 '21 at 19:00
  • The genesis block is valid by definition; its contents does not matter. – Pieter Wuille Feb 10 '21 at 19:22
  • "A block's hash must be less than that target value." *less than or equal to according to this... https://developer.bitcoin.org/reference/block_chain.html – Bradley Thomas Aug 06 '23 at 22:07