-
Notifications
You must be signed in to change notification settings - Fork 1
/
base58.js
76 lines (60 loc) · 1.88 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Base58 encoding/decoding
// Originally written by Mike Hearn for BitcoinJ
// Copyright (c) 2011 Google Inc
// Ported to JavaScript by Stefan Thomas
// Merged Buffer refactorings from base58-native by Stephen Pair
// Copyright (c) 2013 BitPay Inc
var Base58 = {}
Base58.alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
Base58.alphabetMap = {}
for(var i = 0; i < Base58.alphabet.length; i++) {
Base58.alphabetMap[Base58.alphabet.charAt(i)] = i
}
Base58.encode = function(buffer) {
if (buffer.length === 0) return ''
var i, j, digits = [0]
for (i = 0; i < buffer.length; i++) {
for (j = 0; j < digits.length; j++) digits[j] <<= 8
digits[digits.length - 1] += buffer[i]
var carry = 0
for (j = digits.length - 1; j >= 0; j--){
digits[j] += carry
carry = (digits[j] / 58) | 0
digits[j] %= 58
}
while (carry) {
digits.unshift(carry)
carry = (digits[0] / 58) | 0
digits[0] %= 58
}
}
// deal with leading zeros
for (i = 0; i < buffer.length - 1 && buffer[i] == 0; i++) digits.unshift(0)
return digits.map(function(digit) { return Base58.alphabet[digit] }).join('')
}
Base58.decode = function(string) {
if (string.length === 0) return (new Uint8Array())
var input = string.split('').map(function(c){
return Base58.alphabetMap[c]
})
var i, j, bytes = [0]
for (i = 0; i < input.length; i++) {
for (j = 0; j < bytes.length; j++) bytes[j] *= 58
bytes[bytes.length - 1] += input[i]
var carry = 0
for (j = bytes.length - 1; j >= 0; j--){
bytes[j] += carry
carry = bytes[j] >> 8
bytes[j] &= 0xff
}
while (carry) {
bytes.unshift(carry)
carry = bytes[0] >> 8
bytes[0] &= 0xff
}
}
// deal with leading zeros
for (i = 0; i < input.length - 1 && input[i] == 0; i++) bytes.unshift(0)
return (new Uint8Array(bytes))
}
module.exports = Base58;