This repository has been archived by the owner on Sep 5, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathethereumNode.js
512 lines (392 loc) · 14.3 KB
/
ethereumNode.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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
const _ = global._;
const fs = require('fs');
const Q = require('bluebird');
const spawn = require('child_process').spawn;
const { dialog } = require('electron');
const Windows = require('./windows.js');
const Settings = require('./settings');
const log = require('./utils/logger').create('EthereumNode');
const logRotate = require('log-rotate');
const EventEmitter = require('events').EventEmitter;
const Sockets = require('./socketManager');
const ClientBinaryManager = require('./clientBinaryManager');
const DEFAULT_NODE_TYPE = 'geth';
const DEFAULT_NETWORK = 'main';
const UNABLE_TO_BIND_PORT_ERROR = 'unableToBindPort';
const UNABLE_TO_SPAWN_ERROR = 'unableToSpan';
const PASSWORD_WRONG_ERROR = 'badPassword';
const NODE_START_WAIT_MS = 3000;
/**
* Etheruem nodes manager.
*/
class EthereumNode extends EventEmitter {
constructor() {
super();
this.STATES = STATES;
this._loadDefaults();
this._node = null;
this._type = null;
this._network = null;
this._socket = Sockets.get('node-ipc', Settings.rpcMode);
this.on('data', _.bind(this._logNodeData, this));
}
get isOwnNode() {
return !!this._node;
}
get isExternalNode() {
return !this._node;
}
get isIpcConnected() {
return this._socket.isConnected;
}
get type() {
return this.isOwnNode ? this._type : null;
}
get network() {
return this.isOwnNode ? this._network : null;
}
get isEth() {
return this._type === 'eth';
}
get isGeth() {
return this._type === 'geth';
}
get isMainNetwork() {
return this.network === 'main';
}
get isTestNetwork() {
return this.network === 'test';
}
get state() {
return this._state;
}
get stateAsText() {
switch (this._state) {
case STATES.STARTING:
return 'starting';
case STATES.STARTED:
return 'started';
case STATES.CONNECTED:
return 'connected';
case STATES.STOPPING:
return 'stopping';
case STATES.STOPPED:
return 'stopped';
case STATES.ERROR:
return 'error';
}
}
set state(newState) {
this._state = newState;
this.emit('state', this.state, this.stateAsText);
}
get lastError() {
return this._lastErr;
}
set lastError(err) {
return this._lastErr = err;
}
/**
* This method should always be called first to initialise the connection.
* @return {Promise}
*/
init() {
return this._socket.connect(Settings.rpcConnectConfig)
.then(() => {
this.state = STATES.CONNECTED;
this.emit('runningNodeFound');
})
.catch((err) => {
log.warn('Failed to connect to node. Maybe it\'s not running so let\'s start our own...');
log.info(`Node type: ${this.defaultNodeType}`);
log.info(`Network: ${this.defaultNetwork}`);
// if not, start node yourself
return this._start(this.defaultNodeType, this.defaultNetwork)
.catch((err) => {
log.error('Failed to start node', err);
throw err;
});
});
}
restart(newType, newNetwork) {
return Q.try(() => {
if (!this.isOwnNode) {
throw new Error('Cannot restart node since it was started externally');
}
log.info('Restart node', newType, newNetwork);
return this.stop()
.then(() => {
Windows.loading.show();
})
.then(() => {
return this._start(newType || this.type, newNetwork || this.network);
})
.then(() => {
Windows.loading.hide();
})
.catch((err) => {
log.error('Error restarting node', err);
throw err;
});
});
}
/**
* Stop node.
*
* @return {Promise}
*/
stop() {
if (!this._stopPromise) {
return new Q((resolve, reject) => {
if (!this._node) {
return resolve();
}
this.state = STATES.STOPPING;
log.info(`Stopping existing node: ${this._type} ${this._network}`);
this._node.stderr.removeAllListeners('data');
this._node.stdout.removeAllListeners('data');
this._node.stdin.removeAllListeners('error');
this._node.removeAllListeners('error');
this._node.removeAllListeners('exit');
this._node.kill('SIGINT');
// after some time just kill it if not already done so
const killTimeout = setTimeout(() => {
if (this._node) {
this._node.kill('SIGKILL');
}
}, 8000 /* 8 seconds */);
this._node.once('close', () => {
clearTimeout(killTimeout);
this._node = null;
resolve();
});
})
.then(() => {
this.state = STATES.STOPPED;
this._stopPromise = null;
});
} else {
log.debug('Disconnection already in progress, returning Promise.');
}
return this._stopPromise;
}
getLog() {
return Settings.loadUserData('node.log');
}
/**
* Send Web3 command to socket.
* @param {String} method Method name
* @param {Array} [params] Method arguments
* @return {Promise} resolves to result or error.
*/
send(method, params) {
return this._socket.send({
method,
params,
});
}
/**
* Start an ethereum node.
* @param {String} nodeType geth, eth, etc
* @param {String} network network id
* @return {Promise}
*/
_start(nodeType, network) {
log.info(`Start node: ${nodeType} ${network}`);
const isTestNet = (network === 'test');
if (isTestNet) {
log.debug('Node will connect to the test network');
}
return this.stop()
.then(() => {
return this.__startNode(nodeType, network)
.catch((err) => {
log.error('Failed to start node', err);
this._showNodeErrorDialog(nodeType, network);
throw err;
});
})
.then((proc) => {
log.info(`Started node successfully: ${nodeType} ${network}`);
this._node = proc;
this.state = STATES.STARTED;
Settings.saveUserData('node', this._type);
Settings.saveUserData('network', this._network);
return this._socket.connect(Settings.rpcConnectConfig, {
timeout: 30000, /* 30s */
})
.then(() => {
this.state = STATES.CONNECTED;
})
.catch((err) => {
log.error('Failed to connect to node', err);
if (err.toString().indexOf('timeout') >= 0) {
this.emit('nodeConnectionTimeout');
}
this._showNodeErrorDialog(nodeType, network);
throw err;
});
})
.catch((err) => {
// set before updating state so that state change event observers
// can pick up on this
this.lastError = err.tag;
this.state = STATES.ERROR;
// if unable to start eth node then write geth to defaults
if (nodeType === 'eth') {
Settings.saveUserData('node', 'geth');
}
throw err;
});
}
/**
* @return {Promise}
*/
__startNode(nodeType, network) {
this.state = STATES.STARTING;
this._network = network;
this._type = nodeType;
const client = ClientBinaryManager.getClient(nodeType);
let binPath;
if (client) {
binPath = client.binPath;
} else {
throw new Error(`Node "${nodeType}" binPath is not available.`);
}
log.info(`Start node using ${binPath}`);
return new Q((resolve, reject) => {
this.__startProcess(nodeType, network, binPath)
.then(resolve, reject);
});
}
/**
* @return {Promise}
*/
__startProcess(nodeType, network, binPath) {
return new Q((resolve, reject) => {
log.trace('Rotate log file');
// rotate the log file
logRotate(Settings.constructUserDataPath('node.log'), { count: 5 }, (err) => {
if (err) {
log.error('Log rotation problems', err);
return reject(err);
}
let args;
// START TESTNET
if (network == 'test') {
args = (nodeType === 'geth')
? ['--testnet', '--fast', '--ipcpath', Settings.rpcIpcPath]
: ['--morden', '--unsafe-transactions'];
}
// START MAINNET
else {
args = (nodeType === 'geth')
? ['--fast', '--cache', '1024']
: ['--unsafe-transactions'];
}
const nodeOptions = Settings.nodeOptions;
if (nodeOptions && nodeOptions.length) {
log.debug('Custom node options', nodeOptions);
args = args.concat(nodeOptions);
}
log.trace('Spawn', binPath, args);
const proc = spawn(binPath, args);
// node has a problem starting
proc.once('error', (err) => {
if (STATES.STARTING === this.state) {
this.state = STATES.ERROR;
log.info('Node startup error');
// TODO: detect this properly
// this.emit('nodeBinaryNotFound');
reject(err);
}
});
// we need to read the buff to prevent node from not working
proc.stderr.pipe(
fs.createWriteStream(Settings.constructUserDataPath('node.log'), { flags: 'a' })
);
// when proc outputs data
proc.stdout.on('data', (data) => {
log.trace('Got stdout data');
this.emit('data', data);
// check for startup errors
if (STATES.STARTING === this.state) {
const dataStr = data.toString().toLowerCase();
if (nodeType === 'geth') {
if (dataStr.indexOf('fatal: error') >= 0) {
const err = new Error(`Geth error: ${dataStr}`);
if (dataStr.indexOf('bind') >= 0) {
err.tag = UNABLE_TO_BIND_PORT_ERROR;
}
log.debug(err.message);
return reject(err);
}
}
}
});
// when proc outputs data in stderr
proc.stderr.on('data', (data) => {
log.trace('Got stderr data');
this.emit('data', data);
});
this.on('data', _.bind(this._logNodeData, this));
// when data is first received
this.once('data', () => {
/*
We wait a short while before marking startup as successful
because we may want to parse the initial node output for
errors, etc (see geth port-binding error above)
*/
setTimeout(() => {
if (STATES.STARTING === this.state) {
log.info(`${NODE_START_WAIT_MS}ms elapsed, assuming node started up successfully`);
resolve(proc);
}
}, NODE_START_WAIT_MS);
});
});
});
}
_showNodeErrorDialog(nodeType, network) {
let nodelog = this.getLog();
if (nodelog) {
nodelog = `...${nodelog.slice(-1000)}`;
} else {
nodelog = global.i18n.t('mist.errors.nodeStartup');
}
// add node type
nodelog = `Node type: ${nodeType}\n` +
`Network: ${network}\n` +
`Platform: ${process.platform} (Architecure ${process.arch})` + `\n\n${
nodelog}`;
dialog.showMessageBox({
type: 'error',
buttons: ['OK'],
message: global.i18n.t('mist.errors.nodeConnect'),
detail: nodelog,
}, () => {});
}
_logNodeData(data) {
data = data.toString().replace(/[\r\n]+/, '');
const nodeType = (this.type || 'node').toUpperCase();
log.trace(`${nodeType}: ${data}`);
if (!/^\-*$/.test(data) && !_.isEmpty(data)) {
this.emit('nodeLog', data);
}
}
_loadDefaults() {
log.trace('Load defaults');
this.defaultNodeType = Settings.nodeType || Settings.loadUserData('node') || DEFAULT_NODE_TYPE;
this.defaultNetwork = Settings.network || Settings.loadUserData('network') || DEFAULT_NETWORK;
}
}
const STATES = {
STARTING: 0, /* Node about to be started */
STARTED: 1, /* Node started */
CONNECTED: 2, /* IPC connected - all ready */
STOPPING: 3, /* Node about to be stopped */
STOPPED: 4, /* Node stopped */
ERROR: -1, /* Unexpected error */
};
EthereumNode.STARTING = 0;
module.exports = new EthereumNode();