bitcoinjs-lib/src/base58.js

70 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-03-31 11:47:47 +08:00
var BigInteger = require('./jsbn/jsbn')
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) {
var bi = BigInteger.fromByteArrayUnsigned(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)
num = num.add(ALPHABET_MAP[string.charAt(i)])
}
2011-05-04 17:02:56 +01:00
// deal with leading zeros
var i = 0
while ((i < string.length) && (string[i] === ALPHABET[0])) {
i++
}
// FIXME: If BigInteger supported buffers, this could be a copy
var buffer = new Buffer(num.toByteArrayUnsigned())
var padding = new Buffer(i)
padding.fill(0)
return Buffer.concat([padding, 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
}