Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jesobreira
Created October 15, 2019 22:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jesobreira/ee6503c7d70a19f8ab48ceb42ef6aaa7 to your computer and use it in GitHub Desktop.
Save jesobreira/ee6503c7d70a19f8ab48ceb42ef6aaa7 to your computer and use it in GitHub Desktop.
Parse Blockchain Block Header
<?php
function parse_block($block) {
$return = [
'version' => null,
'prevBlockHash' => null,
'merkleRoot' => null,
'timestamp' => null,
'target' => null,
'nonce' => null
];
// first 4 bytes (8 hex bytes) are the version
$version = pack("H*", strrev(substr($block, 0, 8)));
$return['version'] = unpack("l", $version)[1];
// next 32 bytes (64 hex bytes) we will have the previous block hash
$prevBlockHash = strrev(substr($block, 8, 64));
for ($i = 0; $i < strlen($prevBlockHash); $i += 2)
$return['prevBlockHash'] .= $prevBlockHash[$i + 1] . $prevBlockHash[$i];
// next 32 bytes we will have the merkle root of the txes on this block
$merkleRoot = strrev(substr($block, 72, 64));
for ($i = 0; $i < strlen($merkleRoot); $i += 2)
$return['merkleRoot'] .= $merkleRoot[$i + 1] . $merkleRoot[$i];
// next 4 bytes we will have an uint32_t with the timestamp
$return['timestamp'] = unpack("V", pack("H*", substr($block, 136, 8)))[1];
// next 4 bytes, another uint32_t with the block threshould
$return['target'] = unpack("V", pack("H*", substr($block, 144, 8)))[1];
// finally, the nonce
$return['nonce'] = unpack("V", pack("H*", substr($block, 152, 8)))[1];
return $return;
}
var_dump( parse_block("000000204f5ce6ff5b197f40502d00473b3d5272ca2ff7049fda120000000000000000009c7f1fb04cd7e220f7351f6b0c11cb7dc347d0380bbd1e7ad329a56138772b941139a65d5ca3151706190dc2"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment