bitcoinjs-lib/src/base58.js

74 lines
1.7 KiB
JavaScript
Raw Normal View History

// 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
2014-05-28 13:29:01 +10:00
var assert = require('assert')
2014-05-03 10:04:54 +08:00
var BigInteger = require('bigi')
var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
var ALPHABET_BUF = new Buffer(ALPHABET, 'ascii')
var ALPHABET_MAP = {}
for(var i = 0; i < ALPHABET.length; i++) {
ALPHABET_MAP[ALPHABET[i]] = BigInteger.valueOf(i)
}
var BASE = BigInteger.valueOf(58)
function encode(buffer) {
2014-04-22 02:19:30 +10:00
var bi = BigInteger.fromBuffer(buffer)
var result = new Buffer(buffer.length << 1)
var i = result.length - 1
while (bi.compareTo(BigInteger.ZERO) > 0) {
var remainder = bi.mod(BASE)
bi = bi.divide(BASE)
result[i] = ALPHABET_BUF[remainder.intValue()]
i--
2014-03-24 16:00:14 +11:00
}
// deal with leading zeros
var j = 0
while (buffer[j] === 0) {
result[i] = ALPHABET_BUF[0]
j++
i--
2014-03-24 16:00:14 +11:00
}
return result.slice(i + 1, result.length).toString('ascii')
2014-03-24 06:01:33 +11:00
}
function decode(string) {
if (string.length === 0) return new Buffer(0)
var num = BigInteger.ZERO.clone()
2014-03-24 16:00:14 +11:00
for (var i = 0; i < string.length; i++) {
num = num.multiply(BASE)
2014-05-28 13:29:01 +10:00
var figure = ALPHABET_MAP[string.charAt(i)]
assert.notEqual(figure, undefined, 'Non-base58 character')
num = num.add(figure)
}
2011-05-04 17:02:56 +01:00
// deal with leading zeros
var i = 0
while ((i < string.length) && (string[i] === ALPHABET[0])) {
i++
}
2014-04-24 07:22:10 +10:00
var buffer = num.toBuffer()
var leadz = new Buffer(i)
leadz.fill(0)
2014-04-24 07:22:10 +10:00
return Buffer.concat([leadz, buffer])
2014-03-08 13:02:40 +08:00
}
2014-03-24 15:53:57 +11:00
module.exports = {
encode: encode,
decode: decode
2014-03-24 15:53:57 +11:00
}