Merge branch 'mnemonic_primitive_validate_checksum' into 'development'

Validate mnemonic checksum

See merge request GeneralProtocols/xo/stack!101
This commit is contained in:
Jim Hamill
2025-06-23 11:31:39 +00:00
2 changed files with 35 additions and 1 deletions
+16 -1
View File
@@ -74,7 +74,10 @@ export class Mnemonic {
*
* @returns Instance of Mnemonic.
*/
public static fromEntropy(entropy: Uint8Array, wordList: Array<string> = bip39WordListEnglish) {
public static fromEntropy(
entropy: Uint8Array,
wordList: Array<string> = bip39WordListEnglish,
) {
const mnemonic = encodeBip39MnemonicNonStandard(entropy, wordList);
if (typeof mnemonic === 'string') {
@@ -167,6 +170,18 @@ export class Mnemonic {
);
}
// Ensure the checksum is correct by attempting to decode the mnemonic.
// NOTE: LibAuth doesn't currently expose a convenient function to check this by itself.
const decodeResult = decodeBip39MnemonicNonStandard(
mnemonicRaw.words.join(' '),
wordList,
);
// NOTE: The above function will return a string if there is an error.
if (typeof decodeResult === 'string') {
throw new Error(decodeResult);
}
return new this(mnemonicRaw);
}
@@ -327,4 +327,23 @@ describe('Fail cases', () => {
]);
}).toThrow();
});
it('fromWord should fail if checksum is invalid', () => {
expect(() => {
// Invalid word "fnord".
Mnemonic.fromWords([
'abandon',
'abandon',
'abandon',
'abandon',
'abandon',
'abandon',
'abandon',
'abandon',
'abandon',
'abandon',
'banana',
]);
}).toThrow();
});
});