forked from Ebookcoin/ebookcoin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
475 lines (411 loc) · 12.1 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
var program = require('commander');
var packageJson = require('./package.json');
var Logger = require('./logger.js');
var appConfig = require("./config.json");
var genesisblock = require('./genesisBlock.json');
var async = require('async');
var extend = require('extend');
var path = require('path');
var https = require('https');
var fs = require('fs');
var z_schema = require('z-schema');
var util = require('util');
var Sequence = require('./helpers/sequence.js');
process.stdin.resume();
var versionBuild = fs.readFileSync(path.join(__dirname, 'build'), 'utf8');
program
.version(packageJson.version)
.option('-c, --config <path>', 'Config file path')
.option('-p, --port <port>', 'Listening port number')
.option('-a, --address <ip>', 'Listening host name or ip')
.option('-b, --blockchain <path>', 'Blockchain db path')
.option('-x, --peers [peers...]', 'Peers list')
.option('-l, --log <level>', 'Log level')
.parse(process.argv);
if (typeof gc !== 'undefined') {
setInterval(function () {
gc();
}, 60000);
}
if (program.config) {
appConfig = require(path.resolve(process.cwd(), program.config));
}
if (program.port) {
appConfig.port = program.port;
}
if (program.address) {
appConfig.address = program.address;
}
if (program.peers) {
if (typeof program.peers === 'string') {
appConfig.peers.list = program.peers.split(',').map(function (peer) {
peer = peer.split(":");
return {
ip: peer.shift(),
port: peer.shift() || appConfig.port
};
});
} else {
appConfig.peers.list = [];
}
}
if (program.log) {
appConfig.consoleLogLevel = program.log;
}
process.on('uncaughtException', function (err) {
// handle the error safely
logger.fatal('System error', { message: err.message, stack: err.stack });
process.emit('cleanup');
});
var config = {
"db": program.blockchain || "./blockchain.db",
"modules": {
"server": "./modules/server.js",
"accounts": "./modules/accounts.js",
"transactions": "./modules/transactions.js",
"blocks": "./modules/blocks.js",
"signatures": "./modules/signatures.js",
"transport": "./modules/transport.js",
"loader": "./modules/loader.js",
"system": "./modules/system.js",
"peer": "./modules/peer.js",
"delegates": "./modules/delegates.js",
"round": "./modules/round.js",
"contacts": "./modules/contacts.js",
"multisignatures": "./modules/multisignatures.js",
"dapps": "./modules/dapps.js",
"sia": "./modules/sia.js",
"crypto": "./modules/crypto.js",
"sql": "./modules/sql.js"
}
};
var logger = new Logger({echo: appConfig.consoleLogLevel, errorLevel: appConfig.fileLogLevel});
var d = require('domain').create();
d.on('error', function (err) {
logger.fatal('Domain master', { message: err.message, stack: err.stack });
process.exit(0);
});
d.run(function () {
var modules = [];
async.auto({
config: function (cb) {
if (appConfig.dapp.masterrequired && !appConfig.dapp.masterpassword) {
var randomstring = require("randomstring");
appConfig.dapp.masterpassword = randomstring.generate({
length: 12,
readable: true,
charset: 'alphanumeric'
});
fs.writeFile("./config.json", JSON.stringify(appConfig, null, 4), "utf8", function (err) {
cb(err, appConfig);
});
} else {
cb(null, appConfig);
}
},
logger: function (cb) {
cb(null, logger);
},
build: function (cb) {
cb(null, versionBuild);
},
genesisblock: function (cb) {
cb(null, {
block: genesisblock
});
},
public: function (cb) {
cb(null, path.join(__dirname, 'public'));
},
scheme: function (cb) {
z_schema.registerFormat("hex", function (str) {
try {
new Buffer(str, "hex");
} catch (e) {
return false;
}
return true;
});
z_schema.registerFormat('publicKey', function (str) {
if (str.length === 0) {
return true;
}
try {
var publicKey = new Buffer(str, "hex");
return publicKey.length == 32;
} catch (e) {
return false;
}
});
z_schema.registerFormat('splitarray', function (str) {
try {
var a = str.split(',');
if (a.length > 0 && a.length <= 1000) {
return true;
} else {
return false;
}
} catch (e) {
return false;
}
});
z_schema.registerFormat('signature', function (str) {
if (str.length === 0) {
return true;
}
try {
var signature = new Buffer(str, "hex");
return signature.length == 64;
} catch (e) {
return false;
}
});
z_schema.registerFormat('listQuery', function (obj) {
obj.limit = 100;
return true;
});
z_schema.registerFormat('listDelegates', function (obj) {
obj.limit = 101;
return true;
});
z_schema.registerFormat('checkInt', function (value) {
if (isNaN(value) || parseInt(value) != value || isNaN(parseInt(value, 10))) {
return false;
}
value = parseInt(value);
return true;
});
z_schema.registerFormat('ip', function (value) {
});
cb(null, new z_schema());
},
network: ['config', function (cb, scope) {
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
if (scope.config.ssl.enabled) {
var privateKey = fs.readFileSync(scope.config.ssl.options.key);
var certificate = fs.readFileSync(scope.config.ssl.options.cert);
var https = require('https').createServer({
key: privateKey,
cert: certificate
}, app);
var https_io = require('socket.io')(https);
}
cb(null, {
express: express,
app: app,
server: server,
io: io,
https: https,
https_io: https_io
});
}],
dbSequence: ["logger", function (cb, scope) {
var sequence = new Sequence({
onWarning: function (current, limit) {
scope.logger.warn("DB queue", current)
}
});
cb(null, sequence);
}],
sequence: ["logger", function (cb, scope) {
var sequence = new Sequence({
onWarning: function (current, limit) {
scope.logger.warn("Main queue", current)
}
});
cb(null, sequence);
}],
balancesSequence: ["logger", function (cb, scope) {
var sequence = new Sequence({
onWarning: function (current, limit) {
scope.logger.warn("Balance queue", current)
}
});
cb(null, sequence);
}],
connect: ['config', 'public', 'genesisblock', 'logger', 'build', 'network', function (cb, scope) {
var path = require('path');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var requestSanitizer = require('./helpers/request-sanitizer');
var queryParser = require('express-query-int');
scope.network.app.engine('html', require('ejs').renderFile);
scope.network.app.use(require('express-domain-middleware'));
scope.network.app.set('view engine', 'ejs');
scope.network.app.set('views', path.join(__dirname, 'public'));
scope.network.app.use(scope.network.express.static(path.join(__dirname, 'public')));
scope.network.app.use(bodyParser.urlencoded({extended: true, parameterLimit: 5000}));
scope.network.app.use(bodyParser.json());
scope.network.app.use(methodOverride());
var ignore = ['id', 'name', 'lastBlockId', 'blockId', 'username', 'transactionId', 'address', 'recipientId', 'senderId', 'senderUsername', 'recipientUsername', 'previousBlock'];
scope.network.app.use(queryParser({
parser: function (value, radix, name) {
if (ignore.indexOf(name) >= 0) {
return value;
}
if (isNaN(value) || parseInt(value) != value || isNaN(parseInt(value, radix))) {
return value;
}
return parseInt(value);
}
}));
scope.network.app.use(require('./helpers/zscheme-express.js')(scope.scheme));
scope.network.app.use(function (req, res, next) {
var parts = req.url.split('/');
var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
if (parts.length > 1) {
if (parts[1] == 'api') {
if (scope.config.api.access.whiteList.length > 0) {
if (scope.config.api.access.whiteList.indexOf(ip) < 0) {
res.sendStatus(403);
} else {
next();
}
} else {
next();
}
} else if (parts[1] == 'peer') {
if (scope.config.peers.blackList.length > 0) {
if (scope.config.peers.blackList.indexOf(ip) >= 0) {
res.sendStatus(403);
} else {
next();
}
} else {
next();
}
} else {
next();
}
} else {
next();
}
});
scope.network.server.listen(scope.config.port, scope.config.address, function (err) {
scope.logger.log("Ebookcoin started: " + scope.config.address + ":" + scope.config.port);
if (!err) {
if (scope.config.ssl.enabled) {
scope.network.https.listen(scope.config.ssl.options.port, scope.config.ssl.options.address, function (err) {
scope.logger.log("Ebookcoin https started: " + scope.config.ssl.options.address + ":" + scope.config.ssl.options.port);
cb(err, scope.network);
});
} else {
cb(null, scope.network);
}
} else {
cb(err, scope.network);
}
});
}],
bus: function (cb) {
var changeCase = require('change-case');
var bus = function () {
this.message = function () {
var args = [];
Array.prototype.push.apply(args, arguments);
var topic = args.shift();
modules.forEach(function (module) {
var eventName = 'on' + changeCase.pascalCase(topic);
if (typeof(module[eventName]) == 'function') {
module[eventName].apply(module[eventName], args);
}
})
}
}
cb(null, new bus)
},
dbLite: function (cb) {
var dbLite = require('./helpers/dbLite.js');
dbLite.connect(config.db, cb);
},
logic: ['dbLite', 'bus', 'scheme', 'genesisblock', function (cb, scope) {
var Transaction = require('./logic/transaction.js');
var Block = require('./logic/block.js');
var Account = require('./logic/account.js');
async.auto({
bus: function (cb) {
cb(null, scope.bus);
},
dbLite: function (cb) {
cb(null, scope.dbLite);
},
scheme: function (cb) {
cb(null, scope.scheme);
},
genesisblock: function (cb) {
cb(null, {
block: genesisblock
});
},
account: ["dbLite", "bus", "scheme", 'genesisblock', function (cb, scope) {
new Account(scope, cb);
}],
transaction: ["dbLite", "bus", "scheme", 'genesisblock', "account", function (cb, scope) {
new Transaction(scope, cb);
}],
block: ["dbLite", "bus", "scheme", 'genesisblock', "account", "transaction", function (cb, scope) {
new Block(scope, cb);
}]
}, cb);
}],
modules: ['network', 'connect', 'config', 'logger', 'bus', 'sequence', 'dbSequence', 'balancesSequence', 'dbLite', 'logic', function (cb, scope) {
var tasks = {};
Object.keys(config.modules).forEach(function (name) {
tasks[name] = function (cb) {
var d = require('domain').create();
d.on('error', function (err) {
scope.logger.fatal('Domain ' + name, {message: err.message, stack: err.stack});
});
d.run(function () {
logger.debug('Loading module', name)
var Klass = require(config.modules[name]);
var obj = new Klass(cb, scope)
modules.push(obj);
});
}
});
async.parallel(tasks, function (err, results) {
cb(err, results);
});
}],
ready: ['modules', 'bus', function (cb, scope) {
scope.bus.message("bind", scope.modules);
cb();
}]
}, function (err, scope) {
if (err) {
logger.fatal(err)
} else {
scope.logger.info("Modules ready and launched");
process.once('cleanup', function () {
scope.logger.info("Cleaning up...");
async.eachSeries(modules, function (module, cb) {
if (typeof(module.cleanup) == 'function'){
module.cleanup(cb);
}else{
setImmediate(cb);
}
}, function (err) {
if (err) {
scope.logger.error(err);
} else {
scope.logger.info("Cleaned up successfully");
}
process.exit(1);
});
});
process.once('SIGTERM', function () {
process.emit('cleanup');
})
process.once('exit', function () {
process.emit('cleanup');
});
process.once('SIGINT', function () {
process.emit('cleanup');
});
}
});
});