Assume we have a transaction in hex (tx_hex) and we want to find a nonce such that

SHA-256(SHA-256(nonce|| tx_hex)) = new_transaction_id ('||' denotes concatenation)

first bits consist of 32 zeros. I understand that this nonce can be found only by brute force.

However, I cannot figure out how you check this condition in practice. new_transaction_id is in hex, so is that equivalent to checking that its first 8 digits are 0?

And if so to find the nonce, I just have to try every possible number (let's say up to 32 bits) for the first 8 digits of new_transaction_id to be 0?

That is my code BTW

def mine(self, tx_hex):
    for i in range(1,4294967295):
        nonce = hex(i)[2:]
        new_tx = self.add_nonce(nonce, tx_hex)
        sha = self.get_tx_id(new_tx)
        if sha[:8] == '00000000':
            print('Nonce:', i)
  • 3
  • @RedGrittyBrick I don't know if I fully understood your answer, but here I specifically want the new hash to have zeros at its first 32 bits. Can you help for this case? – Paris Feb 18 at 12:54
  • Ignore the count of leading zeroes. Test whether the calculated hash is numerically less than the target value (hash < target). – RedGrittyBrick Feb 18 at 13:37
  • @RedGrittyBrick Ok, that makes sense in practice, but I still want to understand what we mean by the first 32 bits to be zero. Do we examine the 256 bits of SHA-256(SHA-256(nonce|| tx_hex)) (binary) output and expect the first 32 to be zero? – Paris Feb 19 at 7:39
  • See oreilly.com/library/view/mastering-bitcoin/9781491902639/… you should probably view the difficulty as simply a compact encoding of an inverse of the block target. You get the target then you compare the hash with the target, not with any aspect of the compact encoding of it's inverse. The 32 bits of zeroes is just an aspect of the encoding - it isn't applied to the hash. – RedGrittyBrick Feb 19 at 12:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.