// GET BLOCK DATA
$version = $_GET['version'];
$hashPrevBlock = $_GET['hashPrevBlock'];
$hashMerkleRoot = $_GET['hashMerkleRoot'];
$time = $_GET['time'];
$bits = $_GET['bits'];
$nonce = $_GET['nonce'];
?>
// SANITIZE
//version
$version = filter_var($version, FILTER_SANITIZE_NUMBER_INT);
//hashPrevBlock
$hashPrevBlock = htmlspecialchars($hashPrevBlock);
//hashMerkleRoot
$hashMerkleRoot = htmlspecialchars($hashMerkleRoot);
//time
$time = str_replace('%3A', ':', $time); // get converts ":" to "%3A"
$time = htmlspecialchars($time);
//bits
$bits = htmlspecialchars($bits);
//nonce
$nonce = filter_var($nonce, FILTER_SANITIZE_NUMBER_FLOAT);
?>
Hash a block.
// FIELD VARIANTS
//time (timestamp or unix)
// if timestamp (=> unix)
if (strpos($time, '-')) { // simple check to see if timestamp
$time = strtotime($time);
}
?>
// FIND TARGET
function bcdechex($dec) {
$last = bcmod($dec, 16);
$remain = bcdiv(bcsub($dec, $last), 16);
if ($remain == 0) {
return dechex($last);
} else {
return bcdechex($remain) . dechex($last);
}
}
function bchexdec($hex) {
if (strlen($hex) == 1) {
return hexdec($hex);
} else {
$remain = substr($hex, 0, -1);
$last = substr($hex, -1);
return bcadd(bcmul(16, bchexdec($remain)), hexdec($last));
}
}
$first = substr($bits, 0, 2);
$last = substr($bits, 2);
$target = bcmul(hexdec($last), bcpow(2, (8 * (hexdec($first) - 3))));
$target_hex = bcdechex($target);
$target_hex = str_pad($target_hex, 64, '0', STR_PAD_LEFT);
?>
// CONVERT FIELDS //
//This reverses and then swaps every other char
function SwapOrder($in) {
$Split = str_split(strrev($in));
$x = '';
for ($i = 0; $i < count($Split); $i += 2) {
$x .= $Split[$i + 1] . $Split[$i];
}
return $x;
}
//convert to binary then hex (littleEndian)
function littleEndian($value) {
return implode(unpack('H*', pack("V*", $value)));
}
// 1. convert version to hex
$version = (int)$version;
$version = littleEndian($version);
// 2. rearrange
$hashPrevBlock = SwapOrder($hashPrevBlock);
// 3. rearrange
$hashMerkleRoot = SwapOrder($hashMerkleRoot);
// 4 convert to hex
$time = littleEndian($time);
// 5. rearrange
$bits = SwapOrder($bits);
// 6. convert nonce to hex
$nonce = (float)$nonce;
$nonce = littleEndian($nonce);
?>
// FIND RESULT //
// 1. concat it all
$header_hex = $version . $hashPrevBlock . $hashMerkleRoot . $time . $bits . $nonce;
// 2. convert from hex to binary
$header_bin = hex2bin($header_hex);
// 3. hash it
$pass1 = hash('sha256', $header_bin);
// 4. convert from hex to binary
$pass1 = hex2bin($pass1);
// 5. hash it for the second time
$pass2 = hash('sha256', $pass1);
// TA DA
$result_hex = SwapOrder($pass2);
$result = bchexdec($result_hex);
?>
$success = ($result < $target);
if ($success) {
$css = 'class="green"';
} else {
$css = 'class="red"';
}
?>
if ($_GET['submit']) : ?>
Results
if ($success) {
echo 'Success!';
} else {
echo 'Fail :(';
}
?>
endif; ?>