Enable recovery with a mnemonic seed per nip06
This commit is contained in:
@ -7,7 +7,9 @@ import base32Decode from "base32-decode";
|
||||
import { HexKey, TaggedRawEvent, u256, EventKind, encodeTLV, NostrPrefix } from "@snort/nostr";
|
||||
import * as bip39 from "@scure/bip39";
|
||||
import { wordlist } from "@scure/bip39/wordlists/english";
|
||||
import { HDKey } from "@scure/bip32";
|
||||
|
||||
import { DerivationPath } from "Const";
|
||||
import { MetadataCache } from "State/Users";
|
||||
|
||||
export const sha256 = (str: string) => {
|
||||
@ -102,6 +104,15 @@ export function hexToBech32(hrp: string, hex?: string) {
|
||||
}
|
||||
}
|
||||
|
||||
export function generateBip39Entropy(mnemonic?: string): Uint8Array {
|
||||
try {
|
||||
const mn = mnemonic ?? bip39.generateMnemonic(wordlist);
|
||||
return bip39.mnemonicToEntropy(mn, wordlist);
|
||||
} catch (e) {
|
||||
throw new Error("INVALID MNEMONIC PHRASE");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert hex-encoded entropy into mnemonic phrase
|
||||
*/
|
||||
@ -110,6 +121,22 @@ export function hexToMnemonic(hex: string): string {
|
||||
return bip39.entropyToMnemonic(bytes, wordlist);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert mnemonic phrase into hex-encoded private key
|
||||
* using the derivation path specified in NIP06
|
||||
* @param mnemonic the mnemonic-encoded entropy
|
||||
*/
|
||||
export function entropyToDerivedKey(entropy: Uint8Array): string {
|
||||
const masterKey = HDKey.fromMasterSeed(entropy);
|
||||
const newKey = masterKey.derive(DerivationPath);
|
||||
|
||||
if (!newKey.privateKey) {
|
||||
throw new Error("INVALID KEY DERIVATION");
|
||||
}
|
||||
|
||||
return secp.utils.bytesToHex(newKey.privateKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert hex pubkey to bech32 link url
|
||||
*/
|
||||
|
Reference in New Issue
Block a user