1

According to the source code here is where the hash computed by a miner is compared with the target hash:

bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)
{
    bool fNegative;
    bool fOverflow;
    arith_uint256 bnTarget;
bnTarget.SetCompact(nBits, &fNegative, &fOverflow);

// Check range
if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))
    return false;

// Check proof of work matches claimed amount
if (UintToArith256(hash) > bnTarget)
    return false;

return true;

}

Can you fill the code above with comments to make me to understand what is the role of every variable used in this function?

About the hashes comparing I have read this, anyway, can you make another example printing hash strings to show to me the output of every line of the code?

Vojtěch Strnad
  • 8,292
  • 2
  • 12
  • 40
smartmouse
  • 165
  • 7

1 Answers1

3

hash is the SHA256 hash value (a large integer) calculated by the miner for the block. If the hash is less than or equal to the Bitcoin network target, the miner succeeded and the hash is a valid proof of work. Conversely, if the hash value is greater than the Bitcoin network target, the miner failed and the hash is not a valid proof of work.

bnTarget is the current Bitcoin network target (inverse of difficulty). In the network packets it is sent in a Bitcoin specific compact form (nbits) but you need it expanded to an integer for use in numeric comparisons with calculated hashes.

fNegative and fOverflow are error flag values returned by the SetCompact() method. They indicate if the conversion from the nbits value resulted in a negative number (bad) or an arithmetic overflow (bad)

params.powlimit is the maximum possible value of a hash value representing proof of work (hence pow). This is less than the actual max value of the data type being used here. The value of powLimit is 0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff, the value corresponding to difficulty 1.

RedGrittyBrick
  • 26,841
  • 3
  • 25
  • 51
  • What is uint256 hash and what does it do? I assumed it is the hash generated by a miner but then why the comparation is > against the bnTarget instead of <? – smartmouse Oct 09 '22 at 09:22
  • You are right, hash is the value calculated by the miner. Note that if (hash > bnTarget) FAIL is the same as if (hash <= bnTarget) SUCCEED. – RedGrittyBrick Oct 09 '22 at 09:50