Can someone point me to the source code and explain how the average is calculated for the adjustment of difficulty that takes place every 2016 ? Update: i have consulted with previous questions but it has not been documented properly and I am not expert so would be much appreciated.
1 Answer
The function is CalculateNextWorkRequired
in pow.cpp
L#49:
unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)
{
if (params.fPowNoRetargeting)
return pindexLast->nBits;
// Limit adjustment step
int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;
if (nActualTimespan < params.nPowTargetTimespan/4)
nActualTimespan = params.nPowTargetTimespan/4;
if (nActualTimespan > params.nPowTargetTimespan*4)
nActualTimespan = params.nPowTargetTimespan*4;
// Retarget
const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
arith_uint256 bnNew;
bnNew.SetCompact(pindexLast->nBits);
bnNew *= nActualTimespan;
bnNew /= params.nPowTargetTimespan;
if (bnNew > bnPowLimit)
bnNew = bnPowLimit;
return bnNew.GetCompact();
}
Explanation:
1. If retargeting is disabled, return the last difficulty.
2. Calculate the timespan between the last block and 2016 blocks ago
3. Truncate the timespan to no less than 1/4 of the target timespan (3.5 days) or no greater than 4x the target timespan (8 weeks).
4. Multiply the last difficulty target by the ratio actualTimespan:targetTimespan
5. Truncate to the maximum allowed target (bnPowLimit) if the resulting target is too high (very low difficulty)