forked from in3rsha/learnmeabitcoin-code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
merkleroot.php
102 lines (73 loc) · 2.94 KB
/
merkleroot.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#!/usr/bin/php
<?php
// Swap Endian function
function swapendian($data) {
return implode('', array_reverse(str_split($data, 2)));
}
// Merkle Root Function
function merklerootbinary($txids) {
// Stop recursion if there is only one hash value left, because that's the merkle root.
if (count($txids) == 1) {
$merkleroot = $txids[0];
return $merkleroot;
}
else {
// Create the new array of hashes
while (count($txids) > 0) {
if (count($txids) >= 2) {
// Get first two
$pair_first = $txids[0];
$pair_second = $txids[1];
// Hash them (double SHA256)
$pair = $pair_first.$pair_second;
$pairhashes[] = hash('sha256', hash('sha256', $pair, true), true);
// Remove those two from the array
unset($txids[0]);
unset($txids[1]);
// Re-set the indexes (the above just nullifies the values) and make a new array without the original first two slots.
$txids = array_values($txids);
}
if (count($txids) == 1) {
// Get the first one twice
$pair_first = $txids[0];
$pair_second = $txids[0];
// Hash it with itself (double SHA256)
$pair = $pair_first.$pair_second;
$pairhashes[] = hash('sha256', hash('sha256', $pair, true), true);
// Remove it from the array
unset($txids[0]);
// Re-set the indexes (the above just nullifies the values) and make a new array without the original first two slots.
$txids = array_values($txids);
}
}
// Recursion bit. Re-apply this function to the new array of hashes we've just created.
return merklerootbinary($pairhashes);
}
}
function merkleroot($txids) {
// Convert txids in to big endian (BE), because that's the format they need to be in to get the merkle root.
foreach ($txids as $txid) {
$txidsBE[] = swapendian($txid);
}
// Now convert each of these txids in to binary, because the hash function wants the binary value, not the hex.
foreach ($txidsBE as $txidBE) {
$txidsBEbinary[] = hex2bin($txidBE);
}
// Work out the merkle root (in binary) using that lovely recursive function above.
$merkleroot = merklerootbinary($txidsBEbinary);
// Convert the merkle root in to hexadecimal and little-endian, because that's how it's stored in the block header.
$merkleroot = swapendian(bin2hex($merkleroot));
// Return it :)
return $merkleroot;
}
// Get lines from STDIN
$lines = file('php://stdin');
// Clean up input (remove whitespace and ")
$txids = [];
foreach ($lines as $line) {
$txids[] = str_replace('"', '', trim($line));
}
// Work out the Merkle Root
$merkleroot = merkleroot($txids);
// Print Result
echo $merkleroot."\n";