Skip to content

Commit c4cc9e3

Browse files
Sjorsryanofsky
andcommitted
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 <[email protected]>
1 parent 5691fa9 commit c4cc9e3

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

src/pow.cpp

+11-3
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params&
143143
return CheckProofOfWorkImpl(hash, nBits, params);
144144
}
145145

146-
bool CheckProofOfWorkImpl(uint256 hash, unsigned int nBits, const Consensus::Params& params)
146+
std::optional<arith_uint256> DeriveTarget(unsigned int nBits, const uint256 pow_limit)
147147
{
148148
bool fNegative;
149149
bool fOverflow;
@@ -152,8 +152,16 @@ bool CheckProofOfWorkImpl(uint256 hash, unsigned int nBits, const Consensus::Par
152152
bnTarget.SetCompact(nBits, &fNegative, &fOverflow);
153153

154154
// Check range
155-
if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))
156-
return false;
155+
if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(pow_limit))
156+
return {};
157+
158+
return bnTarget;
159+
}
160+
161+
bool CheckProofOfWorkImpl(uint256 hash, unsigned int nBits, const Consensus::Params& params)
162+
{
163+
auto bnTarget{DeriveTarget(nBits, params.powLimit)};
164+
if (!bnTarget) return false;
157165

158166
// Check proof of work matches claimed amount
159167
if (UintToArith256(hash) > bnTarget)

src/pow.h

+12
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,18 @@
1313
class CBlockHeader;
1414
class CBlockIndex;
1515
class uint256;
16+
class arith_uint256;
17+
18+
/**
19+
* Convert nBits value to target.
20+
*
21+
* @param[in] nBits compact representation of the target
22+
* @param[in] pow_limit PoW limit (consensus parameter)
23+
*
24+
* @return the proof-of-work target or nullopt if the nBits value
25+
* is invalid (due to overflow or exceeding pow_limit)
26+
*/
27+
std::optional<arith_uint256> DeriveTarget(unsigned int nBits, const uint256 pow_limit);
1628

1729
unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params&);
1830
unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params&);

0 commit comments

Comments
 (0)