-
Notifications
You must be signed in to change notification settings - Fork 0
/
helper.php
103 lines (78 loc) · 2.48 KB
/
helper.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
103
<?php
class Helper
{
protected $payloadLengthExtra = 14000;
protected $payloadProofTrials = 320;
public function decodeVarInt($input)
{
$int = unpack('C', $input[0]);
$int = current($int);
if ($int >= 253) {
if ((int)$int === 253) {
$int = unpack('n', substr($input, 1, 2));
return array('len' => 3, 'int' => current($int));
} else if ((int)$int === 254) {
$int = unpack('N', substr($input, 1, 5));
return array('len' => 5, 'int' => current($int));
}
}
return array('len' => 1, 'int' => $int);
}
public function varInt($input)
{
// TODO
return pack('C', $input);
}
public function convertTime($payload)
{
$fortySixBits = false;
$timestamp = substr($payload, 0, 4);
$timestamp = $this->unpack_double($timestamp, false);
if ($timestamp == 0) {
$fortySixBits = true;
$timestamp = substr($payload, 0, 8);
$timestamp = $this->unpack_double($timestamp, false);
}
return array($timestamp, $fortySixBits);
}
public function checkPOW($payload)
{
$nonce = substr($payload, 0, 8);
$payload = substr($payload, 8);
$hash = hash('sha512', $payload, true);
$pow = hash('sha512', hash('sha512', $nonce . $hash, true), true);
$pow = substr($pow, 0, 8);
$pow = $this->unpack_double($pow, false);
$target = pow(2, 64) / ((strlen($payload) + $this->payloadLengthExtra) * $this->payloadProofTrials);
if ($pow <= $target) {
return true;
}
return false;
}
public function pack_double($in, $pad_to_bits = 64, $little_endian = true)
{
$in = decbin($in);
$in = str_pad($in, $pad_to_bits, '0', STR_PAD_LEFT);
$out = '';
for ($i = 0, $len = strlen($in); $i < $len; $i += 8) {
$out .= chr(bindec(substr($in, $i, 8)));
}
if($little_endian) {
$out = strrev($out);
}
return $out;
}
function unpack_double($bytes, $little_endian = true)
{
if ($little_endian) {
$bytes = strrev($bytes);
}
$result = '0';
while (strlen($bytes)) {
$ord = ord(substr($bytes, 0, 1));
$result = bcadd(bcmul($result, 256), $ord);
$bytes = substr($bytes, 1);
}
return $result;
}
}