Looking at how the difficulty is being calculated
https://en.bitcoin.it/wiki/Difficulty and trying to port / implement nBits to difficulty in PHP but not having much luck
$nBits = 404103235;
$difficulty = calculate_difficulty($nBits);
echo "difficulty = $difficulty" . PHP_EOL; // 404103235 nBits should be difficulty: 49,692,386,354.894
function calculate_target($nBits){
$shift = 8 * ((($nBits >> 24) & 0xff) - 3);
echo $shift . PHP_EOL;
$bits = $nBits & 0x7fffff;
echo $bits . PHP_EOL;
$sign = (nBits & 0x800000) ? -1 : 1;
echo $sign . PHP_EOL;
return ($shift >= 0) ? $sign * ($bits << $shift) : $sign * ($bits >> -$shift);
}
function target_to_difficulty($target){
return ((1 << 224) - 1) * 1000 / ($target + 1) / 1000.0;
}
function calculate_difficulty($nBits){
return target_to_difficulty(calculate_target($nBits));
}
Output:
168
1450051
1
difficulty = 2.6938707666768E-9
Expecting something like:
168
1450051
1
542528489142608155505707877213460200687386787807972294656
I guess I need something like a BigNum in C/C++? Can this be done in PHP? Any ideas?