Advertisement
Guest User

Untitled

a guest
Oct 20th, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. // Bitcoin Base58 encoder/decoder algorithm
  2. const btcTable = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
  3. console.assert(btcTable.length === 58);
  4.  
  5. // Base58 decoder/encoder for BigInt
  6. function b58ToBi(chars, table = btcTable) {
  7. const carry = BigInt(table.length);
  8. let total = 0n, base = 1n;
  9. for (let i = chars.length - 1; i >= 0; i--) {
  10. const n = table.indexOf(chars[i]);
  11. if (n < 0) throw TypeError(`invalid letter contained: '${chars[i]}'`);
  12. total += base * BigInt(n);
  13. base *= carry;
  14. }
  15. return total;
  16. }
  17. function biToB58(num, table = btcTable) {
  18. const carry = BigInt(table.length);
  19. let r = [];
  20. while (num > 0n) {
  21. r.unshift(table[num % carry]);
  22. num /= carry;
  23. }
  24. return r;
  25. }
  26.  
  27. // Base58 decoder/encoder for bytes
  28. function b58decode(str, table = btcTable) {
  29. const chars = [...str];
  30. const trails = chars.findIndex(c => c !== table[0]);
  31. const head0s = Array(trails).fill(0);
  32. if (trails === chars.length) return Uint8Array.from(head0s);
  33. const beBytes = [];
  34. let num = b58ToBi(chars.slice(trails), table);
  35. while (num > 0n) {
  36. beBytes.unshift(Number(num % 256n));
  37. num /= 256n;
  38. }
  39. return Uint8Array.from(head0s.concat(beBytes));
  40. }
  41.  
  42. function b58encode(beBytes, table = btcTable) {
  43. if (!(beBytes instanceof Uint8Array)) throw TypeError(`must be Uint8Array`);
  44. const trails = beBytes.findIndex(n => n !== 0);
  45. const head0s = table[0].repeat(trails);
  46. if (trails === beBytes.length) return head0s;
  47. const num = beBytes.slice(trails).reduce((r, n) => r * 256n + BigInt(n), 0n);
  48. return head0s + biToB58(num, table).join("");
  49. }
  50.  
  51. // example
  52. {
  53. //BASE58: heading byte value 0s are converted to "1"s (letter of table[0])
  54. console.log(b58encode(new Uint8Array([0, 1, 2]))); // => "15T"
  55. console.log(b58decode("15T")); // => Uint8Array([0, 1, 2])
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement