-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaccounts-manager.js
103 lines (90 loc) · 2.45 KB
/
accounts-manager.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
"use strict";
const { utils } = require("spartan-gold");
const crypto = require("crypto");
const ecKeyUtils = require('eckey-utils');
let accounts = new Map();
let keyPair;
let counter = 1;
module.exports = class AccountsManager {
createNewAccount(path, masterNode, alias, balance) {
if (accounts.has(alias)) {
throw new Error(
`Account with alias "${alias}" already exists. Choose another name.`
);
}
if (path === "") {
while (accounts.has(`m/${counter}'`)) {
counter++;
}
keyPair = masterNode.derivePath(`m/${counter}'`);
counter++;
} else {
if (accounts.has(path)) {
throw new Error(
`Account at path "${path}" already exists. Choose another name.`
);
} else {
keyPair = masterNode.derivePath(path);
}
}
/*Change Private/Public Key to PEM format*/
const curveName = "secp256k1";
const pems = ecKeyUtils.generatePem({
curveName,
privateKey: keyPair.privateKey,
publicKey: keyPair.publicKey,
});
/*Private/Public in x509 andsec1 PEM formats*/
const x509Pem = pems.publicKey;
const sec1Pem = pems.privateKey;
/*Change Prv/Pub Keys to PCKS8/SPKI keys */
const spkix509Pem = crypto
.createPublicKey({ key: x509Pem, format: "pem" })
.export({ type: "spki", format: "pem" });
const pkcs8PemFromSec1 = crypto
.createPrivateKey({ key: sec1Pem, format: "pem", type: "sec1" })
.export({ type: "pkcs8", format: "pem" })
.toString();
keyPair = {publicKey: spkix509Pem, privateKey:pkcs8PemFromSec1};
accounts.set(path, {
path: path,
alias: alias,
keyPair: keyPair,
address: utils.calcAddress(keyPair.publicKey),
balance: balance | 0,
});
}
getAllBalances() {
const result = [];
accounts.forEach((v, k) =>
result.push({
path: k,
alias: v["alias"],
address: v["address"],
balance: v["balance"],
})
);
return result;
}
getAmount(path) {
return accounts.get(path)["balance"];
}
getAccountByAlias(alias) {
let entries = accounts.entries();
for (let entry of entries) {
const it = entry[1];
if (it.alias === alias) {
return it;
}
}
}
getAccountByAddress(address) {
let entries = accounts.entries();
for (let entry of entries) {
const it = entry[1];
if (it.address === address) {
return it;
}
}
}
};