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 5691fa93c4
commit c4cc9e3e9d
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)