-
Notifications
You must be signed in to change notification settings - Fork 1
/
AccountHandler.js
103 lines (80 loc) · 2.85 KB
/
AccountHandler.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
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import TronWeb from 'tronweb';
import Logger from './logger';
import bip39 from 'bip39';
import bip32 from 'bip32';
import { Buffer } from 'buffer/';
import {
ACCOUNT_TYPE,
BIP44
} from './constants';
const logger = new Logger('AccountHandler');
export default class AccountHandler {
constructor(input, accountType = ACCOUNT_TYPE.MNEMONIC) {
switch(accountType) {
case ACCOUNT_TYPE.RAW:
this._importFromPrivateKey(input);
break;
case ACCOUNT_TYPE.MNEMONIC:
this._importFromWordList(input);
break;
default:
throw new Error(`ACCOUNT_TYPE ${accountType} invalid`);
}
}
_importFromPrivateKey(privateKey) {
logger.info('Importing account from private key');
this._type = ACCOUNT_TYPE.RAW;
this._privateKey = privateKey;
this._publicKey = TronWeb.address.fromPrivateKey(privateKey);
}
_importFromWordList(wordList) {
logger.info('Importing account from word list');
if(!bip39.validateMnemonic(wordList))
throw new Error(`Invalid wordList ${wordList} provided`);
logger.info('Word list was valid');
this._type = ACCOUNT_TYPE.MNEMONIC;
this._seed = bip39.mnemonicToSeedHex(wordList);
this._wordList = wordList;
}
getAccountAtIndex(index = 0) {
logger.info(`Getting account at index ${index}`);
if(this._type !== ACCOUNT_TYPE.MNEMONIC)
throw new Error('ACCOUNT_TYPE must be of type MNEMONIC to derive account keys');
logger.info('Valid account type, deriving key pair');
const node = bip32.fromSeed(new Buffer(this._seed, 'hex'));
const child = node.derivePath(`m/44'/${ BIP44.INDEX }'/${ index }'/0/0`, this._seed);
const privateKey = child.privateKey.toString('hex');
const publicKey = TronWeb.address.fromPrivateKey(privateKey);
logger.info(`Generated public key ${publicKey}`);
return {
wordList: this._wordList,
accountType: this._type,
accountIndex: index,
name: false,
internal: false,
privateKey,
publicKey
};
}
export() {
if(this._type === ACCOUNT_TYPE.MNEMONIC)
return this._wordList;
if(this._type === ACCOUNT_TYPE.RAW) {
return {
privateKey: this._privateKey,
publicKey: this._publicKey,
accountType: this._type,
name: false,
internal: false
};
}
return false;
}
static generateAccount(size = 256) {
logger.info(`Generating new account with size ${size}`);
const mnemonic = bip39.generateMnemonic(size);
return new AccountHandler(
mnemonic
);
}
}