Blockchain – What is the equation to convert bits to difficulty?
In Bitcoin, there are three representations of the same thing (with different degrees of precision):
- bit – 32-bit unsigned integer
- Destination – unsigned integer 256 bits
- Difficulty – Double-precision floating point (64-bit)
You will need 6 methods to convert any two of the following:
- bit -> target(
SetCompact()
In ~bitcoin/src/arith_uint256.cpp
) - Beat -> Difficulty (
GetDifficulty()
In ~bitcoin/src/rpc/blockchain.cpp
) - Target -> Bit(
GetCompact()
In ~bitcoin/src/arith_uint256.cpp
) - Target -> Difficulty (same as Target -> Beat -> Difficulty)
- Difficulty -> Beat (not done next time)
bitcoin/src
) - Difficulty -> Goal (same as Difficulty -> Beat -> Goal)
The Bitcoin source code can perform the conversion from bits -> difficulty as requested in the question, but it cannot perform the conversion from difficulty to bits -> bits as requested in the question.
I’ve written my own implementation of the difficulty->bit conversion in vanilla Javascript, with a few additional checks to mimic the target->bit conversion where possible.
function difficulty2bits(difficulty) word;
return bits;
You can check if the above function gives the correct answer by performing the following transformation:
bits -> difficulty -> bits
Bit -> If the difficulty is done using Bitcoin GetDifficulty()
Difficulty -> The bit is completed using: difficulty2bits()
above. If it arrives again with the same bit value, difficulty2bits()
The function is correct. The only exceptions are: (bits & 0x00800000) != 0
This is because bits are negative whereas in Bitcoin this means difficulty is always positive.
I tested the above difficulty2bits()
It is a function and returns a result equal to the original bit value. If you’d like to test it out yourself, I’ve created a live conversion tool on my blog that allows you to perform any of the six conversions listed above in real time. SetCompact()
, GetDifficulty()
and GetCompact()
(with Javascript): https://analytic.null.place/how-do-the-bitcoin-mining-algorithms-work/#form7
Javascript’s numbers are IEEE 754 double precision (same precision as the Bitcoin source’s difficulty), so Javascript is as accurate as the Bitcoin source for any bit/difficulty/destination conversion. However, to alleviate any skepticism, we have also included relevant unit tests for Bitcoin. bitcoin/src/test/blockchain_tests.cpp
and bitcoin/src/test/arith_uint256_tests.cpp
If you download the files from the blog directly below the aforementioned tools, all tests will pass.