GET IN TOUCH WITH PAKKO, CREATIVE DIRECTOR ALIGNED FOR THE FUTURE OF CREATIVITY.
PAKKO@PAKKO.ORG

LA | DUBAI | NY | CDMX

PLAY PC GAMES? ADD ME AS A FRIEND ON STEAM

 


Back to Top

Pakko De La Torre // Creative Director

blockchain - What are the equations to convert between bits and difficulty? - Bitcoin Stack Exchange

blockchain – What are the equations to convert between bits and difficulty? – Bitcoin Stack Exchange

There are 3 representations of the same thing (with varying degrees of precision) in Bitcoin:

and 6 methods are necessary to convert between any two of these:

The Bitcoin source code can do the conversion from bits -> difficulty as asked in the question, but cannot do the conversion from difficulty -> bits as also asked in the question.

I have written my own implementation of the difficulty -> bits conversion in vanilla Javascript by mimicking the target -> bits conversion where possible, plus some additional checks:

It is possible to validate that the above function gives correct answers by doing the following conversion:

Where bits -> difficulty is done using Bitcoin’s GetDifficulty() and difficulty -> bits is done using difficulty2bits() above. If we arrive back at the same bits value then the difficulty2bits() function is correct. The only exception is when (bits & 0x00800000) != 0, since this means that bits is a negative number, whereas difficulty is always a positive number in Bitcoin.

I have tested the above difficulty2bits() function and it does return the same result as the original bits value. If you want to do the tests yourself then I have created a live conversion tool on my blog where you can do any of the 6 conversions listed above in real time (I have transcribed Bitcoin’s SetCompact(), GetDifficulty() and GetCompact() into Javascript): https://analysis.null.place/how-do-the-bitcoin-mining-algorithms-work/#form7

Note that numbers in Javascript are IEEE 754 double precision – the same precision as the difficulty in the Bitcoin source, so Javascript is as accurate as the Bitcoin source for all bits/difficulty/target conversions. However, to assuage scepticism I have also included the relevant unit tests from Bitcoin’s bitcoin/src/test/blockchain_tests.cpp and bitcoin/src/test/arith_uint256_tests.cpp files on the blog just below the aforementioned tool – all tests pass.

This content was originally published here.