Merge branch 'mnemonic-entropy' into 'development'

Add to and from entropy methods to mnemonic primitive

See merge request GeneralProtocols/xo/stack!98
This commit is contained in:
Jim Hamill
2025-06-15 23:51:23 +00:00
+42
View File
@@ -1,8 +1,11 @@
import { import {
bip39WordListEnglish, bip39WordListEnglish,
decodeBip39MnemonicNonStandard,
deriveSeedFromBip39Mnemonic, deriveSeedFromBip39Mnemonic,
encodeBip39MnemonicNonStandard,
generateBip39MnemonicNonStandard, generateBip39MnemonicNonStandard,
} from '@bitauth/libauth'; } from '@bitauth/libauth';
import { Bytes } from './bytes.js';
export type MnemonicRaw = { export type MnemonicRaw = {
words: string[]; words: string[];
@@ -61,6 +64,26 @@ export class Mnemonic {
: this.fromPhrase(phraseOrWords, wordList); : this.fromPhrase(phraseOrWords, wordList);
} }
/**
* Instantiates a mnemonic from entropy.
*
* @param entropy The entropy to use to derive the mnemonic words.
* @param wordList Optional wordlist (defaults to English BIP-39 wordlist).
*
* @throws {Error} If mnemonic could not be generated.
*
* @returns Instance of Mnemonic.
*/
public static fromEntropy(entropy: Uint8Array, wordList: Array<string> = bip39WordListEnglish) {
const mnemonic = encodeBip39MnemonicNonStandard(entropy, wordList);
if (typeof mnemonic === 'string') {
throw new Error(mnemonic);
}
return this.fromPhrase(mnemonic.phrase, wordList);
}
/** /**
* Instantiates a mnemonic from a string * Instantiates a mnemonic from a string
* *
@@ -270,6 +293,25 @@ export class Mnemonic {
return words; return words;
} }
/**
* Returns the entropy for this mnemonic.
*
* @param wordList Optional wordlist (defaults to English BIP-39 wordlist).
*
* @throws {Error} If entropy could not be decoded from the mnemonic using the provided wordlist.
*
* @returns The entropy used to derive the mnemonic words.
*/
public toEntropy(wordList: Array<string> = bip39WordListEnglish): Bytes {
const entropy = decodeBip39MnemonicNonStandard(this.toPhrase(), wordList);
if (typeof entropy === 'string') {
throw new Error(entropy);
}
return Bytes.fromBytes(entropy);
}
/** /**
* Returns a serializable represntation of the class * Returns a serializable represntation of the class
* *