/
mnemonic.js
35 lines (30 loc) · 1018 Bytes
/
mnemonic.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
import {entropyToMnemonic, mnemonicToEntropy, validateMnemonic as validate, wordlists} from 'bip39'
import {Keypair} from '@stellar/stellar-base'
const mnemonicWordsList = wordlists.english
/**
* Converts a secret key to 24-word BIP-39 mnemonic code.
* @param {String} secret
* @returns {String}
*/
function secretToMnemonic(secret) {
const kp = Keypair.fromSecret(secret)
return entropyToMnemonic(kp.rawSecretKey(), mnemonicWordsList)
}
/**
* Converts 24-word BIP-39 mnemonic code to a secret key.
* @param {String} mnemonic
* @returns {String|null}
*/
function mnemonicToSecret(mnemonic) {
try {
const rawSecret = mnemonicToEntropy(mnemonic, mnemonicWordsList)
return Keypair.fromRawEd25519Seed(Buffer.from(rawSecret, 'hex')).secret()
} catch (e) {
console.error(e)
return null
}
}
function validateMnemonic(mnemonic) {
return validate(mnemonic, mnemonicWordsList)
}
export {secretToMnemonic, mnemonicToSecret, validateMnemonic, mnemonicWordsList}