forked from Wasakachain/Miner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerateAccount.js
60 lines (50 loc) · 1.87 KB
/
generateAccount.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
const ethers = require('ethers');
const bip39 = require('bip39');
const bip32 = require('bip32');
const elliptic = require('elliptic');
const secp256k1 = new elliptic.ec('secp256k1');
const ripemd160 = require('ripemd160');
const fs = require('fs');
const purpose = "m/44";
const coinType = "/696969'";
const account = "/0'"
const change = "/0"
const mainPath = purpose + coinType + account + change;
fs.writeFileSync('./account.json', JSON.stringify(loadAccount(generateMnemonic())), { encoding: 'UTF8' });
function loadAccount(mnemonic, count = 1) {
seed = bip39.mnemonicToSeedSync(mnemonic);
const rootKey = bip32.fromSeed(seed);
return createAccount(rootKey, count);
}
function createAccount(rootKey, index) {
let pathFromRootKey = rootKey.derivePath(mainPath + '/' + index);
let keyPair = secp256k1.keyFromPrivate(pathFromRootKey.privateKey);
let publicKey = getCompressedPublicKey(keyPair.getPublic());
let address = getAddress(publicKey);
publicKey = publicKey;
let privateKey = keyPair.getPrivate().toString('hex');
return {
publicKey, address, privateKey
}
};
function generateMnemonic() {
return ethers.utils.HDNode.entropyToMnemonic(generateEntropy(16)); // cryptographyc secure seed
}
function generateEntropy(length = 16) {
return ethers.utils.randomBytes(length); // cryptographyc secure seed
}
function getAddress(publicKeyCompressed) {
return new ripemd160().update(publicKeyCompressed).digest('hex');
}
function getCompressedPublicKey(publicPoints) {
return `${toHexString(publicPoints.x)}${publicPoints.encodeCompressed('hex').substring(0, 2) === '02' ? 0 : 1}`;
}
function toHexString(value) {
let hexString = value.toString(16);
let padding = 64 - hexString.length;
if (!padding) {
return hexString;
}
padding = new Array(padding).fill('0');
return `${padding.join('')}${hexString}`;
}