]> git.codecow.com Git - libnemo.git/commitdiff
Simplify mnemonic construction by offloading to Entropy class.
authorChris Duncan <chris@zoso.dev>
Mon, 4 Aug 2025 18:04:19 +0000 (11:04 -0700)
committerChris Duncan <chris@zoso.dev>
Mon, 4 Aug 2025 18:04:19 +0000 (11:04 -0700)
src/lib/bip39-mnemonic.ts

index d3fc40904d29d4e4f58e4f16842b6217c25ced53..f75a5687572fc4ff227d514eb2f4753772427fc6 100644 (file)
@@ -4,6 +4,7 @@
 import { Bip39Words } from './bip39-wordlist'\r
 import { BIP39_ITERATIONS } from './constants'\r
 import { bytes, hex, utf8 } from './convert'\r
+import { Entropy } from './entropy'\r
 \r
 /**\r
 * Represents a mnemonic phrase that identifies a wallet as defined by BIP-39.\r
@@ -32,23 +33,16 @@ export class Bip39Mnemonic {
        * the limit of 128-256 bits defined in BIP-39. Typically, wallets use the\r
        * maximum entropy allowed.\r
        *\r
-       * @param {(string|Uint8Array<ArrayBuffer>)} entropy - Cryptographically secure random value\r
+       * @param {(string|ArrayBuffer|Uint8Array<ArrayBuffer>)} entropy - Cryptographically secure random value\r
        * @returns {string} Mnemonic phrase created using the BIP-39 wordlist\r
        */\r
-       static async fromEntropy (entropy: string | Uint8Array<ArrayBuffer>): Promise<Bip39Mnemonic> {\r
-               if (typeof entropy === 'string') entropy = hex.toBytes(entropy)\r
-               if (![16, 20, 24, 28, 32].includes(entropy.byteLength)) {\r
-                       throw new RangeError('Invalid entropy byte length for BIP-39')\r
-               }\r
-               const phraseLength = 0.75 * entropy.byteLength\r
-               const checksum = await this.#checksum(entropy)\r
-\r
-               let e = 0n\r
-               for (let i = 0; i < entropy.byteLength; i++) {\r
-                       e = e << 8n | BigInt(entropy[i])\r
-               }\r
+       static async fromEntropy (entropy: string | ArrayBuffer | Uint8Array<ArrayBuffer>): Promise<Bip39Mnemonic> {\r
+               const e = new Entropy(entropy)\r
+               const phraseLength = 0.75 * e.byteLength\r
+               const checksum = await this.#checksum(e.bytes)\r
 \r
-               let concatenation: bigint = (e << BigInt(entropy.byteLength) / 4n) | checksum\r
+               let concatenation: bigint = (e.bigint << BigInt(e.byteLength) / 4n) | checksum\r
+               e.destroy()\r
                const words: string[] = []\r
                for (let i = 0; i < phraseLength; i++) {\r
                        const wordBits = concatenation & 2047n\r