| 13 | #include "util.h" |
| 14 | |
| 15 | unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params) |
| 16 | { |
| 17 | unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact(); |
| 18 | |
| 19 | // Genesis block |
| 20 | if (pindexLast == NULL) |
| 21 | return nProofOfWorkLimit; |
| 22 | |
| 23 | // Only change once per difficulty adjustment interval |
| 24 | uint32_t nHeight = pindexLast->nHeight + 1; |
| 25 | if (nHeight % params.DifficultyAdjustmentInterval() == 0) { |
| 26 | // Go back by what we want to be 14 days worth of blocks |
| 27 | assert(nHeight >= params.DifficultyAdjustmentInterval()); |
| 28 | uint32_t nHeightFirst = nHeight - params.DifficultyAdjustmentInterval(); |
| 29 | const CBlockIndex *pindexFirst = pindexLast->GetAncestor(nHeightFirst); |
| 30 | assert(pindexFirst); |
| 31 | |
| 32 | return CalculateNextWorkRequired(pindexLast, |
| 33 | pindexFirst->GetBlockTime(), params); |
| 34 | } |
| 35 | |
| 36 | if (params.fPowAllowMinDifficultyBlocks) { |
| 37 | // Special difficulty rule for testnet: |
| 38 | // If the new block's timestamp is more than 2* 10 minutes then allow |
| 39 | // mining of a min-difficulty block. |
| 40 | if (pblock->GetBlockTime() > |
| 41 | pindexLast->GetBlockTime() + 2 * params.nPowTargetSpacing) { |
| 42 | return nProofOfWorkLimit; |
| 43 | } |
| 44 | |
| 45 | // Return the last non-special-min-difficulty-rules-block |
| 46 | const CBlockIndex *pindex = pindexLast; |
| 47 | while (pindex->pprev && |
| 48 | pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && |
| 49 | pindex->nBits == nProofOfWorkLimit) { |
| 50 | pindex = pindex->pprev; |
| 51 | } |
| 52 | |
| 53 | return pindex->nBits; |
| 54 | } |
| 55 | |
| 56 | // Do not go lower than the POW limit. |
| 57 | uint32_t nBits = pindexLast->nBits; |
| 58 | if (nBits == nProofOfWorkLimit) { |
| 59 | return nProofOfWorkLimit; |
| 60 | } |
| 61 | |
| 62 | // Done, unless checking UAHF fast difficulty drop |
| 63 | if ((Opt().UAHFTime() == 0) || (pindexLast->GetMedianTimePast() < Opt().UAHFTime())) |
| 64 | return nBits; |
| 65 | |
| 66 | // If producing the last 6 block took less than 12h, we keep the same difficulty. |
| 67 | const CBlockIndex *pindex6 = pindexLast->GetAncestor(nHeight - 7); |
| 68 | assert(pindex6); |
| 69 | int64_t mtp6blocks = |
| 70 | pindexLast->GetMedianTimePast() - pindex6->GetMedianTimePast(); |
| 71 | if (mtp6blocks < 12 * 3600) { |
| 72 | return nBits; |