forked from electronero-project/electronero-network-php-sdk
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbase58.php
388 lines (352 loc) · 11.8 KB
/
base58.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
<?php
/**
*
* monerophp/base58
*
* A PHP Base58 codec
* https://github.com/monero-integrations/monerophp
*
* Using work from
* bigreddmachine [MoneroPy] (https://github.com/bigreddmachine)
* Paul Shapiro [mymonero-core-js] (https://github.com/paulshapiro)
*
* @author Monero Integrations Team <[email protected]> (https://github.com/monero-integrations)
* @copyright 2018
* @license MIT
*
* ============================================================================
*
* // Initialize class
* $base58 = new base58();
*
* // Encode a hexadecimal (base16) string as base58
* $encoded = $base58->encode('0137F8F06C971B168745F562AA107B4D172F336271BC0F9D3B510C14D3460DFB27D8CEBE561E73AC1E11833D5EA40200EB3C82E9C66ACAF1AB1A6BB53C40537C0B7A22160B0E');
*
* // Decode
* $decoded = $base58->decode('479cG5opa54beQWSyqNoWw5tna9sHUNmMTtiFqLPaUhDevpJ2YLwXAggSx5ePdeFrYF8cdbmVRSmp1Kn3t4Y9kFu7rZ7pFw');
*
*/
class base58
{
static $alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
static $encoded_block_sizes = [0, 2, 3, 5, 6, 7, 9, 10, 11];
static $full_block_size = 8;
static $full_encoded_block_size = 11;
/**
*
* Convert a hexadecimal string to a binary array
*
* @param string $hex A hexadecimal string to convert to a binary array
*
* @return array
*
*/
private function hex_to_bin($hex)
{
if (gettype($hex) != 'string') {
throw new Exception('base58->hex_to_bin(): Invalid input type (must be a string)');
}
if (strlen($hex) % 2 != 0) {
throw new Exception('base58->hex_to_bin(): Invalid input length (must be even)');
}
$res = array_fill(0, strlen($hex) / 2, 0);
for ($i = 0; $i < strlen($hex) / 2; $i++) {
$res[$i] = intval(substr($hex, $i * 2, $i * 2 + 2 - $i * 2), 16);
}
return $res;
}
/**
*
* Convert a binary array to a hexadecimal string
*
* @param array $bin A binary array to convert to a hexadecimal string
*
* @return string
*
*/
private function bin_to_hex($bin)
{
if (gettype($bin) != 'array') {
throw new Exception('base58->bin_to_hex(): Invalid input type (must be an array)');
}
$res = [];
for ($i = 0; $i < count($bin); $i++) {
$res[] = substr('0'.dechex($bin[$i]), -2);
}
return join($res);
}
/**
*
* Convert a string to a binary array
*
* @param string $str A string to convert to a binary array
*
* @return array
*
*/
private function str_to_bin($str)
{
if (gettype($str) != 'string') {
throw new Exception('base58->str_to_bin(): Invalid input type (must be a string)');
}
$res = array_fill(0, strlen($str), 0);
for ($i = 0; $i < strlen($str); $i++) {
$res[$i] = ord($str[$i]);
}
return $res;
}
/**
*
* Convert a binary array to a string
*
* @param array $bin A binary array to convert to a string
*
* @return string
*
*/
private function bin_to_str($bin)
{
if (gettype($bin) != 'array') {
throw new Exception('base58->bin_to_str(): Invalid input type (must be an array)');
}
$res = array_fill(0, count($bin), 0);
for ($i = 0; $i < count($bin); $i++) {
$res[$i] = chr($bin[$i]);
}
return preg_replace('/[[:^print:]]/', '', join($res)); // preg_replace necessary to strip errant non-ASCII characters eg. ''
}
/**
*
* Convert a UInt8BE (one unsigned big endian byte) array to UInt64
*
* @param array $data A UInt8BE array to convert to UInt64
*
* @return number
*
*/
private function uint8_be_to_64($data)
{
if (gettype($data) != 'array') {
throw new Exception ('base58->uint8_be_to_64(): Invalid input type (must be an array)');
}
$res = 0;
$i = 0;
switch (9 - count($data)) {
case 1:
$res = bcadd(bcmul($res, bcpow(2, 8)), $data[$i++]);
case 2:
$res = bcadd(bcmul($res, bcpow(2, 8)), $data[$i++]);
case 3:
$res = bcadd(bcmul($res, bcpow(2, 8)), $data[$i++]);
case 4:
$res = bcadd(bcmul($res, bcpow(2, 8)), $data[$i++]);
case 5:
$res = bcadd(bcmul($res, bcpow(2, 8)), $data[$i++]);
case 6:
$res = bcadd(bcmul($res, bcpow(2, 8)), $data[$i++]);
case 7:
$res = bcadd(bcmul($res, bcpow(2, 8)), $data[$i++]);
case 8:
$res = bcadd(bcmul($res, bcpow(2, 8)), $data[$i++]);
break;
default:
throw new Exception('base58->uint8_be_to_64: Invalid input length (1 <= count($data) <= 8)');
}
return $res;
}
/**
*
* Convert a UInt64 (unsigned 64 bit integer) to a UInt8BE array
*
* @param number $num A UInt64 number to convert to a UInt8BE array
* @param integer $size Size of array to return
*
* @return array
*
*/
private function uint64_to_8_be($num, $size)
{
if (gettype($num) != ('integer' || 'double')) {
throw new Exception ('base58->uint64_to_8_be(): Invalid input type ($num must be a number)');
}
if (gettype($size) != 'integer') {
throw new Exception ('base58->uint64_to_8_be(): Invalid input type ($size must be an integer)');
}
if ($size < 1 || $size > 8) {
throw new Exception ('base58->uint64_to_8_be(): Invalid size (1 <= $size <= 8)');
}
$res = array_fill(0, $size, 0);
for ($i = $size - 1; $i >= 0; $i--) {
$res[$i] = bcmod($num, bcpow(2, 8));
$num = bcdiv($num, bcpow(2, 8));
}
return $res;
}
/**
*
* Convert a hexadecimal (Base16) array to a Base58 string
*
* @param array $data
* @param array $buf
* @param number $index
*
* @return array
*
*/
private function encode_block($data, $buf, $index)
{
if (gettype($data) != 'array') {
throw new Exception('base58->encode_block(): Invalid input type ($data must be an array)');
}
if (gettype($buf) != 'array') {
throw new Exception('base58->encode_block(): Invalid input type ($buf must be an array)');
}
if (gettype($index) != ('integer' || 'double')) {
throw new Exception('base58->encode_block(): Invalid input type ($index must be a number)');
}
if (count($data) < 1 or count($data) > self::$full_encoded_block_size) {
throw new Exception('base58->encode_block(): Invalid input length (1 <= count($data) <= 8)');
}
$num = self::uint8_be_to_64($data);
$i = self::$encoded_block_sizes[count($data)] - 1;
while ($num > 0) {
$remainder = bcmod($num, 58);
$num = bcdiv($num, 58);
$buf[$index + $i] = ord(self::$alphabet[$remainder]);
$i--;
}
return $buf;
}
/**
*
* Encode a hexadecimal (Base16) string to Base58
*
* @param string $hex A hexadecimal (Base16) string to convert to Base58
*
* @return string
*
*/
public function encode($hex)
{
if (gettype($hex) != 'string') {
throw new Exception ('base58->encode(): Invalid input type (must be a string)');
}
$data = self::hex_to_bin($hex);
if (count($data) == 0) {
return '';
}
$full_block_count = floor(count($data) / self::$full_block_size);
$last_block_size = count($data) % self::$full_block_size;
$res_size = $full_block_count * self::$full_encoded_block_size + self::$encoded_block_sizes[$last_block_size];
$res = array_fill(0, $res_size, ord(self::$alphabet[0]));
for ($i = 0; $i < $full_block_count; $i++) {
$res = self::encode_block(array_slice($data, $i * self::$full_block_size, ($i * self::$full_block_size + self::$full_block_size) - ($i * self::$full_block_size)), $res, $i * self::$full_encoded_block_size);
}
if ($last_block_size > 0) {
$res = self::encode_block(array_slice($data, $full_block_count * self::$full_block_size, $full_block_count * self::$full_block_size + $last_block_size), $res, $full_block_count * self::$full_encoded_block_size);
}
return self::bin_to_str($res);
}
/**
*
* Convert a Base58 input to hexadecimal (Base16)
*
* @param array $data
* @param array $buf
* @param integer $index
*
* @return array
*
*/
private function decode_block($data, $buf, $index)
{
if (gettype($data) != 'array') {
throw new Exception('base58->decode_block(): Invalid input type ($data must be an array)');
}
if (gettype($buf) != 'array') {
throw new Exception('base58->decode_block(): Invalid input type ($buf must be an array)');
}
if (gettype($index) != ('integer' || 'double')) {
throw new Exception('base58->decode_block(): Invalid input type ($index must be a number)');
}
$res_size = self::index_of(self::$encoded_block_sizes, count($data));
if ($res_size <= 0) {
throw new Exception('base58->decode_block(): Invalid input length ($data must be a value from base58::$encoded_block_sizes)');
}
$res_num = 0;
$order = 1;
for ($i = count($data) - 1; $i >= 0; $i--) {
$digit = strpos(self::$alphabet, chr($data[$i]));
if ($digit < 0) {
throw new Exception("base58->decode_block(): Invalid character ($digit \"{$digit}\" not found in base58::$alphabet)");
}
$product = bcadd(bcmul($order, $digit), $res_num);
if ($product > bcpow(2, 64)) {
throw new Exception('base58->decode_block(): Integer overflow ($product exceeds the maximum 64bit integer)');
}
$res_num = $product;
$order = bcmul($order, 58);
}
if ($res_size < self::$full_block_size && bcpow(2, 8 * $res_size) <= 0) {
throw new Exception('base58->decode_block(): Integer overflow (bcpow(2, 8 * $res_size) exceeds the maximum 64bit integer)');
}
$tmp_buf = self::uint64_to_8_be($res_num, $res_size);
for ($i = 0; $i < count($tmp_buf); $i++) {
$buf[$i + $index] = $tmp_buf[$i];
}
return $buf;
}
/**
*
* Decode a Base58 string to hexadecimal (Base16)
*
* @param string $hex A Base58 string to convert to hexadecimal (Base16)
*
* @return string
*
*/
public function decode($enc)
{
if (gettype($enc) != 'string') {
throw new Exception ('base58->decode(): Invalid input type (must be a string)');
}
$enc = self::str_to_bin($enc);
if (count($enc) == 0) {
return '';
}
$full_block_count = floor(bcdiv(count($enc), self::$full_encoded_block_size));
$last_block_size = bcmod(count($enc), self::$full_encoded_block_size);
$last_block_decoded_size = self::index_of(self::$encoded_block_sizes, $last_block_size);
$data_size = $full_block_count * self::$full_block_size + $last_block_decoded_size;
$data = array_fill(0, $data_size, 0);
for ($i = 0; $i <= $full_block_count; $i++) {
$data = self::decode_block(array_slice($enc, $i * self::$full_encoded_block_size, ($i * self::$full_encoded_block_size + self::$full_encoded_block_size) - ($i * self::$full_encoded_block_size)), $data, $i * self::$full_block_size);
}
if ($last_block_size > 0) {
$data = self::decode_block(array_slice($enc, $full_block_count * self::$full_encoded_block_size, $full_block_count * self::$full_encoded_block_size + $last_block_size), $data, $full_block_count * self::$full_block_size);
}
return self::bin_to_hex($data);
}
/**
*
* Search an array for a value
* Source: https://stackoverflow.com/a/30994678
*
* @param array $haystack An array to search
* @param string $needle A string to search for
*)
* @return number The index of the element found (or -1 for no match)
*
*/
private function index_of($haystack, $needle)
{
if (gettype($haystack) != 'array') {
throw new Exception ('base58->decode(): Invalid input type ($haystack must be an array)');
}
// if (gettype($needle) != 'string') {
// throw new Exception ('base58->decode(): Invalid input type ($needle must be a string)');
// }
foreach ($haystack as $key => $value) if ($value === $needle) return $key;
return -1;
}
}