-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathmain.js
328 lines (304 loc) · 7.94 KB
/
main.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
const fs = require("fs");
const path = require("path");
const { spawn, spawnSync } = require("child_process");
const findCacheDir = require("find-cache-dir");
const { getKeypairs } = require("./crypto");
const KEYS_SOURCE = path.join(__dirname, "keys");
const HOMEDIR = findCacheDir({
name: "ethnode",
cwd: __dirname,
create: true,
});
const LOGLEVELS = [, "warn", "info", "debug"];
function canWrite(path) {
let fd;
try {
fd = fs.openSync(path, "wx");
} catch (e) {
if (e.code === "EACCES") {
return false;
} else {
throw e;
}
}
fs.closeSync(fd);
fs.unlinkSync(path);
return true;
}
function getPaths(client, workdir) {
const base = path.join(workdir, client);
return {
binary: path.join(HOMEDIR, client),
base: base,
genesis: path.join(base, "genesis.json"),
data: path.join(base, "data"),
keys: path.join(base, "keys"),
password: path.join(__dirname, "keys", "password.secret"),
};
}
function generateGenesis(client, chainId, balances, period) {
const genesis = JSON.parse(
JSON.stringify(require(`./genesis.${client}.json`))
);
if (client === "geth") {
genesis.config.chainId = chainId;
genesis.extraData =
"0x" +
"0".repeat(64) +
Object.keys(balances)[0].substr(2) +
"0".repeat(130);
genesis.alloc = { ...genesis.alloc, ...balances };
genesis.config.clique.period = period;
} else if (client === "openethereum") {
genesis.params.networkID = chainId;
genesis.accounts = { ...genesis.accounts, ...balances };
}
return genesis;
}
function generateBalances(addresses, balance) {
balance = balance || "100000000000000000000";
const balances = {};
for (var i = 0; i < addresses.length; i++) {
balances[addresses[i]] = {
balance: balance,
};
}
return balances;
}
function downloadClient(client, workdir, download) {
const paths = getPaths(client, workdir);
if (!canWrite(path.join(HOMEDIR, "__remove_me__"))) {
console.log(
`Cannot write in ${HOMEDIR}, try run "sudo ethnode -d" to ` +
`download ${client}. Remember you can run ethnode without "sudo" ` +
`after this operation.`
);
process.exit(1);
}
if (!fs.existsSync(paths.binary)) {
console.log(`Download latest ${client} version, please wait.`);
const childResult = spawnSync(path.join(__dirname, `get_${client}.sh`), {
env: { HOMEDIR },
stdio: "inherit",
});
if (childResult.status !== 0) {
console.log(
`Error downloading ${client}, this might be temporary, ` +
`try again later.`
);
process.exit(childResult.status);
}
} else if (download) {
console.error(
`You have downloaded ${client} already, if you want to force the download remove ${paths.binary}`
);
process.exit(1);
}
}
async function provide(
client,
workdir,
allocate,
chainId,
execute,
period,
loggingOptions
) {
const paths = getPaths(client, workdir);
const keypairs = await getKeypairs(KEYS_SOURCE, "password");
let balances = generateBalances(
keypairs.map((x) => x.address).concat(allocate)
);
const genesis = generateGenesis(client, chainId, balances, period);
let keysDest =
client === "geth" ? paths.keys : path.join(paths.keys, genesis.name);
try {
fs.mkdirSync(paths.base, { recursive: true });
fs.mkdirSync(keysDest, { recursive: true });
} catch (err) {
if (err.code !== "EEXIST") throw err;
}
fs.writeFileSync(paths.genesis, JSON.stringify(genesis, null, 2));
fs.readdirSync(KEYS_SOURCE)
.filter((filename) => filename.startsWith("UTC--"))
.map((filename) =>
fs.copyFileSync(
path.join(KEYS_SOURCE, filename),
path.join(keysDest, filename)
)
);
if (client === "geth") {
const childResult = spawnSync(
paths.binary,
[...loggingOptions, "--datadir", paths.data, "init", paths.genesis],
{
stdio: execute ? ["ignore", "ignore", "ignore"] : "inherit",
}
);
if (childResult.status !== 0) {
console.log(
`Error running ${paths.binary}, run it manually to check if it ` +
`works or not. If it doesn't, remove it and run ethnode again.`
);
process.exit(childResult.status);
}
}
}
async function run(
client,
{
download,
workdir,
port,
logging,
allocate,
chainId,
execute,
period,
nodeArguments,
}
) {
const loggingOptions = logging
? client === "geth"
? ["--verbosity", LOGLEVELS.indexOf(logging)]
: ["--logging", logging]
: [];
const paths = getPaths(client, workdir);
downloadClient(client, workdir, download);
if (download) {
return;
}
if (!fs.existsSync(paths.genesis)) {
await provide(
client,
workdir,
allocate,
chainId,
execute,
period,
loggingOptions
);
}
const genesis = JSON.parse(fs.readFileSync(paths.genesis));
const keypairs = await getKeypairs(
client === "geth" ? paths.keys : path.join(paths.keys, genesis.name),
"password"
);
if (!execute) {
console.log("Run development node using configuration in", workdir);
console.log("Test accounts");
console.log("# Address Private Key");
for (let i = 0; i < keypairs.length; i++) {
console.log(`${i}: ${keypairs[i].address} ${keypairs[i].privateKey}`);
}
if (allocate.length > 0) {
console.log();
console.log("Extra account allocations");
console.log("Address Private Key");
for (let i = 0; i < allocate.length; i++) {
console.log(`${allocate[i]} <no private key available>`);
}
}
console.log();
}
let args;
if (client === "geth") {
args = [
"--nodiscover",
"--datadir",
paths.data,
"--port",
"30311",
"--http",
"--http.addr",
"0.0.0.0",
"--http.port",
port,
"--http.api",
"personal,eth,net,web3,txpool,miner,debug",
"--http.corsdomain",
"*",
"--ws",
"--ws.addr",
"0.0.0.0",
"--ws.port",
"8546",
"--ws.api",
"personal,eth,net,web3,txpool,miner,debug",
"--ws.origins",
"*",
"--mine",
"--miner.gastarget",
"94000000",
"--miner.gasprice",
"1000000000",
"--allow-insecure-unlock",
"--keystore",
paths.keys,
"--unlock",
keypairs.map((keypair) => keypair.address).join(","),
"--password",
paths.password,
"--networkid",
genesis.config.chainId,
...loggingOptions,
];
} else if (client === "openethereum") {
args = [
"--no-discovery",
"--db-path",
paths.data,
"--jsonrpc-port",
port,
"--chain",
paths.genesis,
"--keys-path",
paths.keys,
"--min-gas-price",
"4000000000",
"--jsonrpc-cors",
"all",
"--jsonrpc-apis",
"all",
"--ws-apis",
"all",
"--ws-origins",
"all",
"--fast-unlock",
"--unlock",
keypairs.map((keypair) => keypair.address).join(","),
"--password",
paths.password,
"--network-id",
parseInt(genesis.params.networkID, 16),
...loggingOptions,
];
} else {
throw `Client "${client}" is not supported`;
}
if (nodeArguments) args.push(nodeArguments);
if (logging === "debug") {
console.log("running:", paths.binary, args.join(" "));
}
const clientProcess = spawn(paths.binary, args, {
stdio: execute ? ["ignore", "ignore", "ignore"] : "inherit",
});
let executeProcess;
clientProcess.on("close", (code) => {
if (code !== 0) {
console.log("Error executing ethnode. Exit code:", code);
}
if (executeProcess) {
executeProcess.kill();
}
process.exit(code);
});
if (execute) {
executeProcess = spawn(execute, { stdio: "inherit", shell: true });
executeProcess.on("close", (code) => {
clientProcess.kill();
process.exit(code);
});
}
}
module.exports = run;