2023-05-17 11:59:30 +00:00
|
|
|
import * as utils from "@noble/curves/abstract/utils";
|
2023-03-25 22:55:34 +00:00
|
|
|
import * as bip39 from "@scure/bip39";
|
|
|
|
import { wordlist } from "@scure/bip39/wordlists/english";
|
|
|
|
import { HDKey } from "@scure/bip32";
|
|
|
|
|
2023-11-17 11:52:10 +00:00
|
|
|
import { DerivationPath } from "@/Const";
|
2023-03-25 22:55:34 +00:00
|
|
|
|
|
|
|
export function generateBip39Entropy(mnemonic?: string): Uint8Array {
|
|
|
|
try {
|
|
|
|
const mn = mnemonic ?? bip39.generateMnemonic(wordlist, 256);
|
|
|
|
return bip39.mnemonicToEntropy(mn, wordlist);
|
|
|
|
} catch (e) {
|
|
|
|
throw new Error("INVALID MNEMONIC PHRASE");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Convert hex-encoded entropy into mnemonic phrase
|
|
|
|
*/
|
|
|
|
export function hexToMnemonic(hex: string): string {
|
2023-05-17 11:59:30 +00:00
|
|
|
const bytes = utils.hexToBytes(hex);
|
2023-03-25 22:55:34 +00:00
|
|
|
return bip39.entropyToMnemonic(bytes, wordlist);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2023-04-14 15:02:15 +00:00
|
|
|
* Derrive NIP-06 private key from master key
|
2023-03-25 22:55:34 +00:00
|
|
|
*/
|
2023-04-14 15:02:15 +00:00
|
|
|
export function entropyToPrivateKey(entropy: Uint8Array): string {
|
2023-03-25 22:55:34 +00:00
|
|
|
const masterKey = HDKey.fromMasterSeed(entropy);
|
|
|
|
const newKey = masterKey.derive(DerivationPath);
|
|
|
|
|
|
|
|
if (!newKey.privateKey) {
|
|
|
|
throw new Error("INVALID KEY DERIVATION");
|
|
|
|
}
|
|
|
|
|
2023-05-17 11:59:30 +00:00
|
|
|
return utils.bytesToHex(newKey.privateKey);
|
2023-03-25 22:55:34 +00:00
|
|
|
}
|