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.
-
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♦ Mar 24 '14 at 12:21
-
Is difficulty the same thing as the target? – Dylan Katz Mar 24 '14 at 15:54
-
3Difficulty is essentially the human readable representation of the target. See here: What is “difficulty” and how it relates to “target”? – Murch♦ Mar 24 '14 at 22:23
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:
Or, more simply, you'd use the same shorthand you use with regular scientific notation:
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).
-
1Can you elaborate on how this is Base-256? Surely for base 256 we would need 256 unique symbols? – El Ronnoco Sep 26 '19 at 12:35
-
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 Feb 10 at 14:57