Validate mnemonic checksum
This commit is contained in:
@@ -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();
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user