You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. 'use strict'
  2. var base58 = require('bs58')
  3. var Buffer = require('safe-buffer').Buffer
  4. module.exports = function (checksumFn) {
  5. // Encode a buffer as a base58-check encoded string
  6. function encode (payload) {
  7. var checksum = checksumFn(payload)
  8. return base58.encode(Buffer.concat([
  9. payload,
  10. checksum
  11. ], payload.length + 4))
  12. }
  13. function decodeRaw (buffer) {
  14. var payload = buffer.slice(0, -4)
  15. var checksum = buffer.slice(-4)
  16. var newChecksum = checksumFn(payload)
  17. if (checksum[0] ^ newChecksum[0] |
  18. checksum[1] ^ newChecksum[1] |
  19. checksum[2] ^ newChecksum[2] |
  20. checksum[3] ^ newChecksum[3]) return
  21. return payload
  22. }
  23. // Decode a base58-check encoded string to a buffer, no result if checksum is wrong
  24. function decodeUnsafe (string) {
  25. var buffer = base58.decodeUnsafe(string)
  26. if (!buffer) return
  27. return decodeRaw(buffer)
  28. }
  29. function decode (string) {
  30. var buffer = base58.decode(string)
  31. var payload = decodeRaw(buffer, checksumFn)
  32. if (!payload) throw new Error('Invalid checksum')
  33. return payload
  34. }
  35. return {
  36. encode: encode,
  37. decode: decode,
  38. decodeUnsafe: decodeUnsafe
  39. }
  40. }