9

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.

3
  • 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, 2014 at 12:21
  • Is difficulty the same thing as the target?
    – Dylan Katz
    Mar 24, 2014 at 15:54
  • 3
    Difficulty is essentially the human readable representation of the target. See here: What is “difficulty” and how it relates to “target”?
    – Murch
    Mar 24, 2014 at 22:23

3 Answers 3

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 0x181bc330, 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).

2
  • 1
    Can you elaborate on how this is Base-256? Surely for base 256 we would need 256 unique symbols?
    – El Ronnoco
    Sep 26, 2019 at 12:35
  • 2
    @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, 2021 at 14:57
1

I am not sure how this is actually implemented in the code, but you can approximate the new target (nBits) value with data from the prior 2016th block. Note that as described above nBits is the 32-bit compact encoding of the 256-bit target value.

Here shows the new difficulty (d_new) as:

d_new = d_old * 2 weeks / t_old

where 'old' signifies the previous 2016 blocks, and t_old is the time it took to find those previous 2016 blocks.

Here shows d_new from genesis block values as:

d_new = nBits_genesis / nBits_new, and similarly
d_old = nBits_genesis / nBits_old

Combining these 3 equations results in

nBits_new = (t_old / 2 weeks) * nBits_old

So knowing the timestamps of the new block and the prior 2016th block, and the target of the prior 2016th block, we can approximate the new target value. For example:

block 703584
nBits = 0x170e2632 = 927282 * 256^(23-3)
timestamp 2021-10-04 16:35:19

block 701568 (the prior 2016th block)
nBits = 0x170ed0eb = 970987 * 256^(23-3)
timestamp 2021-09-21 07:34:36

So
t_old = 13 days 9h 33s = 1155633s and 2 weeks = 1209600s
nBits_old = 970987 * 256^(23-3)
Thus the new target is approximately
1155633/1209600 * 256^20
= 0.955384424 * 970987 * 256^20 = 927666 * 256^20

Converting to the compact 32-bit format we get nBits_new ~ 0x170e27b2

The mantissa 927666 (0x0e27b2) is close to the actual mantissa 927282 (0x0e2632). It's a reasonable approximation but obviously the absolute values of the targets are quite different because it's base-256. Error here is likely due to rounding to the nearest second in the timestamps. Even though this is not the explicit calculation done in the code, I hope that it helps in general understanding, including the references here and here.

0

I have a working c# implementation of nBits computation. I've tested and it works. However, keep in mind my machine is Little Endian so the implementation takes that into account. If your machine is Big Endian, then the way you would read in the nBits bytes would be different. If you don't know how to get changeFactor, the steps are below after the code.

changeFactor is the ratio of time it took to mine the last 2015 blocks to the expected time of 10mins per block. {Pls it is not a typo. It is the last 2015 blocks you will consider when computing change factor even though you only recalculate nBits after every 2016 blocks}.

actual time of last 2015 blocks = unixEpoch of current highest block - unixEpoch of block with blockHeight equals [currentHighestBlockHeight - 2014] {again this is not a typo}

expected time = 2016 * 10 * 60 = 1209600

change factor = actualTime / expectedTime. However, there is a limit for change factor. There can't be a change of more than 400% per retarget cycle.

so after getting change factor you do the ff. to keep it within the set bounds before feeding it to the retargeting function.

if (changeFactor > 4) changeFactor = 4;
if (changeFactor < 0.25) changeFactor = 0.25;

Finally oldNBits is just the nBits of the current Highest block in uint form. Hope this helps.

public static uint RetargetByFactor(uint oldNBits, double changeFactor)
        {
            // convert change factor to rational number with numerator and denomenator
            BigInteger numerator = 0;
            BigInteger denomenator = 1;

            while(changeFactor % 1 != 0)
            {
                changeFactor = changeFactor * 10;
                denomenator = denomenator * 10;
            }
            numerator = (BigInteger)changeFactor;

            byte[] oldNBitsBytes = BitConverter.GetBytes(oldNBits);
            byte[] mantissa = new byte[] {oldNBitsBytes[0], oldNBitsBytes[1], oldNBitsBytes[2], 0x00 };  // need to reverse the bytes because we want the mantissa in little endian
            byte exponent = oldNBitsBytes[3];

            BigInteger result = new BigInteger(mantissa);
            result = result << (exponent-3)*8;

            result = result * numerator / denomenator;

            byte[] resultBytes = result.ToByteArray();

            if (result == 0)
            {
                return 0;
            }

            // now to get the exponent of the newNBits, we count how many binary right shifts are needed for result to go below or equal to 0xffffff.
            byte newExponent = 3;
            while(result > 0xffffff)
            {
                result = result >> 8;
                newExponent++;
            }

            BigInteger newMantissa = result;

            List<byte> compressedResult = new List<byte>();
            byte[] newMantissaBytes = newMantissa.ToByteArray();

            
            compressedResult.AddRange(new byte[] { newMantissaBytes[0], newMantissaBytes[1], newMantissaBytes[2] });

            compressedResult.Add(newExponent);

            return BitConverter.ToUInt32(compressedResult.ToArray(), 0);
        }
1
  • Finally, let me add that you only compute nBits for all blocks whose blockHeight % 2016 equals zero. Feb 4, 2022 at 11:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.