How is the target section of a block header calculated?

9

3

I've been poking around https://en.bitcoin.it/wiki/Target and I've found the current target, but I can't seem to find how it's generated. It's supposedly generated when the difficulty is adjusted, as stated here: https://en.bitcoin.it/wiki/Block_hashing_algorithm, but what exactly is the algorithm for generating the target? If someone could show me some psuedocode that would be great.

Dylan Katz

Posted 2014-03-24T06:12:34.450

Reputation: 197

It is not clear to me whether you are looking for a verbal explanation of the difficulty algorithm, the specific line of code where to find it, or a step-by-step explanation of the code. Perhaps you could edit your question in order to clarify. If you are asking for the first: possible duplicate of How is difficulty calculated?

– Murch – 2014-03-24T12:21:39.453

Is difficulty the same thing as the target? – Dylan Katz – 2014-03-24T15:54:06.590

3

Difficulty is essentially the human readable representation of the target. See here: What is “difficulty” and how it relates to “target”?

– Murch – 2014-03-24T22:23:45.537

Answers

18

The target section of the block header is called nBits in the code. nBits is a 32-bit compact encoding of a 256-bit target threshold. It works like scientific notation, except that it uses base-256 instead of base-10. For example, if nBits is equal to 0x181b8330, you would calculate it like this:

nBits formula

Or, more simply, you'd use the same shorthand you use with regular scientific notation:

nBits quick

At a re-target point (every 2,016th block), Bitcoin Core adjusts nBits according to the rules described in this answer except that it is important to note that when difficulty changes by p percent, nBits is adjusted by the inverse (-p percent). That's because a lower target is harder to reach the way Bitcoin is implemented.

It's also important to note that you can't just adjust the exponent part of nBits in the obvious way because when Satoshi first wrote the code, he inherited from a signed type---so extra care must be taken not to create a negative nBits value. The Bitcoin.org Developer Reference has more details (but be careful, I haven't yet had an expert review that section).

David A. Harding

Posted 2014-03-24T06:12:34.450

Reputation: 10 649

1Can you elaborate on how this is Base-256? Surely for base 256 we would need 256 unique symbols? – El Ronnoco – 2019-09-26T12:35:33.403

1@ElRonnoco It does have 256 unique symbols: each byte is a symbol. (For the analogy, anyway; exponential notation doesn't actually require the base to line up with symbols at all; in fact, mathematicians use base $e$ a lot.) – wizzwizz4 – 2021-02-10T14:57:17.613