1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 | var assert = require('assert')
|
9 | var BigInteger = require('bigi')
|
10 |
|
11 | var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
|
12 | var ALPHABET_BUF = new Buffer(ALPHABET, 'ascii')
|
13 | var ALPHABET_MAP = {}
|
14 | for(var i = 0; i < ALPHABET.length; i++) {
|
15 | ALPHABET_MAP[ALPHABET.charAt(i)] = BigInteger.valueOf(i)
|
16 | }
|
17 | var BASE = new BigInteger('58')
|
18 |
|
19 | function 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 |
|
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 |
|
43 | function 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 |
|
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 |
|
70 | module.exports = {
|
71 | encode: encode,
|
72 | decode: decode
|
73 | }
|