UNPKG

1.71 kBJavaScriptView Raw
1// Base58 encoding/decoding
2// Originally written by Mike Hearn for BitcoinJ
3// Copyright (c) 2011 Google Inc
4// Ported to JavaScript by Stefan Thomas
5// Merged Buffer refactorings from base58-native by Stephen Pair
6// Copyright (c) 2013 BitPay Inc
7
8var assert = require('assert')
9var BigInteger = require('bigi')
10
11var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
12var ALPHABET_BUF = new Buffer(ALPHABET, 'ascii')
13var ALPHABET_MAP = {}
14for(var i = 0; i < ALPHABET.length; i++) {
15 ALPHABET_MAP[ALPHABET.charAt(i)] = BigInteger.valueOf(i)
16}
17var BASE = new BigInteger('58')
18
19function encode(buffer) {
20 var bi = BigInteger.fromBuffer(buffer)
21 var result = new Buffer(buffer.length << 1)
22
23 var i = result.length - 1
24 while (bi.signum() > 0) {
25 var remainder = bi.mod(BASE)
26 bi = bi.divide(BASE)
27
28 result[i] = ALPHABET_BUF[remainder.intValue()]
29 i--
30 }
31
32 // deal with leading zeros
33 var j = 0
34 while (buffer[j] === 0) {
35 result[i] = ALPHABET_BUF[0]
36 j++
37 i--
38 }
39
40 return result.slice(i + 1, result.length).toString('ascii')
41}
42
43function decode(string) {
44 if (string.length === 0) return new Buffer(0)
45
46 var num = BigInteger.ZERO
47
48 for (var i = 0; i < string.length; i++) {
49 num = num.multiply(BASE)
50
51 var figure = ALPHABET_MAP[string.charAt(i)]
52 assert.notEqual(figure, undefined, 'Non-base58 character')
53
54 num = num.add(figure)
55 }
56
57 // deal with leading zeros
58 var j = 0
59 while ((j < string.length) && (string[j] === ALPHABET[0])) {
60 j++
61 }
62
63 var buffer = num.toBuffer()
64 var leadingZeros = new Buffer(j)
65 leadingZeros.fill(0)
66
67 return Buffer.concat([leadingZeros, buffer])
68}
69
70module.exports = {
71 encode: encode,
72 decode: decode
73}