UNPKG

2.03 kBJavaScriptView Raw
1var ALPHABET, ALPHABET_MAP, Base58, i;
2
3Base58 = {};
4
5ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
6
7ALPHABET_MAP = {};
8
9i = 0;
10
11while (i < ALPHABET.length) {
12 ALPHABET_MAP[ALPHABET.charAt(i)] = i;
13 i++;
14}
15
16Base58.encode = function(buffer) {
17 var carry, digits, j;
18 if (buffer.length === 0) {
19 return "";
20 }
21 i = void 0;
22 j = void 0;
23 digits = [0];
24 i = 0;
25 while (i < buffer.length) {
26 j = 0;
27 while (j < digits.length) {
28 digits[j] <<= 8;
29 j++;
30 }
31 digits[0] += buffer[i];
32 carry = 0;
33 j = 0;
34 while (j < digits.length) {
35 digits[j] += carry;
36 carry = (digits[j] / 58) | 0;
37 digits[j] %= 58;
38 ++j;
39 }
40 while (carry) {
41 digits.push(carry % 58);
42 carry = (carry / 58) | 0;
43 }
44 i++;
45 }
46 i = 0;
47 while (buffer[i] === 0 && i < buffer.length - 1) {
48 digits.push(0);
49 i++;
50 }
51 return digits.reverse().map(function(digit) {
52 return ALPHABET[digit];
53 }).join("");
54};
55
56Base58.decode = function(string) {
57 var bytes, c, carry, j;
58 if (string.length === 0) {
59 return new (typeof Uint8Array !== "undefined" && Uint8Array !== null ? Uint8Array : Buffer)(0);
60 }
61 i = void 0;
62 j = void 0;
63 bytes = [0];
64 i = 0;
65 while (i < string.length) {
66 c = string[i];
67 if (!(c in ALPHABET_MAP)) {
68 throw "Base58.decode received unacceptable input. Character '" + c + "' is not in the Base58 alphabet.";
69 }
70 j = 0;
71 while (j < bytes.length) {
72 bytes[j] *= 58;
73 j++;
74 }
75 bytes[0] += ALPHABET_MAP[c];
76 carry = 0;
77 j = 0;
78 while (j < bytes.length) {
79 bytes[j] += carry;
80 carry = bytes[j] >> 8;
81 bytes[j] &= 0xff;
82 ++j;
83 }
84 while (carry) {
85 bytes.push(carry & 0xff);
86 carry >>= 8;
87 }
88 i++;
89 }
90 i = 0;
91 while (string[i] === "1" && i < string.length - 1) {
92 bytes.push(0);
93 i++;
94 }
95 return new (typeof Uint8Array !== "undefined" && Uint8Array !== null ? Uint8Array : Buffer)(bytes.reverse());
96};
97
98module.exports = Base58;