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?

1 Answer 1

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.

2
  • 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 9, 2022 at 9: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. Oct 9, 2022 at 9:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.