diff --git a/packages/primitives/src/mnemonic.ts b/packages/primitives/src/mnemonic.ts index 5ac13cc..de746e9 100644 --- a/packages/primitives/src/mnemonic.ts +++ b/packages/primitives/src/mnemonic.ts @@ -1,8 +1,11 @@ import { bip39WordListEnglish, + decodeBip39MnemonicNonStandard, deriveSeedFromBip39Mnemonic, + encodeBip39MnemonicNonStandard, generateBip39MnemonicNonStandard, } from '@bitauth/libauth'; +import { Bytes } from './bytes.js'; export type MnemonicRaw = { words: string[]; @@ -61,6 +64,26 @@ export class Mnemonic { : 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 = 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 * @@ -270,6 +293,25 @@ export class Mnemonic { 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 = 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 *