OSDN Git Service

update and test the key logic
[bytom/Bytom-JS-SDK.git] / src / utils / key / createKey.js
1 const bip39 = require('bip39');
2 const utils = require('./utils');
3
4 const WORDLISTS = {
5     en: require('bip39/src/wordlists/english.json'),
6     zh: require('bip39/src/wordlists/chinese_simplified.json')
7 };
8
9 const keystore  = require('./keystore');
10
11 const EntropyLength = 128;
12 const LightScryptN = 1 << 12;
13 const LightScryptP = 6;
14
15 function createkey({
16     alias,
17     password,
18     mnemonic,
19     language
20 })  {
21     if(!language){
22         language = 'en';
23     }
24
25     if (mnemonic && mnemonic.length > 0 ){
26         return importKeyFromMnemonic(alias,password, mnemonic, language);
27     }
28
29     let obj = createNewKey(alias, password, language);
30     return {alias: obj.alias, xpub: obj.xPub.toString('hex'), keystore: obj.keystore, mnemonic:obj.mnemonic};
31 }
32
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';
39     }
40
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';
45     }
46
47     return createKeyFromMnemonic(alias, password, mnemonic);
48 }
49
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);
54     let key = {
55         keyType: 'bytom_kd',
56         xPub:    xpub,
57         xPrv:    xprv.xprv,
58         alias
59     };
60     let _keystore = keystore.encryptKey( key, password, LightScryptN, LightScryptP);
61
62     return {xPub: xpub.toString('hex'), alias, keystore: _keystore};
63 }
64
65 function createNewKey(alias, password, language) {
66     let normalizedAlias = alias.trim().toLowerCase();
67     return createChainKDKey(normalizedAlias, password, language);
68 }
69
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]);
73
74     let object = createKeyFromMnemonic(alias, password, mnemonic);
75     object.mnemonic = mnemonic
76
77     return object;
78 }
79
80 export {
81     createkey,
82     importKeyFromMnemonic,
83     createNewKey
84 };