From: Chris Duncan Date: Mon, 4 Aug 2025 18:04:19 +0000 (-0700) Subject: Simplify mnemonic construction by offloading to Entropy class. X-Git-Tag: v0.10.5~46^2~11 X-Git-Url: https://git.codecow.com/?a=commitdiff_plain;h=e7d08a80c29723b3a361fe12c79c9e4ede1f7ff4;p=libnemo.git Simplify mnemonic construction by offloading to Entropy class. --- 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