forked from ethereum/mist
-
Notifications
You must be signed in to change notification settings - Fork 19
/
main.js
executable file
·678 lines (553 loc) · 20.6 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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
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');
const fs = require('fs');
const path = require('path');
Q.config({
cancellation: true,
});
Settings.init();
// logging setup
const log = logger.create('main');
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');
let startCCinit = require('./modules/crossChain/crossChainIPC.js').init;
let startCCinitErc20 = require('./modules/crossChainErc20/crossChainIPC.js').init;
let startCCinitBtc = require('./modules/crossChainBtc/crossChainIpcBtc.js').init;
let upgradeDb = require('./modules/upgradeDb');
upgradeDb.initLog(logger.create("upgradeDb"));
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');
const nodeScanOta = require('./modules/wanChain/nodeScanOta');
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();
});
});
function mkdirsSync(dirname) {
//console.log(dirname);
if (fs.existsSync(dirname)) {
return true;
} else {
if (mkdirsSync(path.dirname(dirname))) {
fs.mkdirSync(dirname);
return true;
}
}
}
async function startCrossChain(){
log.debug('startCCinit...');
try{
await startCCinit();
}catch(error){
log.error("startCrossChain: ", error.toString());
}
log.debug('startCCinit...finish!');
log.debug('startCCinitErc20...');
try{
await startCCinitErc20();
}catch(error){
log.error("startCrossChainErc20: ", error.toString());
}
log.debug('startCCinitErc20...finish!');
log.debug('startCCinitBtc...');
try{
await startCCinitBtc();
}catch(error){
log.error("startCrossChainBtc: ", error.toString());
}
log.debug('startCCinitBtc...finish!');
return new Q((resolve, reject) => {
resolve(this);
});
}
function copy(src, dst) {
fs.writeFileSync(dst, fs.readFileSync(src));
}
// Allows the Swarm protocol to behave like http
protocol.registerStandardSchemes(['bzz']);
onReady = () => {
global.sysconfig = db.getCollection('SYS_config');
// setup DB sync to backend
dbSync.backendSyncInit();
// Initialise window mgr
Windows.init();
// Enable the Swarm protocolfv
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.sysconfig object is ready
i18n.changeLanguage(Settings.language);
// add menu already here, so we have copy and past functionality
appMenu();
// Create the browser window.
let gwan = 'gwan';
let gwanto = 'gwan';
log.info('platform: ' + process.platform);
if(process.platform === 'win32'){
gwan = gwan + '.exe';
gwanto = gwan;
}else if(process.platform === 'darwin'){
gwan = gwan + '_mac';
}else {
gwan = gwan + '_linux';
}
let exePath = path.dirname(app.getPath('exe'));
let filePath = path.join(Settings.userDataPath, 'binaries', 'Gwan', 'unpacked');
let fromPath = path.join(exePath,gwan);
let toPath = path.join(filePath ,gwanto);
log.debug('copy Gwan from :' + fromPath);
log.debug('copy Gwan to :' + toPath);
if(fs.existsSync(fromPath))
{
if(!fs.existsSync(filePath))
{
log.info('create Gwan path:' + filePath);
mkdirsSync(filePath);
}
let timeto = 0;
if(fs.existsSync(toPath)){
timeto = fs.statSync(toPath).mtime.getTime();
let timefrom = fs.statSync(fromPath).mtime.getTime();
log.debug("timeto:", timeto);
log.debug("timefrom:", timefrom);
if( timeto < timefrom){
copy(fromPath,toPath);
fs.chmodSync(toPath, '0755');
log.info(gwan, " copied");
}
} else {
copy(fromPath,toPath);
fs.chmodSync(toPath, '0755');
log.info(gwan, " copied");
}
}
// copy clientBinarys.json
let cbJsonFrom = path.join(exePath, 'clientBinaries.json');
let cbJsonTo = path.join(Settings.userDataPath, 'clientBinaries.json');
log.debug("cbJsonTo:", cbJsonTo);
log.debug("cbJsonFrom:", cbJsonFrom);
if(fs.existsSync(cbJsonFrom))
{
// compare the file change time, if need copy file. don't delete. because the file maybe installed by root.
let timeto=0;
let timefrom;
let configTo;
let configToVersion;
let configFrom;
let configFromVersion;
if(fs.existsSync(cbJsonTo)){
timeto = fs.statSync(cbJsonTo).mtime.getTime();
configTo = JSON.parse(fs.readFileSync(cbJsonTo));
configToVersion = parseInt(configTo.clients.Gwan.version.replace(/\./g,""));
}
timefrom = fs.statSync(cbJsonFrom).mtime.getTime();
configFrom = JSON.parse(fs.readFileSync(cbJsonFrom));
configFromVersion = parseInt(configFrom.clients.Gwan.version.replace(/\./g,""));
log.debug("configToVersion:", configToVersion);
log.debug("configFromVersion:", configFromVersion);
log.debug("timeto:", timeto);
log.debug("timefrom:", timefrom);
if((timeto < timefrom) || (configToVersion < configFromVersion)){
copy(cbJsonFrom, cbJsonTo);
log.info("clientBinaries.json copied");
}
}
const defaultWindow = windowStateKeeper({
defaultWidth: 1024 + 208,
defaultHeight: 720
});
log.info('appDataPath:' + Settings.appDataPath);
// 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);
const shouldQuit = app.makeSingleInstance((commandLine, workingDirectory) => {
console.log("Another instance exist.");
});
if (shouldQuit) {
app.quit();
}
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`,
},
},
});
}
// Checks time sync
if (!Settings.skiptimesynccheck) {
timesync.checkEnabled((err, enabled) => {
if (err) {
log.error('Couldn\'t infer if computer automatically syncs time.');
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/wanchain/wanwallet/releases');
app.quit();
});
throw new Error('Cant start client due to legacy non-Fork setting.');
}
})
.then(() => {
return ClientBinaryManager.init();
})
.then(() => {
return ethereumNode.init();
})
.then(()=>{
return startCrossChain();
})
.then(() => {
upgradeDb.upgradeDb_2_1(Settings.userDataPath,Settings.network);
})
.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) {
// don't popup the network select window, because that will result in socket error to change network.
if (false && 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 ? 'pluto' : '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.getDynamicView('sorted_tabs') || 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);
};