forked from OriginTrail/dkg-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathot-node.js
More file actions
724 lines (639 loc) · 31.3 KB
/
ot-node.js
File metadata and controls
724 lines (639 loc) · 31.3 KB
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
require('dotenv').config();
if (!process.env.NODE_ENV) {
// Environment not set. Use the production.
process.env.NODE_ENV = 'testnet';
}
const HttpNetwork = require('./modules/network/http/http-network');
const Kademlia = require('./modules/network/kademlia/kademlia');
const Transport = require('./modules/network/transport');
const KademliaUtilities = require('./modules/network/kademlia/kademlia-utils');
const Utilities = require('./modules/Utilities');
const GraphStorage = require('./modules/Database/GraphStorage');
const Blockchain = require('./modules/Blockchain');
const BlockchainPluginService = require('./modules/Blockchain/plugin/blockchain-plugin-service');
const fs = require('fs');
const path = require('path');
const models = require('./models');
const SchemaValidator = require('./modules/validator/schema-validator');
const GS1Utilities = require('./modules/importer/gs1-utilities');
const WOTImporter = require('./modules/importer/wot-importer');
const EpcisOtJsonTranspiler = require('./modules/transpiler/epcis/epcis-otjson-transpiler');
const WotOtJsonTranspiler = require('./modules/transpiler/wot/wot-otjson-transpiler');
const RemoteControl = require('./modules/RemoteControl');
const rc = require('rc');
const uuidv4 = require('uuid/v4');
const awilix = require('awilix');
const homedir = require('os').homedir();
const argv = require('minimist')(process.argv.slice(2));
const Graph = require('./modules/Graph');
const Product = require('./modules/Product');
const constants = require('./modules/constants');
const EventEmitter = require('./modules/EventEmitter');
const DVService = require('./modules/DVService');
const MinerService = require('./modules/service/miner-service');
const ApprovalService = require('./modules/service/approval-service');
const ChallengeService = require('./modules/service/challenge-service');
const ProfileService = require('./modules/service/profile-service');
const ReplicationService = require('./modules/service/replication-service');
const APIUtilities = require('./modules/api-utilities');
const RestApiController = require('./modules/service/rest-api-controller');
const M1PayoutAllMigration = require('./modules/migration/m1-payout-all-migration');
const M2SequelizeMetaMigration = require('./modules/migration/m2-sequelize-meta-migration');
const M3NetowrkIdentityMigration = require('./modules/migration/m3-network-identity-migration');
const M4ArangoMigration = require('./modules/migration/m4-arango-migration');
const M5ArangoPasswordMigration = require('./modules/migration/m5-arango-password-migration');
const M7ArangoDatasetSignatureMigration = require('./modules/migration/m7-arango-dataset-signature-migration');
const M8MissedOfferCheckMigration = require('./modules/migration/m8-missed-offer-check-migration');
const ImportWorkerController = require('./modules/worker/import-worker-controller');
const ImportService = require('./modules/service/import-service');
const OtNodeClient = require('./modules/service/ot-node-client');
const PermissionedDataService = require('./modules/service/permissioned-data-service');
const RestoreService = require('./scripts/restore');
const { execSync, fork } = require('child_process');
const semver = require('semver');
const pjson = require('./package.json');
const configjson = require('./config/config.json');
const log = require('./modules/logger');
global.__basedir = __dirname;
let context;
const defaultConfig = Utilities.copyObject(configjson[
process.env.NODE_ENV &&
['development', 'testnet', 'mainnet'].indexOf(process.env.NODE_ENV) >= 0 ?
process.env.NODE_ENV : 'development']);
let config;
try {
// Load config.
config = rc(pjson.name, defaultConfig);
if (argv.configDir) {
config.appDataPath = argv.configDir;
models.sequelize.options.storage = path.join(config.appDataPath, 'system.db');
} else {
config.appDataPath = path.join(
homedir,
`.${pjson.name}rc`,
process.env.NODE_ENV,
);
}
} catch (error) {
console.error(`Failed to read configuration. ${error}.`);
console.error(error.stack);
process.abort();
}
process.on('unhandledRejection', (reason, p) => {
if (reason.message.startsWith('Invalid JSON RPC response')) {
return;
}
log.error(`Unhandled Rejection:\n${reason.stack}`);
});
process.on('uncaughtException', (err) => {
if (process.env.NODE_ENV === 'development') {
log.error(`Caught exception: ${err}.\n ${err.stack}`);
process.exit(1);
}
log.error(`Caught exception: ${err}.\n ${err.stack}`);
});
process.on('warning', (warning) => {
log.warn(warning.name);
log.warn(warning.message);
log.warn(warning.stack);
});
process.on('exit', (code) => {
switch (code) {
case 0:
log.debug(`Normal exiting with code: ${code}`);
break;
case 4:
log.trace('Exiting because of update.');
break;
default:
log.error(`Whoops, terminating with code: ${code}`);
break;
}
});
process.on('SIGINT', () => {
log.important('SIGINT caught. Exiting...');
process.exit(0);
});
/**
* Main node object
*/
class OTNode {
/**
* OriginTrail node system bootstrap function
*/
async bootstrap() {
try {
// check if all dependencies are installed
await Utilities.checkInstalledDependencies();
log.info('npm modules dependencies check done');
// Checking root folder structure
Utilities.checkOtNodeDirStructure();
log.info('ot-node folder structure check done');
} catch (err) {
console.log(err);
process.exit(1);
}
log.important(`Running in ${process.env.NODE_ENV} environment.`);
await this._runNetworkIdentityMigration(config);
// Seal config in order to prevent adding properties.
// Allow identity to be added. Continuity.
config.identity = '';
config.erc725Identity = '';
config.publicKeyData = {};
const appState = {};
if (config.is_bootstrap_node) {
await this.startBootstrapNode({ appState });
return;
}
// check if ArangoDB service is running at all
if (config.database.provider === 'arangodb') {
try {
if (process.env.OT_NODE_DISTRIBUTION === 'docker'
&& (''.localeCompare(config.database.password) === 0
|| 'root'.localeCompare(config.database.password) === 0)) {
await this._runArangoPasswordMigration(config);
}
// get password for database
const databasePasswordFilePath = path
.join(config.appDataPath, config.database.password_file_name);
if (fs.existsSync(databasePasswordFilePath)) {
log.info('Using existing graph database password.');
config.database.password = fs.readFileSync(databasePasswordFilePath).toString();
} else {
log.notify('================================================================');
log.notify(' Using default database password for access ');
log.notify('================================================================');
}
const { version } = await Utilities.getArangoDbVersion(config);
log.info(`Arango server version ${version} is up and running`);
if (semver.lt(version, '3.5.0')) {
if (process.env.OT_NODE_DISTRIBUTION === 'docker'
&& config.autoUpdater.enabled) {
log.info('Your Arango version is lower than required. Starting upgrade...');
await this._runArangoMigration(config);
const { version } = await Utilities.getArangoDbVersion(config);
log.info(`Arango server is updated to version ${version}.`);
} else {
log.error('Arango version too old! Please update to version 3.5.0 or newer');
process.exit(1);
}
}
} catch (err) {
log.error('Please make sure Arango server is up and running');
console.log(err);
process.exit(1);
}
}
this._checkRestoreRequestStatus(config);
// Checking if selected graph database exists
try {
await Utilities.checkDoesStorageDbExists(config);
log.info('Storage database check done');
} catch (err) {
console.log(err);
process.exit(1);
}
Object.seal(config);
// Create the container and set the injectionMode to PROXY (which is also the default).
const container = awilix.createContainer({
injectionMode: awilix.InjectionMode.PROXY,
});
context = container.cradle;
container.loadModules(['modules/command/**/*.js', 'modules/controller/**/*.js', 'modules/service/**/*.js', 'modules/Blockchain/plugin/hyperledger/*.js', 'modules/migration/*.js'], {
formatName: 'camelCase',
resolverOptions: {
lifetime: awilix.Lifetime.SINGLETON,
register: awilix.asClass,
},
});
container.register({
httpNetwork: awilix.asClass(HttpNetwork).singleton(),
emitter: awilix.asClass(EventEmitter).singleton(),
kademlia: awilix.asClass(Kademlia).singleton(),
graph: awilix.asClass(Graph).singleton(),
product: awilix.asClass(Product).singleton(),
dvService: awilix.asClass(DVService).singleton(),
profileService: awilix.asClass(ProfileService).singleton(),
approvalService: awilix.asClass(ApprovalService).singleton(),
config: awilix.asValue(config),
appState: awilix.asValue(appState),
schemaValidator: awilix.asClass(SchemaValidator).singleton(),
blockchain: awilix.asClass(Blockchain).singleton(),
blockchainPluginService: awilix.asClass(BlockchainPluginService).singleton(),
gs1Utilities: awilix.asClass(GS1Utilities).singleton(),
wotImporter: awilix.asClass(WOTImporter).singleton(),
epcisOtJsonTranspiler: awilix.asClass(EpcisOtJsonTranspiler).singleton(),
wotOtJsonTranspiler: awilix.asClass(WotOtJsonTranspiler).singleton(),
graphStorage: awilix.asValue(new GraphStorage(config.database, log)),
remoteControl: awilix.asClass(RemoteControl).singleton(),
logger: awilix.asValue(log),
kademliaUtilities: awilix.asClass(KademliaUtilities).singleton(),
transport: awilix.asValue(Transport()),
apiUtilities: awilix.asClass(APIUtilities).singleton(),
minerService: awilix.asClass(MinerService).singleton(),
replicationService: awilix.asClass(ReplicationService).singleton(),
restApiController: awilix.asClass(RestApiController).singleton(),
challengeService: awilix.asClass(ChallengeService).singleton(),
importWorkerController: awilix.asClass(ImportWorkerController).singleton(),
importService: awilix.asClass(ImportService).singleton(),
permissionedDataService: awilix.asClass(PermissionedDataService).singleton(),
otNodeClient: awilix.asClass(OtNodeClient).singleton(),
});
const blockchain = container.resolve('blockchain');
await blockchain.loadContracts();
const emitter = container.resolve('emitter');
const remoteControl = container.resolve('remoteControl');
const profileService = container.resolve('profileService');
const replicationService = container.resolve('replicationService');
emitter.initialize();
// Connecting to graph database
const graphStorage = container.resolve('graphStorage');
try {
await graphStorage.connect();
log.info(`Connected to graph database: ${graphStorage.identify()}`);
await this._runArangoDatasetSignatureMigration(config, graphStorage);
} catch (err) {
log.error(`Failed to connect to the graph database: ${graphStorage.identify()}`);
process.exit(1);
}
const houstonPasswordFilePath = path
.join(config.appDataPath, config.houston_password_file_name);
if (fs.existsSync(houstonPasswordFilePath)) {
log.info('Using existing houston password.');
config.houston_password = fs.readFileSync(houstonPasswordFilePath).toString();
} else {
config.houston_password = uuidv4();
fs.writeFileSync(houstonPasswordFilePath, config.houston_password);
log.notify('================================================================');
log.notify(' Houston password generated and stored in file ');
log.notify('================================================================');
}
if (config.high_availability.enabled) {
const highAvailabilityService = container.resolve('highAvailabilityService');
await highAvailabilityService.startHighAvailabilityNode();
}
// Starting the kademlia
const transport = container.resolve('transport');
await transport.init(container.cradle);
// Starting event listener on Blockchain
this.listenBlockchainEvents(blockchain);
try {
await profileService.initProfile();
await this._runPayoutMigration(blockchain, config, profileService);
} catch (e) {
log.error('Failed to create profile');
console.log(e);
process.exit(1);
}
await profileService.validateAndUpdateProfiles();
await this._runArangoRemoveUnnecessaryEncryptionDataMigration(
config,
graphStorage,
blockchain,
profileService,
);
await transport.start();
// Initialize bugsnag notification service
const errorNotificationService = container.resolve('errorNotificationService');
await errorNotificationService.initialize();
// Initialise API
const restApiController = container.resolve('restApiController');
try {
await restApiController.startRPC();
} catch (err) {
log.error('Failed to start RPC server');
console.log(err);
process.exit(1);
}
if (config.remote_control_enabled) {
log.info(`Remote control enabled and listening on port ${config.node_remote_control_port}`);
await remoteControl.connect();
}
const commandExecutor = container.resolve('commandExecutor');
await commandExecutor.init();
await commandExecutor.replay();
await commandExecutor.start();
await this._runOfferCheckMigration(blockchain, config, profileService, commandExecutor);
appState.started = true;
}
/**
* Backs up network identity files if they are from the old network version
* @param config
* @returns {Promise<void>}
* @private
*/
async _runNetworkIdentityMigration(config) {
const migrationsStartedMills = Date.now();
const migration = new M3NetowrkIdentityMigration({ logger: log, config });
try {
await migration.run();
} catch (e) {
log.error(`Failed to run code migrations. Lasted ${Date.now() - migrationsStartedMills} millisecond(s). ${e.message}`);
console.log(e);
process.exit(1);
}
}
async _runArangoMigration(config) {
const migrationsStartedMills = Date.now();
const m1PayoutAllMigrationFilename = '4_m4ArangoMigrationFile';
const migrationDir = path.join(config.appDataPath, 'migrations');
const migrationFilePath = path.join(migrationDir, m1PayoutAllMigrationFilename);
if (!fs.existsSync(migrationFilePath)) {
const migration = new M4ArangoMigration({ logger: log, config });
try {
log.info('Initializing Arango migration...');
await migration.run();
log.warn(`One-time Arango migration completed. Lasted ${Date.now() - migrationsStartedMills} millisecond(s)`);
await Utilities.writeContentsToFile(migrationDir, m1PayoutAllMigrationFilename, 'PROCESSED');
} catch (e) {
log.error(`Failed to run code migrations. Lasted ${Date.now() - migrationsStartedMills} millisecond(s). ${e.message}`);
console.log(e);
process.exit(1);
}
}
}
async _runArangoDatasetSignatureMigration(config, graphStorage) {
const migrationsStartedMills = Date.now();
const m7ArangoSignatureMigrationFilename = '7_m7ArangoDatasetSignatureMigrationFile';
const migrationDir = path.join(config.appDataPath, 'migrations');
const migrationFilePath = path.join(migrationDir, m7ArangoSignatureMigrationFilename);
if (!fs.existsSync(migrationFilePath)) {
const migration = new M7ArangoDatasetSignatureMigration({
config,
graphStorage,
});
try {
log.info('Initializing Arango dataset signature migration...');
await migration.run();
log.warn(`One-time Arango dataset signature migration completed. Lasted ${Date.now() - migrationsStartedMills} millisecond(s)`);
await Utilities.writeContentsToFile(migrationDir, m7ArangoSignatureMigrationFilename, 'PROCESSED');
} catch (e) {
log.error(`Failed to run code migrations. Lasted ${Date.now() - migrationsStartedMills} millisecond(s). ${e.message}`);
process.exit(1);
}
}
}
async _runArangoRemoveUnnecessaryEncryptionDataMigration(
config,
graphStorage,
blockchain,
profileService,
) {
const migrationsStartedMills = Date.now();
const m9ArangoEncryptionDataMigrationFilename = '9_m9ArangoRemoveUnnecessaryEncryptionDataMigrationFile';
const migrationDir = path.join(config.appDataPath, 'migrations');
const migrationFilePath = path.join(migrationDir, m9ArangoEncryptionDataMigrationFilename);
if (!fs.existsSync(migrationFilePath)) {
try {
log.info('Initializing Arango remove unnecessary encryption data migration...');
const allMyIdentities = {};
blockchain.getAllBlockchainIds()
.forEach(id => allMyIdentities[id] = profileService.getIdentity(id));
const bids = await models.bids.findAll({
attributes: ['data_set_id', 'offer_id', 'blockchain_id', 'status'],
where: {
status: { [models.Sequelize.Op.in]: ['CHOSEN', 'NOT_CHOSEN'] },
},
});
const forked = fork('modules/migration/m9-remove-unnecessary-encryption-data-worker.js');
forked.send(JSON.stringify({
database: config.database,
config,
allMyIdentities,
bids,
}));
forked.on('message', async (response) => {
if (response.error) {
log.error(`Failed to run code migrations. Lasted ${Date.now() - migrationsStartedMills} millisecond(s). ${response.error}`);
} else {
log.warn(`One-time Arango remove unnecessary encryption data migration completed. Lasted ${Date.now() - migrationsStartedMills} millisecond(s)`);
await Utilities.writeContentsToFile(migrationDir, m9ArangoEncryptionDataMigrationFilename, 'PROCESSED');
}
forked.kill();
});
} catch (e) {
log.error(`Failed to run code migrations. Lasted ${Date.now() - migrationsStartedMills} millisecond(s). ${e.message}`);
process.exit(1);
}
}
}
async _runArangoPasswordMigration(config) {
const migrationsStartedMills = Date.now();
const m5ArangoPasswordMigrationFilename = '5_m5ArangoPasswordMigrationFile';
const migrationDir = path.join(config.appDataPath, 'migrations');
const migrationFilePath = path.join(migrationDir, m5ArangoPasswordMigrationFilename);
if (!fs.existsSync(migrationFilePath)) {
const migration = new M5ArangoPasswordMigration({ log, config });
try {
log.info('Initializing Arango password migration...');
const result = await migration.run();
if (result === 0) {
log.notify(`One-time password migration completed. Lasted ${Date.now() - migrationsStartedMills} millisecond(s)`);
await Utilities.writeContentsToFile(migrationDir, m5ArangoPasswordMigrationFilename, 'PROCESSED');
} else {
log.error('One-time password migration failed. Defaulting to previous implementation');
}
} catch (e) {
log.error(`Failed to run code migrations. Lasted ${Date.now() - migrationsStartedMills} millisecond(s). ${e.message}`);
console.log(e);
process.exit(1);
}
}
}
/**
* Run one time payout migration
* @param blockchain
* @param config
* @param profileService
* @returns {Promise<void>}
* @private
*/
async _runPayoutMigration(blockchain, config, profileService) {
const migrationsStartedMills = Date.now();
log.info('Initializing payOut migration...');
const m1PayoutAllMigrationFilename = '1_m1PayoutAllMigrationFile';
const migrationDir = path.join(config.appDataPath, 'migrations');
const migrationFilePath = path.join(migrationDir, m1PayoutAllMigrationFilename);
if (!fs.existsSync(migrationFilePath)) {
const migration = new M1PayoutAllMigration({
logger: log, blockchain, config, profileService,
});
try {
await migration.run();
log.warn(`One-time payout migration completed. Lasted ${Date.now() - migrationsStartedMills} millisecond(s)`);
await Utilities.writeContentsToFile(migrationDir, m1PayoutAllMigrationFilename, 'PROCESSED');
} catch (e) {
log.error(`Failed to run code migrations. Lasted ${Date.now() - migrationsStartedMills} millisecond(s). ${e.message}`);
console.log(e);
process.exit(1);
}
}
}
/**
* Run offer check migration
* @param blockchain
* @param config
* @param profileService
* @param commandExecutor
* @returns {Promise<void>}
* @private
*/
async _runOfferCheckMigration(blockchain, config, profileService, commandExecutor) {
const migrationsStartedMills = Date.now();
log.info('Initializing missed offer check migration...');
const m8MissedOfferCheckMigrationFilename = '8_m8MissedOfferCheckMigrationFile';
const migrationDir = path.join(config.appDataPath, 'migrations');
const migrationFilePath = path.join(migrationDir, m8MissedOfferCheckMigrationFilename);
if (!fs.existsSync(migrationFilePath)) {
const migration = new M8MissedOfferCheckMigration({
logger: log, blockchain, config, profileService, commandExecutor,
});
try {
await migration.run();
log.warn(`One-time missed offer check migration completed. Lasted ${Date.now() - migrationsStartedMills} millisecond(s)`);
await Utilities.writeContentsToFile(migrationDir, m8MissedOfferCheckMigrationFilename, 'PROCESSED');
} catch (e) {
log.error(`Failed to run code migrations. Lasted ${Date.now() - migrationsStartedMills} millisecond(s). ${e.message}`);
console.log(e);
process.exit(1);
}
}
}
_checkRestoreRequestStatus(config) {
const restoreFile = path.join(config.appDataPath, 'restore_request_status.txt');
if (fs.existsSync(restoreFile)) {
log.info('Detected restore request file, checking status.');
const restoreStatus = fs.readFileSync(restoreFile).toString();
switch (restoreStatus) {
case 'COMPLETED':
log.info('Restore status is completed, continuing with node startup.');
break;
case 'FAILED':
log.warn('Restore status is failed, cancelling node startup');
if (fs.existsSync(path.join(config.appDataPath, 'restore_error_message.txt'))) {
log.warn(`Found error during restore procedure: \n${fs.readFileSync(path
.join(config.appDataPath, 'restore_error_message.txt')).toString()}`);
}
log.important('To start your node please fix the restoration error(s) or skip the restore process by deleting the restore request file.');
process.exit(1);
break;
case 'REQUESTED':
default:
log.info('Restore status is requested, starting restore process');
try {
const restorer = new RestoreService(log);
restorer.restore();
log.info('Successfully completed node restore, restarting to read restored files.');
fs.writeFileSync(restoreFile, 'COMPLETED');
// Exit with unexpected code, so that the node restarts
process.exit(2);
} catch (e) {
log.error(`Failed to execute node restore. Error: ${e.toString()}`);
fs.writeFileSync(path.join(config.appDataPath, 'restore_error_message.txt'), e.toString());
fs.writeFileSync(restoreFile, 'FAILED');
process.exit(1);
}
break;
}
}
}
/**
* Starts bootstrap node
* @return {Promise<void>}
*/
async startBootstrapNode({ appState }) {
const container = awilix.createContainer({
injectionMode: awilix.InjectionMode.PROXY,
});
container.loadModules(['modules/command/**/*.js', 'modules/controller/**/*.js', 'modules/service/**/*.js', 'modules/Blockchain/plugin/hyperledger/*.js', 'modules/migration/*.js'], {
formatName: 'camelCase',
resolverOptions: {
lifetime: awilix.Lifetime.SINGLETON,
register: awilix.asClass,
},
});
container.register({
emitter: awilix.asValue({}),
blockchain: awilix.asClass(Blockchain).singleton(),
blockchainPluginService: awilix.asClass(BlockchainPluginService).singleton(),
kademlia: awilix.asClass(Kademlia).singleton(),
dvService: awilix.asClass(DVService).singleton(),
config: awilix.asValue(config),
appState: awilix.asValue(appState),
remoteControl: awilix.asClass(RemoteControl).singleton(),
logger: awilix.asValue(log),
kademliaUtilities: awilix.asClass(KademliaUtilities).singleton(),
transport: awilix.asValue(Transport()),
apiUtilities: awilix.asClass(APIUtilities).singleton(),
restApiController: awilix.asClass(RestApiController).singleton(),
graphStorage: awilix.asValue(new GraphStorage(config.database, log)),
epcisOtJsonTranspiler: awilix.asClass(EpcisOtJsonTranspiler).singleton(),
wotOtJsonTranspiler: awilix.asClass(WotOtJsonTranspiler).singleton(),
schemaValidator: awilix.asClass(SchemaValidator).singleton(),
importService: awilix.asClass(ImportService).singleton(),
});
const transport = container.resolve('transport');
await transport.init(container.cradle);
await transport.start();
const restApiController = container.resolve('restApiController');
try {
await restApiController.startRPC();
} catch (err) {
log.error('Failed to start RPC server');
console.log(err);
process.exit(1);
}
}
/**
* Listen to all Bidding events
* @param blockchain
*/
listenBlockchainEvents(blockchain) {
log.info('Starting blockchain event listener');
const delay = 20000;
let working = false;
let deadline = Date.now();
setInterval(async () => {
if (!working && Date.now() > deadline) {
try {
working = true;
await blockchain.getAllPastEvents('HUB_CONTRACT');
await blockchain.getAllPastEvents('HOLDING_CONTRACT');
await blockchain.getAllPastEvents('PROFILE_CONTRACT');
await blockchain.getAllPastEvents('APPROVAL_CONTRACT');
await blockchain.getAllPastEvents('LITIGATION_CONTRACT');
await blockchain.getAllPastEvents('MARKETPLACE_CONTRACT');
await blockchain.getAllPastEvents('REPLACEMENT_CONTRACT');
await blockchain.getAllPastEvents('OLD_HOLDING_CONTRACT'); // TODO remove after successful migration
deadline = Date.now() + delay;
} catch (e) {
log.error(`Failed to get blockchain events. Error: ${e}`);
} finally {
working = false;
}
}
}, 5000);
}
}
log.info(' ██████╗ ████████╗███╗ ██╗ ██████╗ ██████╗ ███████╗');
log.info('██╔═══██╗╚══██╔══╝████╗ ██║██╔═══██╗██╔══██╗██╔════╝');
log.info('██║ ██║ ██║ ██╔██╗ ██║██║ ██║██║ ██║█████╗');
log.info('██║ ██║ ██║ ██║╚██╗██║██║ ██║██║ ██║██╔══╝');
log.info('╚██████╔╝ ██║ ██║ ╚████║╚██████╔╝██████╔╝███████╗');
log.info(' ╚═════╝ ╚═╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═════╝ ╚══════╝');
log.info('======================================================');
log.info(` OriginTrail Node v${pjson.version}`);
log.info('======================================================');
log.info('');
function main() {
const otNode = new OTNode();
otNode.bootstrap().then(() => {
log.info('OT Node started');
});
}
// Make sure the Sequelize meta table is migrated before running main.
if (process.env.DB_TYPE === constants.DB_TYPE.psql && process.env.NODE_ENV !== 'development') {
execSync('/etc/init.d/postgresql start');
}
const migrationSequelizeMeta = new M2SequelizeMetaMigration({ logger: log });
migrationSequelizeMeta.run().then(main);