forked from nbd-wtf/nostr-tools
-
Notifications
You must be signed in to change notification settings - Fork 1
/
nip06.ts
75 lines (68 loc) · 2.48 KB
/
nip06.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { bytesToHex } from '@noble/hashes/utils'
import { wordlist } from '@scure/bip39/wordlists/english'
import { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from '@scure/bip39'
import { HDKey } from '@scure/bip32'
const DERIVATION_PATH = `m/44'/1237'`
export function privateKeyFromSeedWords(mnemonic: string, passphrase?: string, accountIndex = 0): Uint8Array {
let root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase))
let privateKey = root.derive(`${DERIVATION_PATH}/${accountIndex}'/0/0`).privateKey
if (!privateKey) throw new Error('could not derive private key')
return privateKey
}
export function accountFromSeedWords(
mnemonic: string,
passphrase?: string,
accountIndex = 0,
): {
privateKey: Uint8Array
publicKey: string
} {
const root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase))
const seed = root.derive(`${DERIVATION_PATH}/${accountIndex}'/0/0`)
const publicKey = bytesToHex(seed.publicKey!.slice(1))
const privateKey = seed.privateKey
if (!privateKey || !publicKey) {
throw new Error('could not derive key pair')
}
return { privateKey, publicKey }
}
export function extendedKeysFromSeedWords(
mnemonic: string,
passphrase?: string,
extendedAccountIndex = 0,
): {
privateExtendedKey: string
publicExtendedKey: string
} {
let root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase))
let seed = root.derive(`${DERIVATION_PATH}/${extendedAccountIndex}'`)
let privateExtendedKey = seed.privateExtendedKey
let publicExtendedKey = seed.publicExtendedKey
if (!privateExtendedKey && !publicExtendedKey) throw new Error('could not derive extended key pair')
return { privateExtendedKey, publicExtendedKey }
}
export function accountFromExtendedKey(
base58key: string,
accountIndex = 0,
): {
privateKey?: Uint8Array
publicKey: string
} {
let extendedKey = HDKey.fromExtendedKey(base58key)
let version = base58key.slice(0, 4)
let child = extendedKey.deriveChild(0).deriveChild(accountIndex)
let publicKey = bytesToHex(child.publicKey!.slice(1))
if (!publicKey) throw new Error('could not derive public key')
if (version === 'xprv') {
let privateKey = child.privateKey!
if (!privateKey) throw new Error('could not derive private key')
return { privateKey, publicKey }
}
return { publicKey }
}
export function generateSeedWords(): string {
return generateMnemonic(wordlist)
}
export function validateWords(words: string): boolean {
return validateMnemonic(words, wordlist)
}