index.js 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. /*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */
  2. import { bytes as assertBytes, number as assertNumber } from '@noble/hashes/_assert';
  3. import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2';
  4. import { sha256 } from '@noble/hashes/sha256';
  5. import { sha512 } from '@noble/hashes/sha512';
  6. import { randomBytes } from '@noble/hashes/utils';
  7. import { utils as baseUtils } from '@scure/base';
  8. // Japanese wordlist
  9. const isJapanese = (wordlist) => wordlist[0] === '\u3042\u3044\u3053\u304f\u3057\u3093';
  10. // Normalization replaces equivalent sequences of characters
  11. // so that any two texts that are equivalent will be reduced
  12. // to the same sequence of code points, called the normal form of the original text.
  13. // https://tonsky.me/blog/unicode/#why-is-a----
  14. function nfkd(str) {
  15. if (typeof str !== 'string')
  16. throw new TypeError(`Invalid mnemonic type: ${typeof str}`);
  17. return str.normalize('NFKD');
  18. }
  19. function normalize(str) {
  20. const norm = nfkd(str);
  21. const words = norm.split(' ');
  22. if (![12, 15, 18, 21, 24].includes(words.length))
  23. throw new Error('Invalid mnemonic');
  24. return { nfkd: norm, words };
  25. }
  26. function assertEntropy(entropy) {
  27. assertBytes(entropy, 16, 20, 24, 28, 32);
  28. }
  29. /**
  30. * Generate x random words. Uses Cryptographically-Secure Random Number Generator.
  31. * @param wordlist imported wordlist for specific language
  32. * @param strength mnemonic strength 128-256 bits
  33. * @example
  34. * generateMnemonic(wordlist, 128)
  35. * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'
  36. */
  37. export function generateMnemonic(wordlist, strength = 128) {
  38. assertNumber(strength);
  39. if (strength % 32 !== 0 || strength > 256)
  40. throw new TypeError('Invalid entropy');
  41. return entropyToMnemonic(randomBytes(strength / 8), wordlist);
  42. }
  43. const calcChecksum = (entropy) => {
  44. // Checksum is ent.length/4 bits long
  45. const bitsLeft = 8 - entropy.length / 4;
  46. // Zero rightmost "bitsLeft" bits in byte
  47. // For example: bitsLeft=4 val=10111101 -> 10110000
  48. return new Uint8Array([(sha256(entropy)[0] >> bitsLeft) << bitsLeft]);
  49. };
  50. function getCoder(wordlist) {
  51. if (!Array.isArray(wordlist) || wordlist.length !== 2048 || typeof wordlist[0] !== 'string')
  52. throw new Error('Wordlist: expected array of 2048 strings');
  53. wordlist.forEach((i) => {
  54. if (typeof i !== 'string')
  55. throw new Error(`Wordlist: non-string element: ${i}`);
  56. });
  57. return baseUtils.chain(baseUtils.checksum(1, calcChecksum), baseUtils.radix2(11, true), baseUtils.alphabet(wordlist));
  58. }
  59. /**
  60. * Reversible: Converts mnemonic string to raw entropy in form of byte array.
  61. * @param mnemonic 12-24 words
  62. * @param wordlist imported wordlist for specific language
  63. * @example
  64. * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';
  65. * mnemonicToEntropy(mnem, wordlist)
  66. * // Produces
  67. * new Uint8Array([
  68. * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,
  69. * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f
  70. * ])
  71. */
  72. export function mnemonicToEntropy(mnemonic, wordlist) {
  73. const { words } = normalize(mnemonic);
  74. const entropy = getCoder(wordlist).decode(words);
  75. assertEntropy(entropy);
  76. return entropy;
  77. }
  78. /**
  79. * Reversible: Converts raw entropy in form of byte array to mnemonic string.
  80. * @param entropy byte array
  81. * @param wordlist imported wordlist for specific language
  82. * @returns 12-24 words
  83. * @example
  84. * const ent = new Uint8Array([
  85. * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,
  86. * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f
  87. * ]);
  88. * entropyToMnemonic(ent, wordlist);
  89. * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'
  90. */
  91. export function entropyToMnemonic(entropy, wordlist) {
  92. assertEntropy(entropy);
  93. const words = getCoder(wordlist).encode(entropy);
  94. return words.join(isJapanese(wordlist) ? '\u3000' : ' ');
  95. }
  96. /**
  97. * Validates mnemonic for being 12-24 words contained in `wordlist`.
  98. */
  99. export function validateMnemonic(mnemonic, wordlist) {
  100. try {
  101. mnemonicToEntropy(mnemonic, wordlist);
  102. }
  103. catch (e) {
  104. return false;
  105. }
  106. return true;
  107. }
  108. const salt = (passphrase) => nfkd(`mnemonic${passphrase}`);
  109. /**
  110. * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.
  111. * @param mnemonic 12-24 words
  112. * @param passphrase string that will additionally protect the key
  113. * @returns 64 bytes of key data
  114. * @example
  115. * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';
  116. * await mnemonicToSeed(mnem, 'password');
  117. * // new Uint8Array([...64 bytes])
  118. */
  119. export function mnemonicToSeed(mnemonic, passphrase = '') {
  120. return pbkdf2Async(sha512, normalize(mnemonic).nfkd, salt(passphrase), { c: 2048, dkLen: 64 });
  121. }
  122. /**
  123. * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.
  124. * @param mnemonic 12-24 words
  125. * @param passphrase string that will additionally protect the key
  126. * @returns 64 bytes of key data
  127. * @example
  128. * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';
  129. * mnemonicToSeedSync(mnem, 'password');
  130. * // new Uint8Array([...64 bytes])
  131. */
  132. export function mnemonicToSeedSync(mnemonic, passphrase = '') {
  133. return pbkdf2(sha512, normalize(mnemonic).nfkd, salt(passphrase), { c: 2048, dkLen: 64 });
  134. }