From: Chris Duncan Date: Wed, 30 Jul 2025 14:29:37 +0000 (-0700) Subject: Refactor mnemonic validation to compare bitwise using bigints. X-Git-Tag: v0.10.5~48^2~5 X-Git-Url: https://git.codecow.com/?a=commitdiff_plain;h=aa86d8dd095d890f2fd7e4612d32b85da6503bb9;p=libnemo.git Refactor mnemonic validation to compare bitwise using bigints. --- diff --git a/src/lib/bip39-mnemonic.ts b/src/lib/bip39-mnemonic.ts index 47fe7cc..3d05afd 100644 --- a/src/lib/bip39-mnemonic.ts +++ b/src/lib/bip39-mnemonic.ts @@ -117,31 +117,38 @@ export class Bip39Mnemonic { return false } - const wordBits = words.map(word => { + let bits = 0n, bitLength = 0n + for (const word of words) { const wordIndex = Bip39Words.indexOf(word) if (wordIndex === -1) { return false } - return dec.toBin(wordIndex, 11) - }).join('') - const checksumLength = wordBits.length / 33 - const entropyLength = wordBits.length - checksumLength - const entropyBits = wordBits.substring(0, entropyLength) - const checksumBits = wordBits.substring(entropyLength) - - if ( - entropyBits == null - || entropyBits.length < 128 - || entropyBits.length > 256 - || entropyBits.length % 32 !== 0 + bits = (bits << 11n) | BigInt(Bip39Words.indexOf(word)) + bitLength += 11n + } + if (Number(bitLength) % 33 !== 0) { + return false + } + + const checksumLength = bitLength / 33n + const entropyLength = Number(bitLength - checksumLength) + const entropyBits = bits >> checksumLength + const checksumBits = bits & ((1n << checksumLength) - 1n) + + if (entropyBits == null + || entropyBits < 0n + || entropyBits > (1n << 256n) - 1n + || entropyLength < 128 + || entropyLength > 256 + || entropyLength % 32 !== 0 ) { return false } - const entropy = await Entropy.import(bin.toBytes(entropyBits)) + const entropyHex = entropyBits.toString(16).padStart(entropyLength / 4, '0') + const entropy = await Entropy.import(entropyHex) const expectedChecksum = await this.checksum(entropy.bytes) - - if (Number(expectedChecksum) !== parseInt(checksumBits, 2)) { + if (expectedChecksum !== checksumBits) { return false }