-
Notifications
You must be signed in to change notification settings - Fork 373
/
base58.js
59 lines (46 loc) · 1.31 KB
/
base58.js
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
// 3rd party
var int = require('int');
// prep position lookup table
var vals = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
var positions = {};
for (var i=0 ; i < vals.length ; ++i) {
positions[vals[i]] = i;
}
/// decode a base58 string payload into a hex representation
function decode(payload) {
var base = 58;
var length = payload.length;
var num = int(0);
var leading_zero = 0;
var seen_other = false;
for (var i=0; i<length ; ++i) {
var char = payload[i];
var p = positions[char];
// if we encounter an invalid character, decoding fails
if (p === undefined) {
throw new Error('invalid base58 string: ' + payload);
}
num = num.mul(base).add(p);
if (char == '1' && !seen_other) {
++leading_zero;
}
else {
seen_other = true;
}
}
var hex = num.toString(16);
// num.toString(16) does not have leading 0
if (hex.length % 2 !== 0) {
hex = '0' + hex;
}
// strings starting with only ones need to be adjusted
// e.g. '1' should map to '00' and not '0000'
if (leading_zero && !seen_other) {
--leading_zero;
}
while (leading_zero-- > 0) {
hex = '00' + hex;
}
return hex;
}
module.exports.decode = decode;