1
0

setEntropy.ts 987 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /* Import modules. */
  2. import {
  3. randomBytes,
  4. sha256,
  5. } from '@nexajs/crypto'
  6. import {
  7. binToHex,
  8. hexToBin,
  9. } from '@nexajs/utils'
  10. /* Set constants. */
  11. const ENTROPY_BYTES_LENGTH = 32
  12. /**
  13. * Create Wallet
  14. *
  15. * Generates 128-bits of random entropy and saves it to the
  16. * local browser.
  17. */
  18. export default function (_entropy) {
  19. let entropy
  20. if (_entropy) {
  21. this.setEntropy(_entropy)
  22. return _entropy
  23. }
  24. /* Return random bytes (as hex string). */
  25. const localBytes = binToHex(randomBytes(ENTROPY_BYTES_LENGTH))
  26. /* Hash the entropy. */
  27. const hashed = sha256(hexToBin(localBytes))
  28. /* Set (final 128-bit) entropy. */
  29. // NOTE: Serialize to a 16-byte (128-bit) Hex String.
  30. // NOTE: We use 16-bytes to remain compatible with popular HD wallets.
  31. entropy = binToHex(hashed).slice(0, 16) + binToHex(hashed).slice(-16)
  32. this.setEntropy(entropy)
  33. console.info('New (128-bit) wallet created!')
  34. return entropy
  35. }