base58.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.encode58 = encode58;
  4. exports.decode58 = decode58;
  5. const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
  6. const ALPHABET_MAP = {};
  7. for (let i = 0; i < ALPHABET.length; i++)
  8. ALPHABET_MAP[ALPHABET.charAt(i)] = i;
  9. const BASE = 58;
  10. function encode58(buffer) {
  11. if (buffer.length === 0)
  12. return '';
  13. let i;
  14. let j;
  15. const digits = [0];
  16. for (i = 0; i < buffer.length; i++) {
  17. for (j = 0; j < digits.length; j++)
  18. digits[j] <<= 8;
  19. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  20. // @ts-ignore
  21. digits[0] += buffer[i];
  22. let carry = 0;
  23. for (j = 0; j < digits.length; ++j) {
  24. digits[j] += carry;
  25. carry = (digits[j] / BASE) | 0;
  26. digits[j] %= BASE;
  27. }
  28. while (carry) {
  29. digits.push(carry % BASE);
  30. carry = (carry / BASE) | 0;
  31. }
  32. }
  33. for (i = 0; buffer[i] === 0 && i < buffer.length - 1; i++)
  34. digits.push(0);
  35. return digits
  36. .reverse()
  37. .map((digit) => ALPHABET[digit])
  38. .join('');
  39. }
  40. function decode58(string) {
  41. if (string.length === 0)
  42. return [];
  43. let i;
  44. let j;
  45. const bytes = [0];
  46. for (i = 0; i < string.length; i++) {
  47. const c = string[i];
  48. if (!(c in ALPHABET_MAP))
  49. throw new Error('Non-base58 character');
  50. for (j = 0; j < bytes.length; j++)
  51. bytes[j] *= BASE;
  52. bytes[0] += ALPHABET_MAP[c];
  53. let carry = 0;
  54. for (j = 0; j < bytes.length; ++j) {
  55. bytes[j] += carry;
  56. carry = bytes[j] >> 8;
  57. bytes[j] &= 0xff;
  58. }
  59. while (carry) {
  60. bytes.push(carry & 0xff);
  61. carry >>= 8;
  62. }
  63. }
  64. for (i = 0; string[i] === '1' && i < string.length - 1; i++)
  65. bytes.push(0);
  66. return bytes.reverse();
  67. }
  68. //# sourceMappingURL=base58.js.map