From e7d08a80c29723b3a361fe12c79c9e4ede1f7ff4 Mon Sep 17 00:00:00 2001 From: Chris Duncan Date: Mon, 4 Aug 2025 11:04:19 -0700 Subject: [PATCH] Simplify mnemonic construction by offloading to Entropy class. --- src/lib/bip39-mnemonic.ts | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/src/lib/bip39-mnemonic.ts b/src/lib/bip39-mnemonic.ts index d3fc409..f75a568 100644 --- a/src/lib/bip39-mnemonic.ts +++ b/src/lib/bip39-mnemonic.ts @@ -4,6 +4,7 @@ import { Bip39Words } from './bip39-wordlist' import { BIP39_ITERATIONS } from './constants' import { bytes, hex, utf8 } from './convert' +import { Entropy } from './entropy' /** * Represents a mnemonic phrase that identifies a wallet as defined by BIP-39. @@ -32,23 +33,16 @@ export class Bip39Mnemonic { * the limit of 128-256 bits defined in BIP-39. Typically, wallets use the * maximum entropy allowed. * - * @param {(string|Uint8Array)} entropy - Cryptographically secure random value + * @param {(string|ArrayBuffer|Uint8Array)} entropy - Cryptographically secure random value * @returns {string} Mnemonic phrase created using the BIP-39 wordlist */ - static async fromEntropy (entropy: string | Uint8Array): Promise { - if (typeof entropy === 'string') entropy = hex.toBytes(entropy) - if (![16, 20, 24, 28, 32].includes(entropy.byteLength)) { - throw new RangeError('Invalid entropy byte length for BIP-39') - } - const phraseLength = 0.75 * entropy.byteLength - const checksum = await this.#checksum(entropy) - - let e = 0n - for (let i = 0; i < entropy.byteLength; i++) { - e = e << 8n | BigInt(entropy[i]) - } + static async fromEntropy (entropy: string | ArrayBuffer | Uint8Array): Promise { + const e = new Entropy(entropy) + const phraseLength = 0.75 * e.byteLength + const checksum = await this.#checksum(e.bytes) - let concatenation: bigint = (e << BigInt(entropy.byteLength) / 4n) | checksum + let concatenation: bigint = (e.bigint << BigInt(e.byteLength) / 4n) | checksum + e.destroy() const words: string[] = [] for (let i = 0; i < phraseLength; i++) { const wordBits = concatenation & 2047n -- 2.47.3