bitcoinjs-lib/src/base58.js

72 lines
1.9 KiB
JavaScript
Raw Normal View History

(function (Bitcoin) {
2012-01-11 02:40:45 +01:00
Bitcoin.Base58 = {
alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",
validRegex: /^[1-9A-HJ-NP-Za-km-z]+$/,
2012-01-11 02:40:45 +01:00
base: BigInteger.valueOf(58),
2011-05-04 17:02:56 +01:00
2012-01-11 02:40:45 +01:00
/**
* Convert a byte array to a base58-encoded string.
*
* Written by Mike Hearn for BitcoinJ.
* Copyright (c) 2011 Google Inc.
*
* Ported to JavaScript by Stefan Thomas.
*/
encode: function (input) {
var bi = BigInteger.fromByteArrayUnsigned(input);
var chars = [];
2011-05-04 17:02:56 +01:00
2012-01-11 02:40:45 +01:00
while (bi.compareTo(B58.base) >= 0) {
var mod = bi.mod(B58.base);
chars.unshift(B58.alphabet[mod.intValue()]);
bi = bi.subtract(mod).divide(B58.base);
}
chars.unshift(B58.alphabet[bi.intValue()]);
2011-05-04 17:02:56 +01:00
2012-01-11 02:40:45 +01:00
// Convert leading zeros too.
for (var i = 0; i < input.length; i++) {
if (input[i] == 0x00) {
chars.unshift(B58.alphabet[0]);
} else break;
}
2011-05-04 17:02:56 +01:00
2012-01-11 10:42:39 +01:00
return chars.join('');
2012-01-11 02:40:45 +01:00
},
2011-05-04 17:02:56 +01:00
2012-01-11 02:40:45 +01:00
/**
* Convert a base58-encoded string to a byte array.
*
* Written by Mike Hearn for BitcoinJ.
* Copyright (c) 2011 Google Inc.
*
* Ported to JavaScript by Stefan Thomas.
*/
decode: function (input) {
2012-01-11 10:42:39 +01:00
var bi = BigInteger.valueOf(0);
2012-01-11 02:40:45 +01:00
var leadingZerosNum = 0;
for (var i = input.length - 1; i >= 0; i--) {
var alphaIndex = B58.alphabet.indexOf(input[i]);
if (alphaIndex < 0) {
throw "Invalid character";
}
2012-01-11 02:40:45 +01:00
bi = bi.add(BigInteger.valueOf(alphaIndex)
.multiply(B58.base.pow(input.length - 1 -i)));
2011-05-04 17:02:56 +01:00
2012-01-11 02:40:45 +01:00
// This counts leading zero bytes
if (input[i] == "1") leadingZerosNum++;
else leadingZerosNum = 0;
}
var bytes = bi.toByteArrayUnsigned();
2011-05-04 17:02:56 +01:00
2012-01-11 02:40:45 +01:00
// Add leading zeros
while (leadingZerosNum-- > 0) bytes.unshift(0);
2011-05-04 17:02:56 +01:00
2012-01-11 02:40:45 +01:00
return bytes;
}
};
var B58 = Bitcoin.Base58;
})(
'undefined' != typeof Bitcoin ? Bitcoin : module.exports
);