1 const bip39 = require('bip39');
2 const utils = require('./utils');
5 en: require('bip39/src/wordlists/english.json'),
6 zh: require('bip39/src/wordlists/chinese_simplified.json')
9 const keystore = require('./keystore');
11 const EntropyLength = 128;
12 const LightScryptN = 1 << 12;
13 const LightScryptP = 6;
25 if (mnemonic && mnemonic.length > 0 ){
26 return importKeyFromMnemonic(alias,password, mnemonic, language);
29 let obj = createNewKey(alias, password, language);
30 return {alias: obj.alias, xpub: obj.xPub.toString('hex'), keystore: obj.keystore, mnemonic:obj.mnemonic};
33 function importKeyFromMnemonic(alias, password, mnemonic, language) {
34 // checksum length = entropy length /32
35 // mnemonic length = (entropy length + checksum length)/11
36 let mnemArray = mnemonic.trim().split(' ');
37 if (mnemArray.length != ((EntropyLength+EntropyLength/32)/11 )){
38 throw 'mnemonic length error';
41 // Pre validate that the mnemonic is well formed and only contains words that
42 // are present in the word list
43 if (!bip39.validateMnemonic(mnemonic, WORDLISTS[language])) {
44 throw 'mnemonic is invalid';
47 return createKeyFromMnemonic(alias, password, mnemonic);
50 function createKeyFromMnemonic(alias,password, mnemonic) {
51 // Generate a Bip32 HD wallet for the mnemonic and a user supplied password
52 let seed = bip39.mnemonicToSeedSync(mnemonic, '');
53 let {xprv, xpub} = utils.newXKeys(seed);
60 let _keystore = keystore.encryptKey( key, password, LightScryptN, LightScryptP);
62 return {xPub: xpub.toString('hex'), alias, keystore: _keystore};
65 function createNewKey(alias, password, language) {
66 let normalizedAlias = alias.trim().toLowerCase();
67 return createChainKDKey(normalizedAlias, password, language);
70 function createChainKDKey(alias,password, language){
71 // Generate a mnemonic for memorization or user-friendly seeds
72 let mnemonic = bip39.generateMnemonic(EntropyLength,undefined, WORDLISTS[language]);
74 let object = createKeyFromMnemonic(alias, password, mnemonic);
75 object.mnemonic = mnemonic
82 importKeyFromMnemonic,