base58.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
  2. const ALPHABET_MAP = {};
  3. for(let i = 0; i < ALPHABET.length; i++)
  4. ALPHABET_MAP[ALPHABET.charAt(i)] = i;
  5. const BASE = 58;
  6. module.exports.encode58 = function (buffer) {
  7. if(buffer.length === 0)
  8. return '';
  9. let i;
  10. let j;
  11. const digits = [0];
  12. for(i = 0; i < buffer.length; i++) {
  13. for(j = 0; j < digits.length; j++)
  14. digits[j] <<= 8;
  15. digits[0] += buffer[i];
  16. let carry = 0;
  17. for(j = 0; j < digits.length; ++j) {
  18. digits[j] += carry;
  19. carry = (digits[j] / BASE) | 0;
  20. digits[j] %= BASE
  21. }
  22. while (carry) {
  23. digits.push(carry % BASE);
  24. carry = (carry / BASE) | 0
  25. }
  26. }
  27. for(i = 0; buffer[i] === 0 && i < buffer.length - 1; i++)
  28. digits.push(0);
  29. return digits.reverse().map(digit => ALPHABET[digit]).join('');
  30. };
  31. module.exports.decode58 = function (string) {
  32. if(string.length === 0)
  33. return [];
  34. let i;
  35. let j;
  36. const bytes = [0];
  37. for(i = 0; i < string.length; i++) {
  38. const c = string[i];
  39. if(!(c in ALPHABET_MAP))
  40. throw new Error('Non-base58 character');
  41. for(j = 0; j < bytes.length; j++)
  42. bytes[j] *= BASE;
  43. bytes[0] += ALPHABET_MAP[c];
  44. let carry = 0;
  45. for(j = 0; j < bytes.length; ++j) {
  46. bytes[j] += carry;
  47. carry = bytes[j] >> 8;
  48. bytes[j] &= 0xff;
  49. }
  50. while (carry) {
  51. bytes.push(carry & 0xff);
  52. carry >>= 8;
  53. }
  54. }
  55. for(i = 0; string[i] === '1' && i < string.length - 1; i++)
  56. bytes.push(0);
  57. return bytes.reverse();
  58. };