index.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. var bs58check = require('bs58check')
  2. function decodeRaw (buffer, version) {
  3. // check version only if defined
  4. if (version !== undefined && buffer[0] !== version) throw new Error('Invalid network version')
  5. // uncompressed
  6. if (buffer.length === 33) {
  7. return {
  8. version: buffer[0],
  9. privateKey: buffer.slice(1, 33),
  10. compressed: false
  11. }
  12. }
  13. // invalid length
  14. if (buffer.length !== 34) throw new Error('Invalid WIF length')
  15. // invalid compression flag
  16. if (buffer[33] !== 0x01) throw new Error('Invalid compression flag')
  17. return {
  18. version: buffer[0],
  19. privateKey: buffer.slice(1, 33),
  20. compressed: true
  21. }
  22. }
  23. function encodeRaw (version, privateKey, compressed) {
  24. var result = new Buffer(compressed ? 34 : 33)
  25. result.writeUInt8(version, 0)
  26. privateKey.copy(result, 1)
  27. if (compressed) {
  28. result[33] = 0x01
  29. }
  30. return result
  31. }
  32. function decode (string, version) {
  33. return decodeRaw(bs58check.decode(string), version)
  34. }
  35. function encode (version, privateKey, compressed) {
  36. if (typeof version === 'number') return bs58check.encode(encodeRaw(version, privateKey, compressed))
  37. return bs58check.encode(
  38. encodeRaw(
  39. version.version,
  40. version.privateKey,
  41. version.compressed
  42. )
  43. )
  44. }
  45. module.exports = {
  46. decode: decode,
  47. decodeRaw: decodeRaw,
  48. encode: encode,
  49. encodeRaw: encodeRaw
  50. }