forked from LiskArchive/lisk-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
806 lines (740 loc) Β· 19.2 KB
/
app.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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
/*
* Copyright Β© 2018 Lisk Foundation
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be copied, modified,
* propagated, or distributed except according to the terms contained in the
* LICENSE file.
*
* Removal or modification of this copyright notice is prohibited.
*/
'use strict';
var path = require('path');
var fs = require('fs');
var d = require('domain').create();
var SocketCluster = require('socketcluster');
var async = require('async');
var Logger = require('./logger.js');
var wsRPC = require('./api/ws/rpc/ws_rpc').wsRPC;
var wsTransport = require('./api/ws/transport');
var AppConfig = require('./helpers/config.js');
var git = require('./helpers/git.js');
var Sequence = require('./helpers/sequence.js');
var httpApi = require('./helpers/http_api.js');
// eslint-disable-next-line import/order
var swaggerHelper = require('./helpers/swagger');
/**
* Main application entry point.
*
* @namespace app
* @requires async
* @requires domain.create
* @requires fs
* @requires socketcluster
* @requires logger.js
* @requires api/ws/rpc/ws_rpc.wsRPC
* @requires helpers/config
* @requires helpers/git
* @requires helpers/http_api
* @requires {@link helpers.Sequence}
* @requires helpers/swagger
* @requires config/swagger
*/
/**
* Handles app instance (acts as global variable, passed as parameter).
*
* @global
* @typedef {Object} scope
* @property {Object} api
* @property {undefined} balancesSequence
* @property {string} build
* @property {Object} bus
* @property {Object} config
* @property {undefined} connect
* @property {Object} db
* @property {Object} ed
* @property {Object} genesisBlock
* @property {string} lastCommit
* @property {Object} listen
* @property {Object} logger
* @property {Object} logic
* @property {Object} modules
* @property {Object} network
* @property {string} nonce
* @property {undefined} ready
* @property {Object} schema
* @property {Object} sequence
* @todo Add description for nonce and ready
*/
// Define workers_controller path
var workersControllerPath = path.join(__dirname, 'workers_controller');
// Begin reading from stdin
process.stdin.resume();
// Read build version from file
var versionBuild = fs.readFileSync(path.join(__dirname, 'build'), 'utf8');
/**
* Hash of the last git commit.
*
* @memberof! app
*/
var lastCommit = '';
if (typeof gc !== 'undefined') {
setInterval(() => {
gc(); // eslint-disable-line no-undef
}, 60000);
}
/**
* Default list of configuration options. Can be overridden by CLI.
*
* @memberof! app
* @default 'config.json'
*/
var appConfig = AppConfig(require('./package.json'));
// Define lisk network env variable to be used by child processes load config files
process.env.LISK_NETWORK = appConfig.network;
// Global objects to be utilized under modules/helpers where scope is not accessible
global.constants = appConfig.constants;
global.exceptions = appConfig.exceptions;
/**
* Application config object.
*
* @memberof! app
*/
var config = {
db: appConfig.db,
cache: appConfig.redis,
cacheEnabled: appConfig.cacheEnabled,
modules: {
accounts: './modules/accounts.js',
blocks: './modules/blocks.js',
cache: './modules/cache.js',
dapps: './modules/dapps.js',
delegates: './modules/delegates.js',
rounds: './modules/rounds.js',
loader: './modules/loader.js',
multisignatures: './modules/multisignatures.js',
node: './modules/node.js',
peers: './modules/peers.js',
system: './modules/system.js',
signatures: './modules/signatures.js',
transactions: './modules/transactions.js',
transport: './modules/transport.js',
voters: './modules/voters',
},
};
/**
* Application logger instance.
*
* @memberof! app
*/
var logger = new Logger({
echo: process.env.LOG_LEVEL || appConfig.consoleLogLevel,
errorLevel: process.env.FILE_LOG_LEVEL || appConfig.fileLogLevel,
filename: appConfig.logFileName,
});
/**
* Db logger instance.
*
* @memberof! app
*/
var dbLogger = null;
if (
appConfig.db.logFileName &&
appConfig.db.logFileName === appConfig.logFileName
) {
dbLogger = logger;
} else {
// since log levels for database monitor are different than node app, i.e. "query", "info", "error" etc, which is decided using "logEvents" property
dbLogger = new Logger({
echo: process.env.DB_LOG_LEVEL || 'log',
errorLevel: process.env.FILE_LOG_LEVEL || 'log',
filename: appConfig.db.logFileName,
});
}
// Try to get the last git commit
try {
lastCommit = git.getLastCommit();
} catch (err) {
logger.debug('Cannot get last git commit', err.message);
}
// Domain error handler
d.on('error', err => {
logger.fatal('Domain master', { message: err.message, stack: err.stack });
process.exit(0);
});
logger.info(`Starting lisk with "${appConfig.network}" genesis block.`);
// Run domain
d.run(() => {
var modules = [];
async.auto(
{
/**
* Attempts to determine nethash from genesis block.
*
* @func config
* @memberof! app
* @param {function} cb - Callback function
* @throws {Error} If unable to assign nethash from genesis block
*/
config(cb) {
if (!appConfig.nethash) {
throw Error('Failed to assign nethash from genesis block');
}
cb(null, appConfig);
},
logger(cb) {
cb(null, logger);
},
build(cb) {
cb(null, versionBuild);
},
/**
* Returns hash of the last git commit.
*
* @func lastCommit
* @memberof! app
* @param {function} cb - Callback function
*/
lastCommit(cb) {
cb(null, lastCommit);
},
genesisBlock(cb) {
cb(null, {
block: appConfig.genesisBlock,
});
},
schema(cb) {
cb(null, swaggerHelper.getValidator());
},
network: [
'config',
/**
* Initalizes express, middleware, socket.io.
*
* @func network[1]
* @memberof! app
* @param {Object} scope
* @param {function} cb - Callback function
*/
function(scope, cb) {
var express = require('express');
var app = express();
if (appConfig.coverage) {
// eslint-disable-next-line import/no-extraneous-dependencies
var im = require('istanbul-middleware');
logger.debug(
'Hook loader for coverage - Do not use in production environment!'
);
im.hookLoader(__dirname);
app.use('/coverage', im.createHandler());
}
if (appConfig.trustProxy) {
app.enable('trust proxy');
}
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var privateKey;
var certificate;
var https;
var https_io;
if (scope.config.api.ssl.enabled) {
privateKey = fs.readFileSync(scope.config.api.ssl.options.key);
certificate = fs.readFileSync(scope.config.api.ssl.options.cert);
https = require('https').createServer(
{
key: privateKey,
cert: certificate,
ciphers:
'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA256:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA',
},
app
);
https_io = require('socket.io')(https);
}
cb(null, {
express,
app,
server,
io,
https,
https_io,
});
},
],
sequence: [
'logger',
/**
* Description of the function.
*
* @func sequence[1]
* @memberof! app
* @param {Object} scope
* @param {function} cb - Callback function
* @todo Add description for the function and its params
*/
function(scope, cb) {
var sequence = new Sequence({
onWarning(current) {
scope.logger.warn('Main queue', current);
},
});
cb(null, sequence);
},
],
balancesSequence: [
'logger',
/**
* Description of the function.
*
* @func balancesSequence[1]
* @memberof! app
* @param {Object} scope
* @param {function} cb - Callback function
* @todo Add description for the function and its params
*/
function(scope, cb) {
var sequence = new Sequence({
onWarning(current) {
scope.logger.warn('Balance queue', current);
},
});
cb(null, sequence);
},
],
swagger: [
'modules',
'logger',
'cache',
/**
* Description of the function.
*
* @func swagger[4]
* @memberof! app
* @param {Object} scope
* @param {function} cb - Callback function
* @todo Add description for the function and its params
*/
function(scope, cb) {
httpApi.bootstrapSwagger(
scope.network.app,
scope.config,
scope.logger,
scope,
cb
);
},
],
/**
* Description of the function.
*
* @func ed
* @memberof! app
* @param {function} cb - Callback function
* @todo Add description for the function and its params
*/
ed(cb) {
cb(null, require('./helpers/ed.js'));
},
bus: [
'ed',
/**
* Description of the function.
*
* @func bus[1]
* @memberof! app
* @param {Object} scope
* @param {function} cb - Callback function
* @todo Add description for the function and its params
*/
function(scope, cb) {
var changeCase = require('change-case');
var bus = function() {
this.message = function() {
var args = [];
Array.prototype.push.apply(args, arguments);
var topic = args.shift();
var eventName = `on${changeCase.pascalCase(topic)}`;
// Iterate over modules and execute event functions (on*)
modules.forEach(module => {
if (typeof module[eventName] === 'function') {
module[eventName].apply(module[eventName], args);
}
if (module.submodules) {
async.each(module.submodules, submodule => {
if (
submodule &&
typeof submodule[eventName] === 'function'
) {
submodule[eventName].apply(submodule[eventName], args);
}
});
}
});
};
};
cb(null, new bus());
},
],
/**
* Description of the function.
*
* @memberof! app
* @param {function} cb - Callback function
* @todo Add description for the function and its params
*/
db(cb) {
var db = require('./db');
db
.connect(config.db, dbLogger)
.then(db => cb(null, db))
.catch(cb);
},
/**
* Description of the function.
*
* @memberof! app
* @param {function} cb
* @todo Add description for the params
*/
cache(cb) {
var cache = require('./helpers/cache.js');
logger.debug(
`Cache ${appConfig.cacheEnabled ? 'Enabled' : 'Disabled'}`
);
cache.connect(config.cacheEnabled, config.cache, logger, cb);
},
webSocket: [
'config',
'logger',
'network',
'db',
/**
* Description of the function.
*
* @func webSocket[5]
* @memberof! app
* @param {Object} scope
* @param {function} cb - Callback function
* @todo Add description for the function and its params
*/
function(scope, cb) {
var webSocketConfig = {
workers: scope.config.wsWorkers,
port: scope.config.wsPort,
host: '0.0.0.0',
wsEngine: scope.config.peers.options.wsEngine,
appName: 'lisk',
workerController: workersControllerPath,
perMessageDeflate: false,
secretKey: 'liskSecretKey',
// Because our node is constantly sending messages, we don't
// need to use the ping feature to detect bad connections.
pingTimeoutDisabled: true,
// Maximum amount of milliseconds to wait before force-killing
// a process after it was passed a 'SIGTERM' or 'SIGUSR2' signal
processTermTimeout: 10000,
logLevel: 0,
};
var childProcessOptions = {
version: scope.config.version,
minVersion: scope.config.minVersion,
nethash: scope.config.nethash,
port: scope.config.wsPort,
nonce: scope.config.nonce,
blackListedPeers: scope.config.peers.access.blackList,
};
scope.socketCluster = new SocketCluster(webSocketConfig);
var MasterWAMPServer = require('wamp-socket-cluster/MasterWAMPServer');
scope.network.app.rpc = wsRPC.setServer(
new MasterWAMPServer(scope.socketCluster, childProcessOptions)
);
scope.socketCluster.on('ready', () => {
scope.logger.info('Socket Cluster ready for incoming connections');
cb();
});
// The 'fail' event aggregates errors from all SocketCluster processes.
scope.socketCluster.on('fail', err => {
scope.logger.error(err);
if (err.name === 'WSEngineInitError') {
var extendedError =
'If you are not able to install sc-uws, you can try setting the wsEngine property in config.json to "ws" before starting the node';
scope.logger.error(extendedError);
}
});
scope.socketCluster.on('workerExit', workerInfo => {
var exitMessage = `Worker with pid ${workerInfo.pid} exited`;
if (workerInfo.signal) {
exitMessage += ` due to signal: '${workerInfo.signal}'`;
}
scope.logger.error(exitMessage);
});
},
],
logic: [
'db',
'bus',
'schema',
'genesisBlock',
/**
* Description of the function.
*
* @func logic[4]
* @memberof! app
* @param {Object} scope
* @param {function} cb - Callback function
*/
function(scope, cb) {
var Transaction = require('./logic/transaction.js');
var Block = require('./logic/block.js');
var Account = require('./logic/account.js');
var Peers = require('./logic/peers.js');
async.auto(
{
bus(cb) {
cb(null, scope.bus);
},
db(cb) {
cb(null, scope.db);
},
ed(cb) {
cb(null, scope.ed);
},
logger(cb) {
cb(null, logger);
},
schema(cb) {
cb(null, scope.schema);
},
genesisBlock(cb) {
cb(null, scope.genesisBlock);
},
account: [
'db',
'bus',
'ed',
'schema',
'genesisBlock',
'logger',
function(scope, cb) {
new Account(scope.db, scope.schema, scope.logger, cb);
},
],
transaction: [
'db',
'bus',
'ed',
'schema',
'genesisBlock',
'account',
'logger',
function(scope, cb) {
new Transaction(
scope.db,
scope.ed,
scope.schema,
scope.genesisBlock,
scope.account,
scope.logger,
cb
);
},
],
block: [
'db',
'bus',
'ed',
'schema',
'genesisBlock',
'account',
'transaction',
function(scope, cb) {
new Block(scope.ed, scope.schema, scope.transaction, cb);
},
],
peers: [
'logger',
function(scope, cb) {
new Peers(scope.logger, cb);
},
],
},
cb
);
},
],
modules: [
'network',
'webSocket',
'config',
'logger',
'bus',
'sequence',
'balancesSequence',
'db',
'logic',
'cache',
/**
* Description of the function.
*
* @func modules[12]
* @param {Object} scope
* @param {function} cb - Callback function
*/
function(scope, cb) {
var tasks = {};
Object.keys(config.modules).forEach(name => {
tasks[name] = function(cb) {
var d = require('domain').create();
d.on('error', err => {
scope.logger.fatal(`Domain ${name}`, {
message: err.message,
stack: err.stack,
});
});
d.run(() => {
logger.debug('Loading module', name);
// eslint-disable-next-line import/no-dynamic-require
var Klass = require(config.modules[name]);
var obj = new Klass(cb, scope);
modules.push(obj);
});
};
});
async.parallel(tasks, (err, results) => {
cb(err, results);
});
},
],
ready: [
'swagger',
'modules',
'bus',
'logic',
/**
* Description of the function.
*
* @func ready[4]
* @memberof! app
* @param {Object} scope
* @param {function} cb - Callback function
* @todo Add description for the function and its params
*/
function(scope, cb) {
scope.modules.swagger = scope.swagger;
// Fire onBind event in every module
scope.bus.message('bind', scope.modules);
scope.logic.peers.bindModules(scope.modules);
cb();
},
],
listenWebSocket: [
'ready',
/**
* Description of the function.
*
* @func api[1]
* @param {Object} scope
* @param {function} cb - Callback function
*/
function(scope, cb) {
new wsTransport(scope.modules.transport);
cb();
},
],
listenHttp: [
'ready',
/**
* Description of the function.
*
* @func listen[1]
* @memberof! app
* @param {Object} scope
* @param {function} cb - Callback function
*/
function(scope, cb) {
scope.network.server.listen(
scope.config.httpPort,
scope.config.address,
err => {
scope.logger.info(
`Lisk started: ${scope.config.address}:${scope.config.httpPort}`
);
if (!err) {
if (scope.config.api.ssl.enabled) {
scope.network.https.listen(
scope.config.api.ssl.options.port,
scope.config.api.ssl.options.address,
err => {
scope.logger.info(
`Lisk https started: ${
scope.config.api.ssl.options.address
}:${scope.config.api.ssl.options.port}`
);
cb(err, scope.network);
}
);
} else {
cb(null, scope.network);
}
} else {
cb(err, scope.network);
}
}
);
},
],
},
(err, scope) => {
// Receives a 'cleanup' signal and cleans all modules
process.once('cleanup', error => {
if (error) {
scope.logger.fatal(error.toString());
}
scope.logger.info('Cleaning up...');
scope.socketCluster.removeAllListeners('fail');
scope.socketCluster.destroy();
async.eachSeries(
modules,
(module, cb) => {
if (typeof module.cleanup === 'function') {
module.cleanup(cb);
} else {
setImmediate(cb);
}
},
err => {
if (err) {
scope.logger.error(err);
} else {
scope.logger.info('Cleaned up successfully');
}
process.exit(1);
}
);
});
process.once('SIGTERM', () => {
process.emit('cleanup');
});
process.once('exit', () => {
process.emit('cleanup');
});
process.once('SIGINT', () => {
process.emit('cleanup');
});
if (err) {
logger.fatal(err);
process.emit('cleanup');
} else {
scope.logger.info('Modules ready and launched');
}
}
);
});
process.on('uncaughtException', err => {
// Handle error safely
logger.fatal('System error', { message: err.message, stack: err.stack });
process.emit('cleanup');
});