-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
38 lines (32 loc) · 1.33 KB
/
index.js
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
const bip39 = require('bip39-light');
const { derivePath } = require('near-hd-key');
const bs58 = require('bs58');
const nacl = require('tweetnacl');
const KEY_DERIVATION_PATH = "m/44'/397'/0'"
const generateSeedPhrase = (entropy) => {
return parseSeedPhrase(entropy !== undefined ? bip39.entropyToMnemonic(entropy) : bip39.generateMnemonic())
}
const normalizeSeedPhrase = (seedPhrase) => seedPhrase.trim().split(/\s+/).map(part => part.toLowerCase()).join(' ')
const parseSeedPhrase = (seedPhrase, derivationPath) => {
const seed = bip39.mnemonicToSeed(normalizeSeedPhrase(seedPhrase))
const { key } = derivePath(derivationPath || KEY_DERIVATION_PATH, seed.toString('hex'))
const keyPair = nacl.sign.keyPair.fromSeed(key)
const publicKey = 'ed25519:' + bs58.encode(Buffer.from(keyPair.publicKey))
const secretKey = 'ed25519:' + bs58.encode(Buffer.from(keyPair.secretKey))
return { seedPhrase, secretKey, publicKey }
}
const findSeedPhraseKey = (seedPhrase, publicKeys) => {
// TODO: Need to iterate through multiple possible derivation paths?
const keyInfo = parseSeedPhrase(seedPhrase)
if (publicKeys.indexOf(keyInfo.publicKey) < 0) {
return {}
}
return keyInfo
}
module.exports = {
KEY_DERIVATION_PATH,
generateSeedPhrase,
normalizeSeedPhrase,
parseSeedPhrase,
findSeedPhraseKey
}