consensus: add DeriveTarget() to pow.h

Split CheckProofOfWorkImpl() to introduce a helper function
DeriveTarget() which converts the nBits value to the target.

The function takes pow_limit as an argument so later commits can
avoid having to pass ChainstateManager through the call stack.

Co-authored-by: Ryan Ofsky <ryan@ofsky.org>
This commit is contained in:
Sjors Provoost 2025-01-03 10:07:38 +01:00
parent 228aba2c4d
commit 6accee1844
No known key found for this signature in database
GPG key ID: 57FF9BDBCC301009
2 changed files with 23 additions and 3 deletions

View file

@ -143,7 +143,7 @@ bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params&
return CheckProofOfWorkImpl(hash, nBits, params);
}
bool CheckProofOfWorkImpl(uint256 hash, unsigned int nBits, const Consensus::Params& params)
std::optional<arith_uint256> DeriveTarget(unsigned int nBits, const uint256 pow_limit)
{
bool fNegative;
bool fOverflow;
@ -152,8 +152,16 @@ bool CheckProofOfWorkImpl(uint256 hash, unsigned int nBits, const Consensus::Par
bnTarget.SetCompact(nBits, &fNegative, &fOverflow);
// Check range
if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))
return false;
if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(pow_limit))
return {};
return bnTarget;
}
bool CheckProofOfWorkImpl(uint256 hash, unsigned int nBits, const Consensus::Params& params)
{
auto bnTarget{DeriveTarget(nBits, params.powLimit)};
if (!bnTarget) return false;
// Check proof of work matches claimed amount
if (UintToArith256(hash) > bnTarget)

View file

@ -13,6 +13,18 @@
class CBlockHeader;
class CBlockIndex;
class uint256;
class arith_uint256;
/**
* Convert nBits value to target.
*
* @param[in] nBits compact representation of the target
* @param[in] pow_limit PoW limit (consensus parameter)
*
* @return the proof-of-work target or nullopt if the nBits value
* is invalid (due to overflow or exceeding pow_limit)
*/
std::optional<arith_uint256> DeriveTarget(unsigned int nBits, const uint256 pow_limit);
unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params&);
unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params&);