Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Bitcoin Base58 encoder/decoder algorithm
- const btcTable = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
- console.assert(btcTable.length === 58);
- // Base58 decoder/encoder for BigInt
- function b58ToBi(chars, table = btcTable) {
- const carry = BigInt(table.length);
- let total = 0n, base = 1n;
- for (let i = chars.length - 1; i >= 0; i--) {
- const n = table.indexOf(chars[i]);
- if (n < 0) throw TypeError(`invalid letter contained: '${chars[i]}'`);
- total += base * BigInt(n);
- base *= carry;
- }
- return total;
- }
- function biToB58(num, table = btcTable) {
- const carry = BigInt(table.length);
- let r = [];
- while (num > 0n) {
- r.unshift(table[num % carry]);
- num /= carry;
- }
- return r;
- }
- // Base58 decoder/encoder for bytes
- function b58decode(str, table = btcTable) {
- const chars = [...str];
- const trails = chars.findIndex(c => c !== table[0]);
- const head0s = Array(trails).fill(0);
- if (trails === chars.length) return Uint8Array.from(head0s);
- const beBytes = [];
- let num = b58ToBi(chars.slice(trails), table);
- while (num > 0n) {
- beBytes.unshift(Number(num % 256n));
- num /= 256n;
- }
- return Uint8Array.from(head0s.concat(beBytes));
- }
- function b58encode(beBytes, table = btcTable) {
- if (!(beBytes instanceof Uint8Array)) throw TypeError(`must be Uint8Array`);
- const trails = beBytes.findIndex(n => n !== 0);
- const head0s = table[0].repeat(trails);
- if (trails === beBytes.length) return head0s;
- const num = beBytes.slice(trails).reduce((r, n) => r * 256n + BigInt(n), 0n);
- return head0s + biToB58(num, table).join("");
- }
- // example
- {
- //BASE58: heading byte value 0s are converted to "1"s (letter of table[0])
- console.log(b58encode(new Uint8Array([0, 1, 2]))); // => "15T"
- console.log(b58decode("15T")); // => Uint8Array([0, 1, 2])
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement