1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace mattvb91\TronTrx\Support; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* @codeCoverageIgnore |
7
|
|
|
*/ |
8
|
|
|
class Base58Check |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* Encode Base58Check |
12
|
|
|
* |
13
|
|
|
* @param string $string |
14
|
|
|
* @param int $prefix |
15
|
|
|
* @param bool $compressed |
16
|
|
|
* @return string |
17
|
|
|
*/ |
18
|
|
|
public static function encode(string $string, int $prefix = 128, bool $compressed = true) |
19
|
|
|
{ |
20
|
|
|
$string = hex2bin($string); |
21
|
|
|
|
22
|
|
|
if ($prefix) { |
23
|
|
|
$string = chr($prefix) . $string; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
if ($compressed) { |
27
|
|
|
$string .= chr(0x01); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
$string = $string . substr(Hash::SHA256(Hash::SHA256($string)), 0, 4); |
31
|
|
|
|
32
|
|
|
$base58 = Base58::encode(Crypto::bin2bc($string)); |
33
|
|
|
for ($i = 0; $i < strlen($string); $i++) { |
34
|
|
|
if ($string[$i] != "\x00") { |
35
|
|
|
break; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
$base58 = '1' . $base58; |
39
|
|
|
} |
40
|
|
|
return $base58; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Decoding from Base58Check |
45
|
|
|
* |
46
|
|
|
* @param string $string |
47
|
|
|
* @param int $removeLeadingBytes |
48
|
|
|
* @param int $removeTrailingBytes |
49
|
|
|
* @param bool $removeCompression |
50
|
|
|
* @return bool|string |
51
|
|
|
*/ |
52
|
|
|
public static function decode(string $string, int $removeLeadingBytes = 1, int $removeTrailingBytes = 4, bool $removeCompression = true) |
53
|
|
|
{ |
54
|
|
|
$string = bin2hex(Crypto::bc2bin(Base58::decode($string))); |
55
|
|
|
|
56
|
|
|
//If end bytes: Network type |
57
|
|
|
if ($removeLeadingBytes) { |
58
|
|
|
$string = substr($string, $removeLeadingBytes * 2); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
//If the final bytes: Checksum |
62
|
|
|
if ($removeTrailingBytes) { |
63
|
|
|
$string = substr($string, 0, -($removeTrailingBytes * 2)); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
//If end bytes: compressed byte |
67
|
|
|
if ($removeCompression) { |
68
|
|
|
$string = substr($string, 0, -2); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
return $string; |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|