bip39.hoon 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. :: bip39 implementation in hoon
  2. ::
  3. /= bip39-english /common/bip39-english
  4. /= * /common/zose
  5. ::
  6. |%
  7. ++ from-entropy
  8. |= byts
  9. ^- tape
  10. =. wid (mul wid 8)
  11. ~| [%unsupported-entropy-bit-length wid]
  12. ?> &((gte wid 128) (lte wid 256))
  13. ::
  14. =+ cs=(div wid 32)
  15. =/ check=@
  16. %+ rsh [0 (sub 256 cs)]
  17. (sha-256l:sha (div wid 8) dat)
  18. =/ bits=byts
  19. :- (add wid cs)
  20. %+ can 0
  21. :~ cs^check
  22. wid^dat
  23. ==
  24. ::
  25. =/ pieces
  26. |- ^- (list @)
  27. :- (end [0 11] dat.bits)
  28. ?: (lte wid.bits 11) ~
  29. $(bits [(sub wid.bits 11) (rsh [0 11] dat.bits)])
  30. ::
  31. =/ words=(list tape)
  32. %+ turn pieces
  33. |= ind=@ud
  34. (snag ind `(list tape)`bip39-english)
  35. ::
  36. %+ roll (flop words)
  37. |= [nex=tape all=tape]
  38. ?~ all nex
  39. :(weld all " " nex)
  40. ::
  41. ::NOTE always produces a 512-bit result
  42. ++ to-seed
  43. |= [mnem=tape pass=tape]
  44. ^- @
  45. %- hmac-sha512t:pbkdf:crypto
  46. [(crip mnem) (crip (weld "mnemonic" pass)) 2.048 64]
  47. ::
  48. ++ en-base58
  49. |= dat=@
  50. =/ cha
  51. '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
  52. %- flop
  53. |- ^- tape
  54. ?: =(0 dat) ~
  55. :- (cut 3 [(mod dat 58) 1] cha)
  56. $(dat (div dat 58))
  57. ::
  58. ++ de-base58
  59. |= t=tape
  60. =- (scan t (bass 58 (plus -)))
  61. ;~ pose
  62. (cook |=(a=@ (sub a 56)) (shim 'A' 'H'))
  63. (cook |=(a=@ (sub a 57)) (shim 'J' 'N'))
  64. (cook |=(a=@ (sub a 58)) (shim 'P' 'Z'))
  65. (cook |=(a=@ (sub a 64)) (shim 'a' 'k'))
  66. (cook |=(a=@ (sub a 65)) (shim 'm' 'z'))
  67. (cook |=(a=@ (sub a 49)) (shim '1' '9'))
  68. ==
  69. --