7

I'm trying to wrap my head around the mining process by doing a small example of block hashing.

According to the Wiki entry about difficulty, the target for a block hash can be read from the "bits" part of the header as follows: In this example, the bits part is 535f0119.

535f0119 * 2**(8*(0x1b - 3))

My resulting target would be:

535f0119000000000000000000000000000000000000000000000000

The target in decimal would be:

8780002705592212783085671453687210878315895819816253650256038723584

Let's say the hash I got with my current nonce is

4d47599dd86834282a8ae6f20ba454704ddbe6eb23aa31b9fdec97fc7679b559

How can I now compare if the hash is smaller than the target? What do I have to do with the hash to be able to say "hash < target"?

13

How to calculate the target from bits

Let's start with a block-header, always 80-bytes that looks like this:

04000000b9e2784a84e5d2468cee60ad14e08d0fee5dda49a37148040000000000000000e9dd2b13157508891880ef68729a1e5ecdde58062ebfa214a89f0141e5a4717faefd2b577627061880564bec

From the 80-bytes, the bits are actually the 72nd to 76th byte:

04000000b9e2784a84e5d2468cee60ad14e08d0fee5dda49a37148040000000000000000e9dd2b13157508891880ef68729a1e5ecdde58062ebfa214a89f0141e5a4717faefd2b57**76270618**80564bec

or

76270618

This number, however, is in little-endian, so we have to reverse the bytes:

18062776

The first byte is the "exponent"

e = 0x18

The next 3 bytes are the "coefficient"

c = 0x062776

You plug this into a formula:

target = c * 2**(8*(e - 3))

In our case, that is:

target = 0x062776 * 2**(8*(0x18 - 3))

Which turns out to be:

0000000000000000062776000000000000000000000000000000000000000000

Let's calculate the hash of this block header using Python 2:

from hashlib import sha256
header = "04000000b9e2784a84e5d2468cee60ad14e08d0fee5dda49a37148040000000000000000e9dd2b13157508891880ef68729a1e5ecdde58062ebfa214a89f0141e5a4717faefd2b577627061880564bec".decode('hex')
print sha256(sha256(header).digest()).digest()[::-1].encode('hex')

The output is

0000000000000000040199a6c7b922f711ee7e98cd58863b8b981b02d2b83e13

You can compare this to the target

>>> 0x0000000000000000040199a6c7b922f711ee7e98cd58863b8b981b02d2b83e13 < 0x0000000000000000062776000000000000000000000000000000000000000000 
True

That's how we know a block satisfies the proof-of-work.

  • Could difficulty be argued to be a percent then? i.e. d = (target hash)/(most difficult target hash) – Josh Jun 25 '18 at 17:09

Your Answer

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

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