forked from ethereum/mist
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
529 lines (419 loc) · 15.8 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
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
global._ = require('./modules/utils/underscore');
const { app, dialog, ipcMain, shell, protocol } = require('electron');
const timesync = require('os-timesync');
const dbSync = require('./modules/dbSync.js');
const i18n = require('./modules/i18n.js');
const logger = require('./modules/utils/logger');
const Sockets = require('./modules/socketManager');
const Windows = require('./modules/windows');
const ClientBinaryManager = require('./modules/clientBinaryManager');
const UpdateChecker = require('./modules/updateChecker');
const Settings = require('./modules/settings');
const Q = require('bluebird');
const windowStateKeeper = require('electron-window-state');
Q.config({
cancellation: true,
});
// logging setup
const log = logger.create('main');
Settings.init();
if (Settings.cli.version) {
log.info(Settings.appVersion);
process.exit(0);
}
if (Settings.cli.ignoreGpuBlacklist) {
app.commandLine.appendSwitch('ignore-gpu-blacklist', 'true');
}
if (Settings.inAutoTestMode) {
log.info('AUTOMATED TESTING');
}
log.info(`Running in production mode: ${Settings.inProductionMode}`);
if (Settings.rpcMode === 'http') {
log.warn('Connecting to a node via HTTP instead of ipcMain. This is less secure!!!!'.toUpperCase());
}
// db
const db = global.db = require('./modules/db');
require('./modules/ipcCommunicator.js');
const appMenu = require('./modules/menuItems');
const ipcProviderBackend = require('./modules/ipc/ipcProviderBackend.js');
const ethereumNode = require('./modules/ethereumNode.js');
const swarmNode = require('./modules/swarmNode.js');
const nodeSync = require('./modules/nodeSync.js');
global.webviews = [];
global.mining = false;
global.icon = `${__dirname}/icons/${Settings.uiMode}/icon.png`;
global.mode = Settings.uiMode;
global.dirname = __dirname;
global.i18n = i18n;
// INTERFACE PATHS
// - WALLET
if (Settings.uiMode === 'wallet') {
log.info('Starting in Wallet mode');
global.interfaceAppUrl = (Settings.inProductionMode)
? `file://${__dirname}/interface/wallet/index.html`
: 'http://localhost:3050';
global.interfacePopupsUrl = (Settings.inProductionMode)
? `file://${__dirname}/interface/index.html`
: 'http://localhost:3000';
// - MIST
} else {
log.info('Starting in Mist mode');
let url = (Settings.inProductionMode)
? `file://${__dirname}/interface/index.html`
: 'http://localhost:3000';
if (Settings.cli.resetTabs) {
url += '?reset-tabs=true';
}
global.interfaceAppUrl = global.interfacePopupsUrl = url;
}
// prevent crashed and close gracefully
process.on('uncaughtException', (error) => {
log.error('UNCAUGHT EXCEPTION', error);
app.quit();
});
// Quit when all windows are closed.
app.on('window-all-closed', () => {
app.quit();
});
// Listen to custom protocole incoming messages, needs registering of URL schemes
app.on('open-url', (e, url) => {
log.info('Open URL', url);
});
let killedSocketsAndNodes = false;
app.on('before-quit', (event) => {
if (!killedSocketsAndNodes) {
log.info('Defer quitting until sockets and node are shut down');
event.preventDefault();
// sockets manager
Sockets.destroyAll()
.catch(() => {
log.error('Error shutting down sockets');
});
// delay quit, so the sockets can close
setTimeout(async () => {
await ethereumNode.stop()
killedSocketsAndNodes = true;
await db.close();
app.quit();
}, 500);
} else {
log.info('About to quit...');
}
});
let mainWindow;
let splashWindow;
let onReady;
let startMainWindow;
// This method will be called when Electron has done everything
// initialization and ready for creating browser windows.
app.on('ready', () => {
// if using HTTP RPC then inform user
if (Settings.rpcMode === 'http') {
dialog.showErrorBox('Insecure RPC connection', `
WARNING: You are connecting to an Ethereum node via: ${Settings.rpcHttpPath}
This is less secure than using local IPC - your passwords will be sent over the wire in plaintext.
Only do this if you have secured your HTTP connection or you know what you are doing.
`);
}
// initialise the db
global.db.init().then(onReady).catch((err) => {
log.error(err);
app.quit();
});
});
// Allows the Swarm protocol to behave like http
protocol.registerStandardSchemes(['bzz']);
onReady = () => {
global.config = db.getCollection('SYS_config');
// setup DB sync to backend
dbSync.backendSyncInit();
// Initialise window mgr
Windows.init();
// Enable the Swarm protocol
protocol.registerHttpProtocol('bzz', (request, callback) => {
const redirectPath = `${Settings.swarmURL}/${request.url.replace('bzz:/', 'bzz://')}`;
callback({ method: request.method, referrer: request.referrer, url: redirectPath });
}, (error) => {
if (error) {
log.error(error);
}
});
// check for update
if (!Settings.inAutoTestMode) UpdateChecker.run();
// initialize the web3 IPC provider backend
ipcProviderBackend.init();
// instantiate custom protocols
// require('./customProtocols.js');
// change to user language now that global.config object is ready
i18n.changeLanguage(Settings.language);
// add menu already here, so we have copy and past functionality
appMenu();
// Create the browser window.
const defaultWindow = windowStateKeeper({
defaultWidth: 1024 + 208,
defaultHeight: 720
});
// MIST
if (Settings.uiMode === 'mist') {
mainWindow = Windows.create('main', {
primary: true,
electronOptions: {
width: Math.max(defaultWindow.width, 500),
height: Math.max(defaultWindow.height, 440),
x: defaultWindow.x,
y: defaultWindow.y,
webPreferences: {
nodeIntegration: true, /* necessary for webviews;
require will be removed through preloader */
preload: `${__dirname}/modules/preloader/mistUI.js`,
'overlay-fullscreen-video': true,
'overlay-scrollbars': true,
experimentalFeatures: true,
},
},
});
// WALLET
} else {
mainWindow = Windows.create('main', {
primary: true,
electronOptions: {
width: Math.max(defaultWindow.width, 500),
height: Math.max(defaultWindow.height, 440),
x: defaultWindow.x,
y: defaultWindow.y,
webPreferences: {
preload: `${__dirname}/modules/preloader/walletMain.js`,
'overlay-fullscreen-video': true,
'overlay-scrollbars': true,
},
},
});
}
// Delegating events to save window bounds on windowStateKeeper
defaultWindow.manage(mainWindow.window);
if (!Settings.inAutoTestMode) {
splashWindow = Windows.create('splash', {
primary: true,
url: `${global.interfacePopupsUrl}#splashScreen_${Settings.uiMode}`,
show: true,
electronOptions: {
width: 400,
height: 230,
resizable: false,
backgroundColor: '#F6F6F6',
useContentSize: true,
frame: false,
webPreferences: {
preload: `${__dirname}/modules/preloader/splashScreen.js`,
},
},
});
}
// check time sync
// var ntpClient = require('ntp-client');
// ntpClient.getNetworkTime("pool.ntp.org", 123, function(err, date) {
timesync.checkEnabled((err, enabled) => {
if (err) {
log.error('Couldn\'t get time from NTP time sync server.', err);
return;
}
if (!enabled) {
dialog.showMessageBox({
type: 'warning',
buttons: ['OK'],
message: global.i18n.t('mist.errors.timeSync.title'),
detail: `${global.i18n.t('mist.errors.timeSync.description')}\n\n${global.i18n.t(`mist.errors.timeSync.${process.platform}`)}`,
}, () => {
});
}
});
const kickStart = () => {
// client binary stuff
ClientBinaryManager.on('status', (status, data) => {
Windows.broadcast('uiAction_clientBinaryStatus', status, data);
});
// node connection stuff
ethereumNode.on('nodeConnectionTimeout', () => {
Windows.broadcast('uiAction_nodeStatus', 'connectionTimeout');
});
ethereumNode.on('nodeLog', (data) => {
Windows.broadcast('uiAction_nodeLogText', data.replace(/^.*[0-9]]/, ''));
});
// state change
ethereumNode.on('state', (state, stateAsText) => {
Windows.broadcast('uiAction_nodeStatus', stateAsText,
ethereumNode.STATES.ERROR === state ? ethereumNode.lastError : null
);
});
// starting swarm
swarmNode.on('starting', () => {
Windows.broadcast('uiAction_swarmStatus', 'starting');
});
// swarm download progress
swarmNode.on('downloadProgress', (progress) => {
Windows.broadcast('uiAction_swarmStatus', 'downloadProgress', progress);
});
// started swarm
swarmNode.on('started', (isLocal) => {
Windows.broadcast('uiAction_swarmStatus', 'started', isLocal);
});
// capture sync results
const syncResultPromise = new Q((resolve, reject) => {
nodeSync.on('nodeSyncing', (result) => {
Windows.broadcast('uiAction_nodeSyncStatus', 'inProgress', result);
});
nodeSync.on('stopped', () => {
Windows.broadcast('uiAction_nodeSyncStatus', 'stopped');
});
nodeSync.on('error', (err) => {
log.error('Error syncing node', err);
reject(err);
});
nodeSync.on('finished', () => {
nodeSync.removeAllListeners('error');
nodeSync.removeAllListeners('finished');
resolve();
});
});
// check legacy chain
// CHECK for legacy chain (FORK RELATED)
Q.try(() => {
// open the legacy chain message
if ((Settings.loadUserData('daoFork') || '').trim() === 'false') {
dialog.showMessageBox({
type: 'warning',
buttons: ['OK'],
message: global.i18n.t('mist.errors.legacyChain.title'),
detail: global.i18n.t('mist.errors.legacyChain.description')
}, () => {
shell.openExternal('https://github.com/ethereum/mist/releases');
app.quit();
});
throw new Error('Cant start client due to legacy non-Fork setting.');
}
})
.then(() => {
return ClientBinaryManager.init();
})
.then(() => {
return ethereumNode.init();
})
.then(() => {
// Wallet shouldn't start Swarm
if (Settings.uiMode === 'wallet') {
return Promise.resolve();
}
return swarmNode.init();
})
.then(function sanityCheck() {
if (!ethereumNode.isIpcConnected) {
throw new Error('Either the node didn\'t start or IPC socket failed to connect.');
}
/* At this point Geth is running and the socket is connected. */
log.info('Connected via IPC to node.');
// update menu, to show node switching possibilities
appMenu();
})
.then(function getAccounts() {
return ethereumNode.send('eth_accounts', []);
})
.then(function onboarding(resultData) {
if (ethereumNode.isGeth && (resultData.result === null || (_.isArray(resultData.result) && resultData.result.length === 0))) {
log.info('No accounts setup yet, lets do onboarding first.');
return new Q((resolve, reject) => {
const onboardingWindow = Windows.createPopup('onboardingScreen', {
primary: true,
electronOptions: {
width: 576,
height: 442,
},
});
onboardingWindow.on('closed', () => {
app.quit();
});
// change network types (mainnet, testnet)
ipcMain.on('onBoarding_changeNet', (e, testnet) => {
const newType = ethereumNode.type;
const newNetwork = testnet ? 'rinkeby' : 'main';
log.debug('Onboarding change network', newType, newNetwork);
ethereumNode.restart(newType, newNetwork)
.then(function nodeRestarted() {
appMenu();
})
.catch((err) => {
log.error('Error restarting node', err);
reject(err);
});
});
// launch app
ipcMain.on('onBoarding_launchApp', () => {
// prevent that it closes the app
onboardingWindow.removeAllListeners('closed');
onboardingWindow.close();
ipcMain.removeAllListeners('onBoarding_changeNet');
ipcMain.removeAllListeners('onBoarding_launchApp');
resolve();
});
if (splashWindow) {
splashWindow.hide();
}
});
}
return;
})
.then(function doSync() {
// we're going to do the sync - so show splash
if (splashWindow) {
splashWindow.show();
}
if (!Settings.inAutoTestMode) {
return syncResultPromise;
}
return;
})
.then(function allDone() {
startMainWindow();
})
.catch((err) => {
log.error('Error starting up node and/or syncing', err);
}); /* socket connected to geth */
}; /* kick start */
if (splashWindow) {
splashWindow.on('ready', kickStart);
} else {
kickStart();
}
}; /* onReady() */
/**
Start the main window and all its processes
@method startMainWindow
*/
startMainWindow = () => {
log.info(`Loading Interface at ${global.interfaceAppUrl}`);
mainWindow.on('ready', () => {
if (splashWindow) {
splashWindow.close();
}
mainWindow.show();
});
mainWindow.load(global.interfaceAppUrl);
// close app, when the main window is closed
mainWindow.on('closed', () => {
app.quit();
});
// observe Tabs for changes and refresh menu
const Tabs = global.db.getCollection('UI_tabs');
const sortedTabs = Tabs.addDynamicView('sorted_tabs');
sortedTabs.applySimpleSort('position', false);
const refreshMenu = () => {
clearTimeout(global._refreshMenuFromTabsTimer);
global._refreshMenuFromTabsTimer = setTimeout(() => {
log.debug('Refresh menu with tabs');
global.webviews = sortedTabs.data();
appMenu(global.webviews);
}, 1000);
};
Tabs.on('insert', refreshMenu);
Tabs.on('update', refreshMenu);
Tabs.on('delete', refreshMenu);
};