base58check.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { toBase58, fromBase58 } from '@exodus/bytes/base58.js'
  2. import { assertU8, fromUint8 } from './_utils.js'
  3. const E_CHECKSUM = 'Invalid checksum'
  4. // checksum length is 4, i.e. only the first 4 bytes of the hash are used
  5. function encodeWithChecksum(arr, checksum) {
  6. // arr type in already validated in input
  7. const res = new Uint8Array(arr.length + 4)
  8. res.set(arr, 0)
  9. res.set(checksum.slice(0, 4), arr.length)
  10. return toBase58(res)
  11. }
  12. function decodeWithChecksum(str) {
  13. const arr = fromBase58(str) // checks input
  14. const payloadSize = arr.length - 4
  15. if (payloadSize < 0) throw new Error(E_CHECKSUM)
  16. return [arr.slice(0, payloadSize), arr.slice(payloadSize)]
  17. }
  18. function assertChecksum(c, r) {
  19. if ((c[0] ^ r[0]) | (c[1] ^ r[1]) | (c[2] ^ r[2]) | (c[3] ^ r[3])) throw new Error(E_CHECKSUM)
  20. }
  21. export const makeBase58check = (hashAlgo, hashAlgoSync) => {
  22. const apis = {
  23. async encode(arr) {
  24. assertU8(arr)
  25. return encodeWithChecksum(arr, await hashAlgo(arr))
  26. },
  27. async decode(str, format = 'uint8') {
  28. const [payload, checksum] = decodeWithChecksum(str)
  29. assertChecksum(checksum, await hashAlgo(payload))
  30. return fromUint8(payload, format)
  31. },
  32. }
  33. if (!hashAlgoSync) return apis
  34. return {
  35. ...apis,
  36. encodeSync(arr) {
  37. assertU8(arr)
  38. return encodeWithChecksum(arr, hashAlgoSync(arr))
  39. },
  40. decodeSync(str, format = 'uint8') {
  41. const [payload, checksum] = decodeWithChecksum(str)
  42. assertChecksum(checksum, hashAlgoSync(payload))
  43. return fromUint8(payload, format)
  44. },
  45. }
  46. }