-
-
Notifications
You must be signed in to change notification settings - Fork 189
/
Copy pathloader.js
941 lines (839 loc) · 27.6 KB
/
loader.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
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
'use strict';
var async = require('async');
var constants = require('../helpers/constants.js');
var jobsQueue = require('../helpers/jobsQueue.js');
var ip = require('neoip');
var sandboxHelper = require('../helpers/sandbox.js');
var schema = require('../schema/loader.js');
var sql = require('../sql/loader.js');
require('colors');
// Private fields
var modules, library, self, __private = {}, shared = {};
__private.loaded = false;
__private.isActive = false;
__private.lastBlock = null;
__private.genesisBlock = null;
__private.total = 0;
__private.blocksToSync = 0;
__private.syncIntervalId = null;
__private.syncInterval = 10000;
__private.retries = 5;
/**
* Initializes library with scope content.
* Calls private function initialize.
* @memberof module:loader
* @class
* @classdesc Main Loader methods.
* @param {function} cb - Callback function.
* @param {scope} scope - App instance.
* @return {setImmediateCallback} Callback function with `self` as data.
*/
// Constructor
function Loader (cb, scope) {
library = {
logger: scope.logger,
db: scope.db,
network: scope.network,
schema: scope.schema,
sequence: scope.sequence,
bus: scope.bus,
genesisblock: scope.genesisblock,
balancesSequence: scope.balancesSequence,
logic: {
transaction: scope.logic.transaction,
account: scope.logic.account,
peers: scope.logic.peers
},
config: {
loading: {
verifyOnLoading: scope.config.loading.verifyOnLoading,
snapshot: scope.config.loading.snapshot
}
}
};
self = this;
__private.initialize();
__private.genesisBlock = __private.lastBlock = library.genesisblock;
setImmediate(cb, null, self);
}
// Private methods
/**
* Sets private network object with height 0 and peers empty array.
* @private
*/
__private.initialize = function () {
__private.network = {
height: 0, // Network height
peers: [] // "Good" peers and with height close to network height
};
};
/**
* Cancels timers based on input parameter and private variable syncIntervalId
* or Sync trigger by sending a socket signal with 'loader/sync' and setting
* next sync with 1000 milliseconds.
* @private
* @implements {library.network.wsServer.emit}
* @implements {modules.blocks.lastBlock.get}
* @param {boolean} turnOn
* @emits loader/sync
*/
__private.syncTrigger = function (turnOn) {
if (turnOn === false && __private.syncIntervalId) {
library.logger.trace('Clearing sync interval');
clearTimeout(__private.syncIntervalId);
__private.syncIntervalId = null;
}
if (turnOn === true && !__private.syncIntervalId) {
library.logger.trace('Setting sync interval');
setImmediate(function nextSyncTrigger () {
library.logger.trace('Sync trigger');
library.network.wsServer.emit('loader/sync', {
blocks: __private.blocksToSync,
height: modules.blocks.lastBlock.get().height
});
__private.syncIntervalId = setTimeout(nextSyncTrigger, 1000);
});
}
};
/**
* Syncs timer trigger.
* @private
* @implements {modules.blocks.lastReceipt.get}
* @implements {modules.blocks.lastReceipt.isStale}
* @implements {Loader.syncing}
* @implements {library.sequence.add}
* @implements {async.retry}
* @implements {__private.initialize}
*/
__private.syncTimer = function () {
library.logger.trace('Setting sync timer');
function nextSync (cb) {
library.logger.trace('Sync timer trigger', { loaded: __private.loaded, syncing: self.syncing(), last_receipt: modules.blocks.lastReceipt.get() });
if (__private.loaded && !self.syncing() && modules.blocks.lastReceipt.isStale()) {
library.sequence.add(function (sequenceCb) {
async.retry(__private.retries, __private.sync, sequenceCb);
}, function (err) {
if (err) {
library.logger.error('Sync timer', err);
__private.initialize();
}
return setImmediate(cb);
});
} else {
return setImmediate(cb);
}
}
jobsQueue.register('loaderSyncTimer', nextSync, __private.syncInterval);
};
/**
* Gets a random peer and loads signatures calling the api.
* Processes each signature from peer.
* @private
* @implements {Loader.getNetwork}
* @implements {modules.transport.getFromPeer}
* @implements {library.schema.validate}
* @implements {library.sequence.add}
* @implements {async.eachSeries}
* @implements {modules.multisignatures.processSignature}
* @param {function} cb
* @return {setImmediateCallback} cb, err
*/
__private.loadSignatures = function (cb) {
async.waterfall([
function (waterCb) {
self.getNetwork(function (err, network) {
if (err) {
return setImmediate(waterCb, err);
} else {
var peer = network.peers[Math.floor(Math.random() * network.peers.length)];
return setImmediate(waterCb, null, peer);
}
});
},
function (peer, waterCb) {
library.logger.log('Loading signatures from: ' + peer.string);
modules.transport.getFromPeer(peer, {
api: '/signatures',
method: 'GET'
}, function (err, res) {
if (err) {
return setImmediate(waterCb, err);
} else {
library.schema.validate(res.body, schema.loadSignatures, function (err) {
return setImmediate(waterCb, err, res.body.signatures);
});
}
});
},
function (signatures, waterCb) {
library.sequence.add(function (cb) {
async.eachSeries(signatures, function (signature, eachSeriesCb) {
async.eachSeries(signature.signatures, function (s, eachSeriesCb) {
modules.multisignatures.processSignature({
signature: s,
transaction: signature.transaction
}, function (err) {
return setImmediate(eachSeriesCb);
});
}, eachSeriesCb);
}, cb);
}, waterCb);
}
], function (err) {
return setImmediate(cb, err);
});
};
/**
* Gets a random peer and loads transactions calling the api.
* Validates each transaction from peer and remove peer if invalid.
* Calls processUnconfirmedTransaction for each transaction.
* @private
* @implements {Loader.getNetwork}
* @implements {modules.transport.getFromPeer}
* @implements {library.schema.validate}
* @implements {async.eachSeries}
* @implements {library.logic.transaction.objectNormalize}
* @implements {modules.peers.remove}
* @implements {library.balancesSequence.add}
* @implements {modules.transactions.processUnconfirmedTransaction}
* @param {function} cb
* @return {setImmediateCallback} cb, err
* @todo missed error propagation when balancesSequence.add
*/
__private.loadTransactions = function (cb) {
async.waterfall([
function (waterCb) {
self.getNetwork(function (err, network) {
if (err) {
return setImmediate(waterCb, err);
} else {
var peer = network.peers[Math.floor(Math.random() * network.peers.length)];
return setImmediate(waterCb, null, peer);
}
});
},
function (peer, waterCb) {
library.logger.log('Loading transactions from: ' + peer.string);
modules.transport.getFromPeer(peer, {
api: '/transactions',
method: 'GET'
}, function (err, res) {
if (err) {
return setImmediate(waterCb, err);
}
library.schema.validate(res.body, schema.loadTransactions, function (err) {
if (err) {
return setImmediate(waterCb, err[0].message);
} else {
return setImmediate(waterCb, null, peer, res.body.transactions);
}
});
});
},
function (peer, transactions, waterCb) {
async.eachSeries(transactions, function (transaction, eachSeriesCb) {
var id = (transaction ? transactions.id : 'null');
try {
transaction = library.logic.transaction.objectNormalize(transaction);
} catch (e) {
library.logger.debug('Transaction normalization failed', { id: id, err: e.toString(), module: 'loader', tx: transaction });
library.logger.warn(['Transaction', id, 'is not valid, peer removed'].join(' '), peer.string);
modules.peers.remove(peer.ip, peer.port);
return setImmediate(eachSeriesCb, e);
}
return setImmediate(eachSeriesCb);
}, function (err) {
return setImmediate(waterCb, err, transactions);
});
},
function (transactions, waterCb) {
async.eachSeries(transactions, function (transaction, eachSeriesCb) {
library.balancesSequence.add(function (cb) {
transaction.bundled = true;
modules.transactions.processUnconfirmedTransaction(transaction, false, cb);
}, function (err) {
if (err) {
// TODO: Validate if must include error propagation.
library.logger.debug(err);
}
return setImmediate(eachSeriesCb);
});
}, waterCb);
}
], function (err) {
return setImmediate(cb, err);
});
};
/**
* Checks mem tables:
* - count blocks from `blocks` table
* - get genesis block from `blocks` table
* - count accounts from `mem_accounts` table by block id
* - get rounds from `mem_round`
* Matches genesis block with database.
* Verifies Snapshot mode.
* Recreates memory tables when necessary:
* - Calls logic.account to removeTables and createTables
* - Calls block to load block. When blockchain ready emits a bus message.
* Detects orphaned blocks in `mem_accounts` and gets delegates.
* Loads last block and emits a bus message blockchain is ready.
* @private
* @implements {library.db.task}
* @implements {modules.rounds.calc}
* @implements {library.bus.message}
* @implements {library.logic.account.removeTables}
* @implements {library.logic.account.createTables}
* @implements {async.until}
* @implements {modules.blocks.loadBlocksOffset}
* @implements {modules.blocks.deleteAfterBlock}
* @implements {modules.blocks.loadLastBlock}
* @emits exit
* @throws {string} When fails to match genesis block with database
*/
__private.loadBlockChain = function () {
var offset = 0, limit = Number(library.config.loading.loadPerIteration) || 1000;
var verify = Boolean(library.config.loading.verifyOnLoading);
function load (count) {
verify = true;
__private.total = count;
async.series({
removeTables: function (seriesCb) {
library.logic.account.removeTables(function (err) {
if (err) {
throw err;
} else {
return setImmediate(seriesCb);
}
});
},
createTables: function (seriesCb) {
library.logic.account.createTables(function (err) {
if (err) {
throw err;
} else {
return setImmediate(seriesCb);
}
});
},
loadBlocksOffset: function (seriesCb) {
async.until(
function (testCb) {
return testCb(null, count < offset);
}, function (cb) {
if (count > 1) {
library.logger.info('Rebuilding blockchain, current block height: ' + (offset + 1));
}
modules.blocks.process.loadBlocksOffset(limit, offset, verify, function (err, lastBlock) {
if (err) {
return setImmediate(cb, err);
}
offset = offset + limit;
__private.lastBlock = lastBlock;
return setImmediate(cb);
});
}, function (err) {
return setImmediate(seriesCb, err);
}
);
}
}, function (err) {
if (err) {
library.logger.error(err);
if (err.block) {
library.logger.error('Blockchain failed at: ' + err.block.height);
modules.blocks.chain.deleteAfterBlock(err.block.id, function (err, res) {
library.logger.error('Blockchain clipped');
library.bus.message('blockchainReady');
});
}
} else {
library.logger.info('Blockchain ready');
library.bus.message('blockchainReady');
}
});
}
function reload (count, message) {
if (message) {
library.logger.warn(message);
library.logger.warn('Recreating memory tables');
}
return load(count);
}
function checkMemTables (t) {
var promises = [
t.one(sql.countBlocks),
t.query(sql.getGenesisBlock),
t.one(sql.countMemAccounts),
t.query(sql.getMemRounds),
t.query(sql.countDuplicatedDelegates)
];
return t.batch(promises);
}
function matchGenesisBlock (row) {
if (row) {
var matched = (
row.id === __private.genesisBlock.block.id &&
row.payloadHash.toString('hex') === __private.genesisBlock.block.payloadHash &&
row.blockSignature.toString('hex') === __private.genesisBlock.block.blockSignature
);
if (matched) {
library.logger.info('Genesis block matched with database');
} else {
throw 'Failed to match genesis block with database';
}
}
}
function verifySnapshot (count, round) {
if (library.config.loading.snapshot !== undefined || library.config.loading.snapshot > 0) {
library.logger.info('Snapshot mode enabled');
if (isNaN(library.config.loading.snapshot) || library.config.loading.snapshot >= round) {
library.config.loading.snapshot = round;
if ((count === 1) || (count % constants.activeDelegates > 0)) {
library.config.loading.snapshot = (round > 1) ? (round - 1) : 1;
}
modules.rounds.setSnapshotRounds(library.config.loading.snapshot);
}
library.logger.info('Snapshotting to end of round: ' + library.config.loading.snapshot);
return true;
} else {
return false;
}
}
library.db.task(checkMemTables).then(function (results) {
var count = results[0].count;
library.logger.info('Blocks ' + count);
var round = modules.rounds.calc(count);
if (count === 1) {
return reload(count);
}
matchGenesisBlock(results[1][0]);
verify = verifySnapshot(count, round);
if (verify) {
return reload(count, 'Blocks verification enabled');
}
var missed = !(results[2].count);
if (missed) {
return reload(count, 'Detected missed blocks in mem_accounts');
}
var unapplied = results[3].filter(function (row) {
return (row.round !== String(round));
});
if (unapplied.length > 0) {
return reload(count, 'Detected unapplied rounds in mem_round');
}
var duplicatedDelegates = +results[4][0].count;
if (duplicatedDelegates > 0) {
library.logger.error('Delegates table corrupted with duplicated entries');
return process.emit('exit');
}
function updateMemAccounts (t) {
var promises = [
t.none(sql.updateMemAccounts),
t.query(sql.getOrphanedMemAccounts),
t.query(sql.getDelegates)
];
return t.batch(promises);
}
library.db.task(updateMemAccounts).then(function (results) {
if (results[1].length > 0) {
return reload(count, 'Detected orphaned blocks in mem_accounts');
}
if (results[2].length === 0) {
return reload(count, 'No delegates found');
}
modules.blocks.utils.loadLastBlock(function (err, block) {
if (err) {
return reload(count, err || 'Failed to load last block');
} else {
__private.lastBlock = block;
library.logger.info('Blockchain ready');
library.bus.message('blockchainReady');
}
});
});
}).catch(function (err) {
library.logger.error(err.stack || err);
return process.emit('exit');
});
};
/**
* Loads blocks from network.
* @private
* @implements {Loader.getNetwork}
* @implements {async.whilst}
* @implements {modules.blocks.lastBlock.get}
* @implements {modules.blocks.loadBlocksFromPeer}
* @implements {modules.blocks.getCommonBlock}
* @param {function} cb
* @return {setImmediateCallback} cb, err
*/
__private.loadBlocksFromNetwork = function (cb) {
var errorCount = 0;
var loaded = false;
self.getNetwork(function (err, network) {
if (err) {
return setImmediate(cb, err);
} else {
async.whilst(
function (testCb) {
return testCb(null, !loaded && errorCount < 5);
},
function (next) {
var peer = network.peers[Math.floor(Math.random() * network.peers.length)];
var lastBlock = modules.blocks.lastBlock.get();
function loadBlocks () {
__private.blocksToSync = peer.height;
modules.blocks.process.loadBlocksFromPeer(peer, function (err, lastValidBlock) {
if (err) {
library.logger.error(err.toString());
library.logger.error('Failed to load blocks from: ' + peer.string);
errorCount += 1;
}
loaded = lastValidBlock.id === lastBlock.id;
lastValidBlock = lastBlock = null;
next();
});
}
function getCommonBlock (cb) {
library.logger.info('Looking for common block with: ' + peer.string);
modules.blocks.process.getCommonBlock(peer, lastBlock.height, function (err, commonBlock) {
if (!commonBlock) {
if (err) { library.logger.error(err.toString()); }
library.logger.error('Failed to find common block with: ' + peer.string);
errorCount += 1;
return next();
} else {
library.logger.info(['Found common block:', commonBlock.id, 'with:', peer.string].join(' '));
return setImmediate(cb);
}
});
}
if (lastBlock.height === 1) {
loadBlocks();
} else {
getCommonBlock(loadBlocks);
}
},
function (err) {
if (err) {
library.logger.error('Failed to load blocks from network', err);
return setImmediate(cb, err);
} else {
return setImmediate(cb);
}
}
);
}
});
};
/**
* - Undoes unconfirmed transactions.
* - Establish broadhash consensus
* - Syncs: loadBlocksFromNetwork, updateSystem
* - Establish broadhash consensus
* - Applies unconfirmed transactions
* @private
* @implements {async.series}
* @implements {modules.transactions.undoUnconfirmedList}
* @implements {modules.transport.getPeers}
* @implements {__private.loadBlocksFromNetwork}
* @implements {modules.system.update}
* @implements {modules.transactions.applyUnconfirmedList}
* @param {function} cb
* @todo check err actions
*/
__private.sync = function (cb) {
library.logger.info('Starting sync');
library.bus.message('syncStarted');
__private.isActive = true;
__private.syncTrigger(true);
async.series({
undoUnconfirmedList: function (seriesCb) {
library.logger.debug('Undoing unconfirmed transactions before sync');
return modules.transactions.undoUnconfirmedList(seriesCb);
},
getPeersBefore: function (seriesCb) {
library.logger.debug('Establishing broadhash consensus before sync');
return modules.transport.getPeers({ limit: constants.maxPeers }, seriesCb);
},
loadBlocksFromNetwork: function (seriesCb) {
return __private.loadBlocksFromNetwork(seriesCb);
},
updateSystem: function (seriesCb) {
return modules.system.update(seriesCb);
},
getPeersAfter: function (seriesCb) {
library.logger.debug('Establishing broadhash consensus after sync');
return modules.transport.getPeers({ limit: constants.maxPeers }, seriesCb);
},
applyUnconfirmedList: function (seriesCb) {
library.logger.debug('Applying unconfirmed transactions after sync');
return modules.transactions.applyUnconfirmedList(seriesCb);
}
}, function (err) {
__private.isActive = false;
__private.syncTrigger(false);
__private.blocksToSync = 0;
library.logger.info('Finished sync');
library.bus.message('syncFinished');
return setImmediate(cb, err);
});
};
/*
* Given a list of peers (with associated blockchain height), we find a list
* of good peers (likely to sync with), then perform a histogram cut, removing
* peers far from the most common observed height. This is not as easy as it
* sounds, since the histogram has likely been made across several blocks,
* therefore need to aggregate).
*/
/**
* Gets the list of good peers.
* @private
* @implements {modules.blocks.lastBlock.get}
* @implements {library.logic.peers.create}
* @param {number} heights
* @return {Object} {height number, peers array}
*/
__private.findGoodPeers = function (heights) {
var lastBlockHeight = modules.blocks.lastBlock.get().height;
library.logger.trace('Good peers - received', { count: heights.length });
heights = heights.filter(function (item) {
// Removing unreachable peers or heights below last block height
return item != null && item.height >= lastBlockHeight;
});
library.logger.trace('Good peers - filtered', { count: heights.length });
// No peers found
if (heights.length === 0) {
return { height: 0, peers: [] };
} else {
// Ordering the peers with descending height
heights = heights.sort(function (a, b) {
return b.height - a.height;
});
var histogram = {};
var max = 0;
var height;
// Aggregating height by 2. TODO: To be changed if node latency increases?
var aggregation = 2;
// Histogram calculation, together with histogram maximum
for (var i in heights) {
var val = parseInt(heights[i].height / aggregation) * aggregation;
histogram[val] = (histogram[val] ? histogram[val] : 0) + 1;
if (histogram[val] > max) {
max = histogram[val];
height = val;
}
}
// Performing histogram cut of peers too far from histogram maximum
var peers = heights.filter(function (item) {
return item && Math.abs(height - item.height) < aggregation + 1;
}).map(function (item) {
return library.logic.peers.create(item);
});
library.logger.trace('Good peers - accepted', { count: peers.length });
library.logger.debug('Good peers', peers);
return { height: height, peers: peers };
}
};
// Public methods
// Rationale:
// - We pick 100 random peers from a random peer (could be unreachable).
// - Then for each of them we grab the height of their blockchain.
// - With this list we try to get a peer with sensibly good blockchain height (see __private.findGoodPeers for actual strategy).
/**
* Gets good peers.
* @implements {modules.blocks.lastBlock.get}
* @implements {modules.peers.list}
* @implements {__private.findGoodPeers}
* @param {function} cb
* @return {setImmediateCallback} err | __private.network (good peers)
*/
Loader.prototype.getNetwork = function (cb) {
if (__private.network.height > 0 && Math.abs(__private.network.height - modules.blocks.lastBlock.get().height) === 1) {
return setImmediate(cb, null, __private.network);
}
modules.peers.list({}, function (err, peers) {
if (err) {
return setImmediate(cb, err);
}
__private.network = __private.findGoodPeers(peers);
if (!__private.network.peers.length) {
return setImmediate(cb, 'Failed to find enough good peers');
} else {
return setImmediate(cb, null, __private.network);
}
});
};
/**
* Checks if private variable syncIntervalId have value.
* @return {boolean} True if syncIntervalId have value
*/
Loader.prototype.syncing = function () {
return !!__private.syncIntervalId;
};
/**
* Returns current blockchain height to achieve if in sync process;
* Returns `0` if syncing done.
*
* @returns {number}
*/
Loader.prototype.getBlocksToSync = function () {
return __private.blocksToSync;
}
/**
* Returns last blockchain height when syncing.
*
* @returns {number}
*/
Loader.prototype.getHeight = function () {
return __private.lastBlock.height;
}
/**
* Returns if the blockchain is in sync process.
*
* @returns {boolean}
*/
Loader.prototype.loaded = function () {
return __private.loaded;
}
/**
* Returns total synced blocks.
*
* @returns {number}
*/
Loader.prototype.getTotalBlocks = function () {
return __private.total;
}
/**
* Calls helpers.sandbox.callMethod().
* @implements module:helpers#callMethod
* @param {function} call - Method to call.
* @param {*} args - List of arguments.
* @param {function} cb - Callback function.
*/
Loader.prototype.sandboxApi = function (call, args, cb) {
sandboxHelper.callMethod(shared, call, args, cb);
};
/**
* Checks if `modules` is loaded.
* @return {boolean} True if `modules` is loaded.
*/
Loader.prototype.isLoaded = function () {
return !!modules;
};
// Events
/**
* Pulls Transactions and signatures.
* @implements {__private.syncTimer}
* @implements {async.series}
* @implements {async.retry}
* @implements {__private.loadTransactions}
* @implements {__private.loadSignatures}
* @implements {__private.initialize}
* @return {function} calls to __private.syncTimer()
*/
Loader.prototype.onPeersReady = function () {
library.logger.trace('Peers ready', { module: 'loader' });
// Enforce sync early
__private.syncTimer();
setImmediate(function load () {
async.series({
loadTransactions: function (seriesCb) {
if (__private.loaded) {
async.retry(__private.retries, __private.loadTransactions, function (err) {
if (err) {
library.logger.log('Unconfirmed transactions loader', err);
}
return setImmediate(seriesCb);
});
} else {
return setImmediate(seriesCb);
}
},
loadSignatures: function (seriesCb) {
if (__private.loaded) {
async.retry(__private.retries, __private.loadSignatures, function (err) {
if (err) {
library.logger.log('Signatures loader', err);
}
return setImmediate(seriesCb);
});
} else {
return setImmediate(seriesCb);
}
}
}, function (err) {
library.logger.trace('Transactions and signatures pulled');
if (err) {
__private.initialize();
}
});
});
};
/**
* Assigns needed modules from scope to private modules variable.
* Calls __private.loadBlockChain
* @param {modules} scope
*/
Loader.prototype.onBind = function (scope) {
modules = {
transactions: scope.transactions,
blocks: scope.blocks,
peers: scope.peers,
rounds: scope.rounds,
transport: scope.transport,
multisignatures: scope.multisignatures,
system: scope.system
};
__private.loadBlockChain();
};
/**
* Sets private variable loaded to true.
*/
Loader.prototype.onBlockchainReady = function () {
__private.loaded = true;
};
/**
* Sets private variable loaded to false.
* @param {function} cb
* @return {setImmediateCallback} cb
*/
Loader.prototype.cleanup = function (cb) {
__private.loaded = false;
return setImmediate(cb);
};
// Internal API
/**
* @todo implement API comments with apidoc.
* @see {@link http://apidocjs.com/}
*/
Loader.prototype.internal = {
statusPing: function () {
return modules.blocks.lastBlock.isFresh();
}
};
// Shared API
/**
* @todo implement API comments with apidoc.
* @see {@link http://apidocjs.com/}
*/
Loader.prototype.shared = {
status: function (req, cb) {
return setImmediate(cb, null, {
loaded: __private.loaded,
now: __private.lastBlock.height,
blocksCount: __private.total
});
},
sync: function (req, cb) {
return setImmediate(cb, null, {
syncing: self.syncing(),
blocks: __private.blocksToSync,
height: modules.blocks.lastBlock.get().height,
broadhash: modules.system.getBroadhash(),
consensus: modules.transport.consensus()
});
}
};
// Export
module.exports = Loader;