Search code examples
targetbitcoin

Where and how pool difficulty(pdiff) is set in bitcoin source code?


I am working with bitcoin source code want to set initial difficulty to 1 (I changed bdiff,nBits field). So I need to change pdiff as well. according to :

difficulty = difficulty_1_target / current_target (target is a 256 bit number)

difficulty_1_target can be different for various ways to measure difficulty. Traditionally, it represents a hash where the leading 32 bits are zero and the rest are one (this is known as "pool difficulty" or "pdiff"). The Bitcoin protocol represents targets as a custom floating point type with limited precision; as a result, Bitcoin clients often approximate difficulty based on this (this is known as "bdiff").

Anyone knows where pdiff is stored ? Is it hard coded ?


Solution

  • I found the solution! It's not exactly a pdiff field in the code but there is a function in blockchain.cpp :

    double GetDifficulty(const CBlockIndex* blockindex)
    {
        if (blockindex == nullptr)
        {
            return 1.0;
        }
    
        int nShift = (blockindex->nBits >> 24) & 0xff;
        double dDiff =
            (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);
    
        while (nShift < 29)
        {
            dDiff *= 256.0;
            nShift++;
        }
        while (nShift > 29)
        {
            dDiff /= 256.0;
            nShift--;
        }
        return dDiff;
     }
    

    for bitcoin initial nBits is equal to 0x1d00ffff so dDiff field above becomes 1 and nshift is equal to 1D. For my private version I set nBits to 0x1f0fffff and should calculate dDiff like

    double dDiff =(double)0x000ffff / (double)(blockindex->nBits & 0x00ffffff);
    

    and nShift field for me is 0x1f so I changed while conditions to while(nShift < 31) andwhile (nShift > 31). by running command bitcoin-cli getdifficulty I got 1 as initial difficulty.