-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathUtils.php
111 lines (94 loc) · 2.48 KB
/
Utils.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
104
105
106
107
108
109
110
111
<?php
declare(strict_types=1);
namespace AndKom\Bitcoin\Address;
use StephenHill\Base58;
/**
* Class Utils
* @package AndKom\Bitcoin\Address
*/
class Utils
{
/**
* @param string $data
* @return string
*/
static public function sha256(string $data): string
{
return hash('sha256', $data, true);
}
/**
* @param string $data
* @return string
*/
static public function hash256(string $data): string
{
return static::sha256(static::sha256($data));
}
/**
* @param string $data
* @return string
*/
static public function hash160(string $data): string
{
return hash('ripemd160', static::sha256($data), true);
}
/**
* @param string $hex
* @return string
* @throws Exception
*/
static public function hex2bin(string $hex): string
{
$bin = @hex2bin($hex);
if (false === $bin) {
throw new Exception('Invalid hex-encoded string.');
}
return $bin;
}
/**
* @param string $hash
* @param string $prefix
* @return string
* @throws \Exception
*/
static public function base58encode(string $hash, string $prefix = "\x00"): string
{
$payload = $prefix . Validate::pubKeyHash($hash);
$checksum = substr(static::hash256($payload), 0, 4);
$address = $payload . $checksum;
$base58 = (new Base58())->encode($address);
return $base58;
}
/**
* @param string $base58
* @return array
* @throws \Exception
*/
static public function base58decode(string $base58): array
{
$address = (new Base58())->decode($base58);
$addressLen = strlen($address);
if (25 != $addressLen) {
throw new Exception(sprintf('Invalid address length: %d.', $addressLen));
}
$payload = substr($address, 0, -4);
$checksum = substr($address, -4);
$checksumCheck = substr(static::hash256($payload), 0, 4);
if ($checksum != $checksumCheck) {
throw new Exception('Invalid checksum.');
}
$prefix = $payload[0];
$hash = substr($payload, 1, 20);
return [$hash, $prefix];
}
/**
* @param string $tag
* @param string $data
* @return string
*/
static public function taggedHash(string $tag, string $data): string
{
$tagHash = static::sha256($tag);
return static::sha256($tagHash . $tagHash . $data);
}
}