bitcoinjs-lib/src/base58.js

83 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
2014-03-31 11:47:47 +08:00
var BigInteger = require('./jsbn/jsbn')
// FIXME: ? This is a Base58Check alphabet
2014-03-31 11:47:47 +08:00
var alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
var base = BigInteger.valueOf(58)
var alphabetMap = {}
2014-03-31 11:47:47 +08:00
for (var i=0; i<alphabet.length; ++i) {
var chr = alphabet[i]
alphabetMap[chr] = BigInteger.valueOf(i)
}
// encode a byte array into a base58 encoded String
// @return String
function encode(buffer) {
var bi = BigInteger.fromByteArrayUnsigned(buffer)
2014-03-31 11:47:47 +08:00
var chars = []
2014-03-24 16:00:14 +11:00
while (bi.compareTo(base) >= 0) {
2014-03-31 11:47:47 +08:00
var mod = bi.mod(base)
bi = bi.subtract(mod).divide(base)
chars.push(alphabet[mod.intValue()])
2014-03-24 16:00:14 +11:00
}
2014-03-31 11:47:47 +08:00
chars.push(alphabet[bi.intValue()])
2014-03-24 16:00:14 +11:00
// Convert leading zeros too.
for (var i=0; i<buffer.length; i++) {
if (buffer[i] !== 0x00) break
chars.push(alphabet[0])
2014-03-24 16:00:14 +11:00
}
2014-03-31 11:47:47 +08:00
return chars.reverse().join('')
2014-03-24 06:01:33 +11:00
}
// decode a base58 encoded String into a byte array
// @return Array
function decode(str) {
2014-03-31 11:47:47 +08:00
var num = BigInteger.valueOf(0)
2014-03-31 11:47:47 +08:00
var leading_zero = 0
var seen_other = false
for (var i=0; i<str.length; ++i) {
var chr = str[i]
var bi = alphabetMap[chr]
2014-03-24 16:00:14 +11:00
// if we encounter an invalid character, decoding fails
if (bi === undefined) {
throw new Error('invalid base58 string: ' + str)
2014-03-24 16:00:14 +11:00
}
num = num.multiply(base).add(bi)
2014-03-24 16:00:14 +11:00
if (chr === '1' && !seen_other) {
2014-03-31 11:47:47 +08:00
++leading_zero
} else {
seen_other = true
2014-03-24 16:00:14 +11:00
}
}
2011-05-04 17:02:56 +01:00
2014-03-31 11:47:47 +08:00
var bytes = num.toByteArrayUnsigned()
2011-05-04 17:02:56 +01:00
// remove leading zeros
while (leading_zero-- > 0) {
2014-03-31 11:47:47 +08:00
bytes.unshift(0)
}
return new Buffer(bytes)
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
}