-
Notifications
You must be signed in to change notification settings - Fork 98
/
Copy pathvalidation.js
2661 lines (2468 loc) · 113 KB
/
validation.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
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*jslint node: true */
"use strict";
var _ = require('lodash');
var async = require('async');
var storage = require('./storage.js');
var graph = require('./graph.js');
var main_chain = require('./main_chain.js');
var paid_witnessing = require("./paid_witnessing.js");
var headers_commission = require("./headers_commission.js");
var mc_outputs = require("./mc_outputs.js");
var objectHash = require("./object_hash.js");
var objectLength = require("./object_length.js");
var db = require('./db.js');
var chash = require('./chash.js');
var mutex = require('./mutex.js');
var constants = require("./constants.js");
var ValidationUtils = require("./validation_utils.js");
var Definition = require("./definition.js");
var aa_validation = require("./aa_validation.js");
var conf = require('./conf.js');
var profiler = require('./profiler.js');
var breadcrumbs = require('./breadcrumbs.js');
var MAX_INT32 = Math.pow(2, 31) - 1;
var hasFieldsExcept = ValidationUtils.hasFieldsExcept;
var isNonemptyString = ValidationUtils.isNonemptyString;
var isStringOfLength = ValidationUtils.isStringOfLength;
var isInteger = ValidationUtils.isInteger;
var isNonnegativeInteger = ValidationUtils.isNonnegativeInteger;
var isPositiveInteger = ValidationUtils.isPositiveInteger;
var isNonemptyArray = ValidationUtils.isNonemptyArray;
var isValidAddress = ValidationUtils.isValidAddress;
var isValidBase64 = ValidationUtils.isValidBase64;
var assocWitnessListMci = {};
function hasValidHashes(objJoint){
var objUnit = objJoint.unit;
try {
if (objectHash.getUnitHash(objUnit) !== objUnit.unit)
return false;
}
catch(e){
console.log("failed to calc unit hash: "+e);
return false;
}
return true;
}
function validate(objJoint, callbacks, external_conn) {
var objUnit = objJoint.unit;
if (typeof objUnit !== "object" || objUnit === null)
throw Error("no unit object");
if (!objUnit.unit)
throw Error("no unit");
console.log("\nvalidating joint identified by unit "+objJoint.unit.unit);
if (!isStringOfLength(objUnit.unit, constants.HASH_LENGTH))
return callbacks.ifJointError("wrong unit length");
try{
// UnitError is linked to objUnit.unit, so we need to ensure objUnit.unit is true before we throw any UnitErrors
if (objectHash.getUnitHash(objUnit) !== objUnit.unit)
return callbacks.ifJointError("wrong unit hash: "+objectHash.getUnitHash(objUnit)+" != "+objUnit.unit);
}
catch(e){
return callbacks.ifJointError("failed to calc unit hash: "+e);
}
const bGenesis = storage.isGenesisUnit(objUnit.unit);
var bAA = false;
if (objJoint.aa) {
bAA = true;
delete objJoint.aa;
}
else {
if (ValidationUtils.isArrayOfLength(objUnit.authors, 1) && !ValidationUtils.isNonemptyObject(objUnit.authors[0].authentifiers) && !objUnit.content_hash)
return callbacks.ifTransientError("possible AA");
}
if (objJoint.unsigned){
if (hasFieldsExcept(objJoint, ["unit", "unsigned"]))
return callbacks.ifJointError("unknown fields in unsigned unit-joint");
}
else if ("ball" in objJoint){
if (!isStringOfLength(objJoint.ball, constants.HASH_LENGTH))
return callbacks.ifJointError("wrong ball length");
if (hasFieldsExcept(objJoint, ["unit", "ball", "skiplist_units"]))
return callbacks.ifJointError("unknown fields in ball-joint");
if ("skiplist_units" in objJoint){
if (!isNonemptyArray(objJoint.skiplist_units))
return callbacks.ifJointError("missing or empty skiplist array");
//if (objUnit.unit.charAt(0) !== "0")
// return callbacks.ifJointError("found skiplist while unit doesn't start with 0");
}
}
else{
if (hasFieldsExcept(objJoint, ["unit"]))
return callbacks.ifJointError("unknown fields in unit-joint");
}
if ("content_hash" in objUnit){ // nonserial and stripped off content
if (!isStringOfLength(objUnit.content_hash, constants.HASH_LENGTH))
return callbacks.ifUnitError("wrong content_hash length");
if (hasFieldsExcept(objUnit, ["unit", "version", "alt", "timestamp", "authors", "witness_list_unit", "witnesses", "content_hash", "parent_units", "last_ball", "last_ball_unit"]))
return callbacks.ifUnitError("unknown fields in nonserial unit");
if (!objJoint.ball)
return callbacks.ifJointError("content_hash allowed only in finished ball");
}
else{ // serial
if (hasFieldsExcept(objUnit, ["unit", "version", "alt", "timestamp", "authors", "messages", "witness_list_unit", "witnesses", "earned_headers_commission_recipients", "last_ball", "last_ball_unit", "parent_units", "headers_commission", "payload_commission", "oversize_fee", "tps_fee", "burn_fee", "max_aa_responses"]))
return callbacks.ifUnitError("unknown fields in unit");
if (typeof objUnit.headers_commission !== "number")
return callbacks.ifJointError("no headers_commission");
if (typeof objUnit.payload_commission !== "number")
return callbacks.ifJointError("no payload_commission");
if ("oversize_fee" in objUnit && !isPositiveInteger(objUnit.oversize_fee))
return callbacks.ifJointError("bad oversize_fee");
if ("tps_fee" in objUnit && !isNonnegativeInteger(objUnit.tps_fee))
return callbacks.ifUnitError("bad tps_fee");
if ("burn_fee" in objUnit && !isPositiveInteger(objUnit.burn_fee))
return callbacks.ifUnitError("bad burn_fee");
if ("max_aa_responses" in objUnit && !isNonnegativeInteger(objUnit.max_aa_responses))
return callbacks.ifUnitError("bad max_aa_responses");
if (!isNonemptyArray(objUnit.messages))
return callbacks.ifUnitError("missing or empty messages array");
if (objUnit.messages.length > constants.MAX_MESSAGES_PER_UNIT && !bGenesis)
return callbacks.ifUnitError("too many messages");
if (objectLength.getHeadersSize(objUnit) !== objUnit.headers_commission)
return callbacks.ifJointError("wrong headers commission, expected "+objectLength.getHeadersSize(objUnit));
if (objectLength.getTotalPayloadSize(objUnit) !== objUnit.payload_commission)
return callbacks.ifJointError("wrong payload commission, unit "+objUnit.unit+", calculated "+objectLength.getTotalPayloadSize(objUnit)+", expected "+objUnit.payload_commission);
if (objUnit.headers_commission + objUnit.payload_commission > constants.MAX_UNIT_LENGTH && !bGenesis)
return callbacks.ifUnitError("unit too large");
}
if (!isNonemptyArray(objUnit.authors))
return callbacks.ifUnitError("missing or empty authors array");
if (constants.supported_versions.indexOf(objUnit.version) === -1)
return callbacks.ifUnitError("wrong version");
if (objUnit.alt !== constants.alt)
return callbacks.ifUnitError("wrong alt");
if (objUnit.version !== constants.versionWithoutTimestamp) {
if (!isPositiveInteger(objUnit.timestamp))
return callbacks.ifUnitError("timestamp required in version " + objUnit.version);
var current_ts = Math.round(Date.now() / 1000);
var max_seconds_into_the_future_to_accept = conf.max_seconds_into_the_future_to_accept || 3600;
if (objUnit.timestamp > current_ts + max_seconds_into_the_future_to_accept)
return callbacks.ifTransientError("timestamp is too far into the future");
}
if (bGenesis) {
if ("oversize_fee" in objUnit)
return callbacks.ifUnitError("oversize_fee in genesis");
if ("tps_fee" in objUnit)
return callbacks.ifUnitError("tps_fee in genesis");
if ("burn_fee" in objUnit)
return callbacks.ifUnitError("burn_fee in genesis");
if ("max_aa_responses" in objUnit)
return callbacks.ifUnitError("max_aa_responses in genesis");
if ("parent_units" in objUnit)
return callbacks.ifUnitError("parent_units in genesis");
if ("last_ball" in objUnit)
return callbacks.ifUnitError("last_ball in genesis");
if ("last_ball_unit" in objUnit)
return callbacks.ifUnitError("last_ball_unit in genesis");
}
else {
if (!isNonemptyArray(objUnit.parent_units))
return callbacks.ifUnitError("missing or empty parent units array");
if (!isStringOfLength(objUnit.last_ball, constants.HASH_LENGTH))
return callbacks.ifUnitError("wrong length of last ball");
if (!isStringOfLength(objUnit.last_ball_unit, constants.HASH_LENGTH))
return callbacks.ifUnitError("wrong length of last ball unit");
}
if ("witness_list_unit" in objUnit && "witnesses" in objUnit)
return callbacks.ifUnitError("ambiguous witnesses");
var arrAuthorAddresses = objUnit.authors ? objUnit.authors.map(function(author) { return author.address; } ) : [];
var objValidationState = {
arrAdditionalQueries: [],
arrDoubleSpendInputs: [],
arrInputKeys: []
};
if (bGenesis) {
objValidationState.last_ball_mci = 0;
objValidationState.bGenesis = true;
}
if (objJoint.unsigned)
objValidationState.bUnsigned = true;
// if (bAA)
objValidationState.bAA = bAA;
if (conf.bLight){
if (!isPositiveInteger(objUnit.timestamp) && !objJoint.unsigned)
return callbacks.ifJointError("bad timestamp");
if (objJoint.ball)
return callbacks.ifJointError("I'm light, can't accept stable unit "+objUnit.unit+" without proof");
return objJoint.unsigned
? callbacks.ifOkUnsigned(true)
: callbacks.ifOk({sequence: 'good', arrDoubleSpendInputs: [], arrAdditionalQueries: []}, function(){});
}
else{
if ("timestamp" in objUnit && !isPositiveInteger(objUnit.timestamp))
return callbacks.ifJointError("bad timestamp");
}
mutex.lock(arrAuthorAddresses, function(unlock){
var conn = null;
var commit_fn = null;
var start_time = null;
async.series(
[
function(cb){
if (external_conn) {
conn = external_conn;
start_time = Date.now();
commit_fn = function (cb2) { cb2(); };
return cb();
}
db.takeConnectionFromPool(function(new_conn){
conn = new_conn;
start_time = Date.now();
commit_fn = function (cb2) {
conn.query(objValidationState.bAdvancedLastStableMci ? "COMMIT" : "ROLLBACK", function () { cb2(); });
};
conn.query("BEGIN", function(){cb();});
});
},
function(cb){
profiler.start();
checkDuplicate(conn, objUnit, cb);
},
function(cb){
profiler.stop('validation-checkDuplicate');
profiler.start();
objUnit.content_hash ? cb() : validateHeadersCommissionRecipients(objUnit, cb);
},
function(cb){
profiler.stop('validation-hc-recipients');
profiler.start();
!objUnit.parent_units
? cb()
: validateHashTreeBall(conn, objJoint, cb);
},
function(cb){
profiler.stop('validation-hash-tree-ball');
profiler.start();
!objUnit.parent_units
? cb()
: validateParentsExistAndOrdered(conn, objUnit, cb);
},
function(cb){
profiler.stop('validation-parents-exist');
profiler.start();
!objUnit.parent_units
? cb()
: validateHashTreeParentsAndSkiplist(conn, objJoint, cb);
},
function(cb){
profiler.stop('validation-hash-tree-parents');
// profiler.start(); // conflicting with profiling in determineIfStableInLaterUnitsAndUpdateStableMcFlag
!objUnit.parent_units
? cb()
: validateParents(conn, objJoint, objValidationState, cb);
},
function(cb){
// profiler.stop('validation-parents');
profiler.start();
!objJoint.skiplist_units
? cb()
: validateSkiplist(conn, objJoint.skiplist_units, cb);
},
function(cb){
profiler.stop('validation-skiplist');
validateWitnesses(conn, objUnit, objValidationState, cb);
},
function (cb) {
validateAATrigger(conn, objUnit, objValidationState, cb);
},
function (cb) {
validateTpsFee(conn, objJoint, objValidationState, cb);
},
function(cb){
profiler.start();
validateAuthors(conn, objUnit.authors, objUnit, objValidationState, cb);
},
function(cb){
profiler.stop('validation-authors');
profiler.start();
objUnit.content_hash ? cb() : validateMessages(conn, objUnit.messages, objUnit, objValidationState, cb);
}
],
function(err){
if(err){
if (profiler.isStarted())
profiler.stop('validation-advanced-stability');
// We might have advanced the stability point and have to commit the changes as the caches are already updated.
// There are no other updates/inserts/deletes during validation
commit_fn(function(){
var consumed_time = Date.now()-start_time;
profiler.add_result('failed validation', consumed_time);
console.log(objUnit.unit+" validation "+JSON.stringify(err)+" took "+consumed_time+"ms");
if (!external_conn)
conn.release();
unlock();
if (typeof err === "object"){
if (err.error_code === "unresolved_dependency")
callbacks.ifNeedParentUnits(err.arrMissingUnits, err.dontsave);
else if (err.error_code === "need_hash_tree") // need to download hash tree to catch up
callbacks.ifNeedHashTree();
else if (err.error_code === "invalid_joint") // ball found in hash tree but with another unit
callbacks.ifJointError(err.message);
else if (err.error_code === "transient")
callbacks.ifTransientError(err.message);
else
throw Error("unknown error code");
}
else
callbacks.ifUnitError(err);
});
}
else{
profiler.stop('validation-messages');
profiler.start();
commit_fn(function(){
var consumed_time = Date.now()-start_time;
profiler.add_result('validation', consumed_time);
console.log(objUnit.unit+" validation ok took "+consumed_time+"ms");
if (!external_conn)
conn.release();
profiler.stop('validation-commit');
if (objJoint.unsigned){
unlock();
callbacks.ifOkUnsigned(objValidationState.sequence === 'good');
}
else
callbacks.ifOk(objValidationState, unlock);
});
}
}
); // async.series
});
}
// ----------------
function checkDuplicate(conn, objUnit, cb){
var unit = objUnit.unit;
conn.query("SELECT sequence, main_chain_index FROM units WHERE unit=?", [unit], function (rows) {
if (rows.length === 0)
return cb();
var row = rows[0];
// if (row.sequence === 'final-bad' && row.main_chain_index !== null && row.main_chain_index < storage.getMinRetrievableMci() && objUnit.messages && !objUnit.content_hash) // already stripped locally but received a full version
// return cb();
cb(createTransientError("unit "+unit+" already exists"));
});
}
function validateHashTreeBall(conn, objJoint, callback){
if (!objJoint.ball)
return callback();
var objUnit = objJoint.unit;
var unit_by_hash_tree_ball = storage.assocHashTreeUnitsByBall[objJoint.ball];
// conn.query("SELECT unit FROM hash_tree_balls WHERE ball=?", [objJoint.ball], function(rows){
if (!unit_by_hash_tree_ball)
return callback({error_code: "need_hash_tree", message: "ball "+objJoint.ball+" is not known in hash tree"});
if (unit_by_hash_tree_ball !== objUnit.unit)
return callback(createJointError("ball "+objJoint.ball+" unit "+objUnit.unit+" contradicts hash tree"));
callback();
// });
}
function validateHashTreeParentsAndSkiplist(conn, objJoint, callback){
if (!objJoint.ball)
return callback();
var objUnit = objJoint.unit;
function validateBallHash(arrParentBalls, arrSkiplistBalls){
var hash = objectHash.getBallHash(objUnit.unit, arrParentBalls, arrSkiplistBalls, !!objUnit.content_hash);
if (hash !== objJoint.ball)
return callback(createJointError("ball hash is wrong"));
callback();
}
function readBallsByUnits(arrUnits, handleList){
conn.query("SELECT ball FROM balls WHERE unit IN(?) ORDER BY ball", [arrUnits], function(rows){
var arrBalls = rows.map(function(row){ return row.ball; });
if (arrBalls.length === arrUnits.length)
return handleList(arrBalls);
// we have to check in hash_tree_balls too because if we were synced, went offline, and now starting to catch up, our parents will have no ball yet
for (var ball in storage.assocHashTreeUnitsByBall){
var unit = storage.assocHashTreeUnitsByBall[ball];
if (arrUnits.indexOf(unit) >= 0 && arrBalls.indexOf(ball) === -1)
arrBalls.push(ball);
}
arrBalls.sort();
handleList(arrBalls);
});
}
readBallsByUnits(objUnit.parent_units, function(arrParentBalls){
if (arrParentBalls.length !== objUnit.parent_units.length)
return callback(createJointError("some parents not found in balls nor in hash tree")); // while the child is found in hash tree
if (!objJoint.skiplist_units)
return validateBallHash(arrParentBalls, []);
readBallsByUnits(objJoint.skiplist_units, function(arrSkiplistBalls){
if (arrSkiplistBalls.length !== objJoint.skiplist_units.length)
return callback(createJointError("some skiplist balls not found"));
validateBallHash(arrParentBalls, arrSkiplistBalls);
});
});
}
// we cannot verify that skiplist units lie on MC if they are unstable yet,
// but if they don't, we'll get unmatching ball hash when the current unit reaches stability
function validateSkiplist(conn, arrSkiplistUnits, callback){
var prev = "";
async.eachSeries(
arrSkiplistUnits,
function(skiplist_unit, cb){
//if (skiplist_unit.charAt(0) !== "0")
// return cb("skiplist unit doesn't start with 0");
if (skiplist_unit <= prev)
return cb(createJointError("skiplist units not ordered"));
conn.query("SELECT unit, is_stable, is_on_main_chain, main_chain_index FROM units WHERE unit=?", [skiplist_unit], function(rows){
if (rows.length === 0)
return cb("skiplist unit "+skiplist_unit+" not found");
var objSkiplistUnitProps = rows[0];
// if not stable, can't check that it is on MC as MC is not stable in its area yet
if (objSkiplistUnitProps.is_stable === 1){
if (objSkiplistUnitProps.is_on_main_chain !== 1)
return cb("skiplist unit "+skiplist_unit+" is not on MC");
if (objSkiplistUnitProps.main_chain_index % 10 !== 0)
return cb("skiplist unit "+skiplist_unit+" MCI is not divisible by 10");
}
// we can't verify the choice of skiplist unit.
// If we try to find a skiplist unit now, we might find something matching on unstable part of MC.
// Again, we have another check when we reach stability
cb();
});
},
callback
);
}
function validateParentsExistAndOrdered(conn, objUnit, callback){
var prev = "";
var arrMissingParentUnits = [];
if (objUnit.parent_units.length > constants.MAX_PARENTS_PER_UNIT) // anti-spam
return callback("too many parents: "+objUnit.parent_units.length);
async.eachSeries(
objUnit.parent_units,
function(parent_unit, cb){
if (parent_unit <= prev)
return cb("parent units not ordered");
prev = parent_unit;
if (storage.assocUnstableUnits[parent_unit] || storage.assocStableUnits[parent_unit])
return cb();
storage.readStaticUnitProps(conn, parent_unit, function(objUnitProps){
if (!objUnitProps)
arrMissingParentUnits.push(parent_unit);
cb();
}, true);
},
function(err){
if (err)
return callback(err);
if (arrMissingParentUnits.length > 0){
conn.query("SELECT error FROM known_bad_joints WHERE unit IN(?)", [arrMissingParentUnits], function(rows){
(rows.length > 0)
? callback("some of the unit's parents are known bad: "+rows[0].error)
: callback({error_code: "unresolved_dependency", arrMissingUnits: arrMissingParentUnits});
});
return;
}
callback();
}
);
}
function validateParents(conn, objJoint, objValidationState, callback){
// avoid merging the obvious nonserials
function checkNoSameAddressInDifferentParents(){
if (objUnit.parent_units.length === 1)
return callback();
var assocAuthors = {};
var found_address;
async.eachSeries(
objUnit.parent_units,
function(parent_unit, cb){
storage.readUnitAuthors(conn, parent_unit, function(arrAuthors){
arrAuthors.forEach(function(address){
if (assocAuthors[address])
found_address = address;
assocAuthors[address] = true;
});
cb(found_address);
});
},
function(){
if (found_address)
return callback("some addresses found more than once in parents, e.g. "+found_address);
return callback();
}
);
}
function readMaxParentLastBallMci(handleResult){
storage.readMaxLastBallMci(conn, objUnit.parent_units, function(max_parent_last_ball_mci) {
if (max_parent_last_ball_mci > objValidationState.last_ball_mci)
return callback("last ball mci must not retreat, parents: "+objUnit.parent_units.join(', '));
handleResult(max_parent_last_ball_mci);
});
}
var objUnit = objJoint.unit;
if (objValidationState.bAA && objUnit.parent_units.length > 2)
throw Error("AA unit with more than 2 parents");
// obsolete: when handling a ball, we can't trust parent list before we verify ball hash
// obsolete: when handling a fresh unit, we can begin trusting parent list earlier, after we verify parents_hash
// after this point, we can trust parent list as it either agrees with parents_hash or agrees with hash tree
// hence, there are no more joint errors, except unordered parents or skiplist units
var last_ball = objUnit.last_ball;
var last_ball_unit = objUnit.last_ball_unit;
var arrPrevParentUnitProps = [];
objValidationState.max_parent_limci = 0;
objValidationState.max_parent_wl = 0;
async.eachSeries(
objUnit.parent_units,
function(parent_unit, cb){
storage.readUnitProps(conn, parent_unit, function(objParentUnitProps){
if (objUnit.version !== constants.versionWithoutTimestamp && objUnit.timestamp < objParentUnitProps.timestamp)
return cb("timestamp decreased from parent " + parent_unit);
if (objParentUnitProps.latest_included_mc_index > objValidationState.max_parent_limci)
objValidationState.max_parent_limci = objParentUnitProps.latest_included_mc_index;
if (objParentUnitProps.witnessed_level > objValidationState.max_parent_wl)
objValidationState.max_parent_wl = objParentUnitProps.witnessed_level;
async.eachSeries(
arrPrevParentUnitProps,
function(objPrevParentUnitProps, cb2){
graph.compareUnitsByProps(conn, objPrevParentUnitProps, objParentUnitProps, function(result){
(result === null) ? cb2() : cb2("parent unit "+parent_unit+" is related to one of the other parent units");
});
},
function(err){
if (err)
return cb(err);
arrPrevParentUnitProps.push(objParentUnitProps);
cb();
}
);
});
},
function(err){
if (err)
return callback(err);
conn.query(
"SELECT is_stable, is_on_main_chain, main_chain_index, ball, timestamp, (SELECT MAX(main_chain_index) FROM units) AS max_known_mci \n\
FROM units LEFT JOIN balls USING(unit) WHERE unit=?",
[last_ball_unit],
function(rows){
if (rows.length !== 1) // at the same time, direct parents already received
return callback("last ball unit "+last_ball_unit+" not found");
var objLastBallUnitProps = rows[0];
// it can be unstable and have a received (not self-derived) ball
//if (objLastBallUnitProps.ball !== null && objLastBallUnitProps.is_stable === 0)
// throw "last ball "+last_ball+" is unstable";
if (objLastBallUnitProps.ball === null && objLastBallUnitProps.is_stable === 1)
throw Error("last ball unit "+last_ball_unit+" is stable but has no ball");
if (objLastBallUnitProps.is_on_main_chain !== 1)
return callback("last ball "+last_ball+" is not on MC");
if (objLastBallUnitProps.ball && objLastBallUnitProps.ball !== last_ball)
return callback("last_ball "+last_ball+" and last_ball_unit "+last_ball_unit+" do not match");
objValidationState.last_ball_mci = objLastBallUnitProps.main_chain_index;
objValidationState.last_ball_timestamp = objLastBallUnitProps.timestamp;
objValidationState.max_known_mci = objLastBallUnitProps.max_known_mci;
if (objValidationState.max_parent_limci < objValidationState.last_ball_mci)
return callback("last ball unit "+last_ball_unit+" is not included in parents, unit "+objUnit.unit);
var bRequiresTimestamp = (objValidationState.last_ball_mci >= constants.timestampUpgradeMci);
if (bRequiresTimestamp && objUnit.version === constants.versionWithoutTimestamp)
return callback("should be higher version at this mci");
if (!bRequiresTimestamp && objUnit.version !== constants.versionWithoutTimestamp)
return callback("should be version " + constants.versionWithoutTimestamp + " at this mci");
var bWithKeys = (objValidationState.last_ball_mci >= constants.includeKeySizesUpgradeMci);
var bWithKeysVersion = (objUnit.version !== constants.versionWithoutTimestamp && objUnit.version !== constants.versionWithoutKeySizes);
if (bWithKeys !== bWithKeysVersion)
return callback("wrong version, with keys mci = " + bWithKeys + ", with keys version = " + bWithKeysVersion);
const bCommonOpList = (objValidationState.last_ball_mci >= constants.v4UpgradeMci);
const fVersion = parseFloat(objUnit.version);
if (fVersion >= constants.fVersion4) {
if (!bCommonOpList)
return callback("version 4.0+ should be used only since mci " + constants.v4UpgradeMci);
if ("witnesses" in objUnit)
return callback("should have no per-unit witnesses since version 4.0");
if ("witness_list_unit" in objUnit)
return callback("should have no witness_list_unit since version 4.0");
const oversize_fee = storage.getOversizeFee(objUnit, objValidationState.last_ball_mci);
if (oversize_fee) {
if (objUnit.oversize_fee !== oversize_fee)
return callback(createJointError(`oversize_fee mismatch: expected ${oversize_fee}, found ${objUnit.oversize_fee}`));
}
else {
if ("oversize_fee" in objUnit)
return callback("zero oversize fee should be omitted");
}
if (!("tps_fee" in objUnit) && !objValidationState.bAA)
return callback("no tps_fee field");
}
else { // < 4.0
if (bCommonOpList)
return callback("version 4.0 should be used since mci " + constants.v4UpgradeMci);
if (!("witnesses" in objUnit) && !("witness_list_unit" in objUnit))
return callback("should have either witnesses or witness_list_unit");
if ("oversize_fee" in objUnit)
return callback("oversize_fee not charged before version 4.0");
if ("tps_fee" in objUnit)
return callback("tps_fee not charged before version 4.0");
if ("burn_fee" in objUnit)
return callback("burn_fee not paid before version 4.0");
}
readMaxParentLastBallMci(function(max_parent_last_ball_mci){
if (objLastBallUnitProps.is_stable === 1){
// if it were not stable, we wouldn't have had the ball at all
if (objLastBallUnitProps.ball !== last_ball)
return callback("stable: last_ball "+last_ball+" and last_ball_unit "+last_ball_unit+" do not match");
if (objValidationState.last_ball_mci <= constants.lastBallStableInParentsUpgradeMci || max_parent_last_ball_mci === objValidationState.last_ball_mci)
return checkNoSameAddressInDifferentParents();
}
// Last ball is not stable yet in our view. Check if it is stable in view of the parents
main_chain.determineIfStableInLaterUnitsAndUpdateStableMcFlag(conn, last_ball_unit, objUnit.parent_units, objLastBallUnitProps.is_stable, function(bStable, bAdvancedLastStableMci){
/*if (!bStable && objLastBallUnitProps.is_stable === 1){
var eventBus = require('./event_bus.js');
eventBus.emit('nonfatal_error', "last ball is stable, but not stable in parents, unit "+objUnit.unit, new Error());
return checkNoSameAddressInDifferentParents();
}
else */if (!bStable)
return callback(objUnit.unit+": last ball unit "+last_ball_unit+" is not stable in view of your parents "+objUnit.parent_units);
if (bAdvancedLastStableMci)
return callback(createTransientError("last ball just advanced, try again"));
if (!bAdvancedLastStableMci)
return checkNoSameAddressInDifferentParents();
conn.query("SELECT ball FROM balls WHERE unit=?", [last_ball_unit], function(ball_rows){
if (ball_rows.length === 0)
throw Error("last ball unit "+last_ball_unit+" just became stable but ball not found");
if (ball_rows[0].ball !== last_ball)
return callback("last_ball "+last_ball+" and last_ball_unit "+last_ball_unit
+" do not match after advancing stability point");
if (bAdvancedLastStableMci)
objValidationState.bAdvancedLastStableMci = true; // not used
checkNoSameAddressInDifferentParents();
});
});
});
}
);
}
);
}
function checkNoReferencesInWitnessAddressDefinitions(conn, objValidationState, arrWitnesses, cb){
profiler.start();
var cross = (conf.storage === 'sqlite') ? 'CROSS' : ''; // correct the query planner
conn.query(
"SELECT 1 \n\
FROM address_definition_changes \n\
JOIN definitions USING(definition_chash) \n\
JOIN units AS change_units USING(unit) -- units where the change was declared \n\
JOIN unit_authors USING(definition_chash) \n\
JOIN units AS definition_units ON unit_authors.unit=definition_units.unit -- units where the definition was disclosed \n\
WHERE address_definition_changes.address IN(?) AND has_references=1 \n\
AND change_units.is_stable=1 AND change_units.main_chain_index<=? AND +change_units.sequence='good' \n\
AND definition_units.is_stable=1 AND definition_units.main_chain_index<=? AND +definition_units.sequence='good' \n\
UNION \n\
SELECT 1 \n\
FROM definitions \n\
"+cross+" JOIN unit_authors USING(definition_chash) \n\
JOIN units AS definition_units ON unit_authors.unit=definition_units.unit -- units where the definition was disclosed \n\
WHERE definition_chash IN(?) AND has_references=1 \n\
AND definition_units.is_stable=1 AND definition_units.main_chain_index<=? AND +definition_units.sequence='good' \n\
LIMIT 1",
[arrWitnesses, objValidationState.last_ball_mci, objValidationState.last_ball_mci, arrWitnesses, objValidationState.last_ball_mci],
function(rows){
profiler.stop('validation-witnesses-no-refs');
(rows.length > 0) ? cb("some witnesses have references in their addresses") : cb();
}
);
}
function checkWitnessesKnownAndGood(conn, objValidationState, arrWitnesses, cb) {
if (objValidationState.bGenesis)
return cb();
profiler.start();
// check that all witnesses are already known and their units are good and stable
conn.query(
// address=definition_chash is true in the first appearence of the address
// (not just in first appearence: it can return to its initial definition_chash sometime later)
"SELECT COUNT(DISTINCT address) AS count_stable_good_witnesses \n\
FROM unit_authors " + db.forceIndex(conf.storage === 'sqlite' ? 'byDefinitionChash' : 'unitAuthorsIndexByAddressDefinitionChash') + " \n\
CROSS JOIN units USING(unit) \n\
WHERE address=definition_chash AND +sequence='good' AND is_stable=1 AND main_chain_index<=? AND definition_chash IN(?)",
[objValidationState.last_ball_mci, arrWitnesses],
function(rows){
profiler.stop('validation-witnesses-stable');
if (rows[0].count_stable_good_witnesses !== constants.COUNT_WITNESSES)
return cb("some witnesses are not stable, not serial, or don't come before last ball");
cb();
}
);
}
function validateWitnesses(conn, objUnit, objValidationState, callback){
function validateWitnessListMutations(arrWitnesses){
if (!objUnit.parent_units) // genesis
return callback();
storage.determineIfHasWitnessListMutationsAlongMc(conn, objUnit, last_ball_unit, arrWitnesses, function(err){
if (err && objValidationState.last_ball_mci >= 512000) // do not enforce before the || bug was fixed
return callback(err);
checkNoReferencesInWitnessAddressDefinitions(conn, objValidationState, arrWitnesses, err => {
if (err)
return callback(err);
checkWitnessedLevelDidNotRetreat(arrWitnesses);
});
});
}
function checkWitnessedLevelDidNotRetreat(arrWitnesses){
if (!objUnit.parent_units) // genesis
return callback();
storage.determineWitnessedLevelAndBestParent(conn, objUnit.parent_units, arrWitnesses, objUnit.version, function(witnessed_level, best_parent_unit){
if (!best_parent_unit)
return callback("no best parent");
objValidationState.witnessed_level = witnessed_level;
objValidationState.best_parent_unit = best_parent_unit;
if (objValidationState.last_ball_mci < constants.witnessedLevelMustNotRetreatUpgradeMci) // not enforced
return callback();
if (typeof objValidationState.max_parent_wl === 'undefined')
throw Error('no max_parent_wl');
if (objValidationState.last_ball_mci >= constants.witnessedLevelMustNotRetreatFromAllParentsUpgradeMci)
return (witnessed_level >= objValidationState.max_parent_wl) ? callback() : callback("witnessed level retreats from parent's "+objValidationState.max_parent_wl+" to "+witnessed_level);
storage.readStaticUnitProps(conn, best_parent_unit, function(props){
(witnessed_level >= props.witnessed_level)
? callback()
: callback("witnessed level retreats from "+props.witnessed_level+" to "+witnessed_level);
});
});
}
if (objValidationState.last_ball_mci >= constants.v4UpgradeMci)
return checkWitnessedLevelDidNotRetreat(storage.getOpList(objValidationState.last_ball_mci));
var last_ball_unit = objUnit.last_ball_unit;
if (typeof objUnit.witness_list_unit === "string"){
profiler.start();
storage.readWitnessList(conn, objUnit.witness_list_unit, function(arrWitnesses){
if (arrWitnesses.length === 0){
profiler.stop('validation-witnesses-read-list');
return callback("referenced witness list unit "+objUnit.witness_list_unit+" has no witnesses");
}
if (typeof assocWitnessListMci[objUnit.witness_list_unit] === 'number' && assocWitnessListMci[objUnit.witness_list_unit] <= objValidationState.last_ball_mci){
profiler.stop('validation-witnesses-read-list');
return validateWitnessListMutations(arrWitnesses);
}
conn.query("SELECT sequence, is_stable, main_chain_index FROM units WHERE unit=?", [objUnit.witness_list_unit], function(unit_rows){
profiler.stop('validation-witnesses-read-list');
if (unit_rows.length === 0)
return callback("witness list unit "+objUnit.witness_list_unit+" not found");
var objWitnessListUnitProps = unit_rows[0];
if (objWitnessListUnitProps.sequence !== 'good')
return callback("witness list unit "+objUnit.witness_list_unit+" is not serial");
if (objWitnessListUnitProps.is_stable !== 1)
return callback("witness list unit "+objUnit.witness_list_unit+" is not stable");
if (objWitnessListUnitProps.main_chain_index > objValidationState.last_ball_mci)
return callback("witness list unit "+objUnit.witness_list_unit+" must come before last ball");
assocWitnessListMci[objUnit.witness_list_unit] = objWitnessListUnitProps.main_chain_index;
validateWitnessListMutations(arrWitnesses);
});
}, true);
}
else if (Array.isArray(objUnit.witnesses) && objUnit.witnesses.length === constants.COUNT_WITNESSES){
var prev_witness = objUnit.witnesses[0];
for (var i=0; i<objUnit.witnesses.length; i++){
var curr_witness = objUnit.witnesses[i];
if (!chash.isChashValid(curr_witness))
return callback("witness address "+curr_witness+" is invalid");
if (i === 0)
continue;
if (curr_witness <= prev_witness)
return callback("wrong order of witnesses, or duplicates");
prev_witness = curr_witness;
}
if (storage.isGenesisUnit(objUnit.unit)){
// addresses might not be known yet, it's ok
validateWitnessListMutations(objUnit.witnesses);
return;
}
checkWitnessesKnownAndGood(conn, objValidationState, objUnit.witnesses, err => {
if (err)
return callback(err);
validateWitnessListMutations(objUnit.witnesses);
});
}
else
return callback("no witnesses or not enough witnesses");
}
async function validateAATrigger(conn, objUnit, objValidationState, callback) {
if (objValidationState.last_ball_mci < constants.v4UpgradeMci || objValidationState.bAA || !objValidationState.last_ball_mci) {
if ("max_aa_responses" in objUnit)
return callback(`max_aa_responses should not be there`);
if (objValidationState.bAA || !objValidationState.last_ball_mci)
return callback();
}
if ("content_hash" in objUnit) { // messages already stripped off
objValidationState.count_primary_aa_triggers = 0;
return callback();
}
let arrOutputAddresses = [];
for (let m of objUnit.messages) {
if (m.app === 'payment' && m.payload) {
for (let o of m.payload.outputs)
if (!arrOutputAddresses.includes(o.address))
arrOutputAddresses.push(o.address);
}
}
// Look for AA triggers
// There might be actually more triggers due to AAs defined between last_ball_mci and our unit, so our validation of tps fee might require a smaller fee than the fee actually charged when the trigger executes
const rows = await conn.query("SELECT 1 FROM aa_addresses WHERE address IN (?) AND mci<=?", [arrOutputAddresses, objValidationState.last_ball_mci]);
if (rows.length === 0) {
if ("max_aa_responses" in objUnit)
return callback(`no outputs to AAs, max_aa_responses should not be there`);
return callback();
}
objValidationState.count_primary_aa_triggers = rows.length;
callback();
}
function isFromOP(author_addresses, mci) {
const ops = storage.getOpList(mci);
for (let a of author_addresses)
if (ops.includes(a))
return true;
return false;
}
async function validateTpsFee(conn, objJoint, objValidationState, callback) {
if (objValidationState.last_ball_mci < constants.v4UpgradeMci || !objValidationState.last_ball_mci)
return callback();
const objUnit = objJoint.unit;
if (objValidationState.bAA) {
if ("tps_fee" in objUnit)
return callback("tps_fee in AA response");
return callback();
}
if ("content_hash" in objUnit) // tps_fee and other unit fields have been already stripped
return callback();
const objUnitProps = {
unit: objUnit.unit,
parent_units: objUnit.parent_units,
best_parent_unit: objValidationState.best_parent_unit,
last_ball_unit: objUnit.last_ball_unit,
timestamp: objUnit.timestamp,
count_primary_aa_triggers: objValidationState.count_primary_aa_triggers,
max_aa_responses: objUnit.max_aa_responses,
};
const count_units = storage.getCountUnitsPayingTpsFee(objUnitProps);
const min_tps_fee = await storage.getLocalTpsFee(conn, objUnitProps, count_units);
console.log('validation', {min_tps_fee}, objUnitProps)
// compare against the current tps fee or soft-reject
const current_tps_fee = objJoint.ball ? 0 : storage.getCurrentTpsFee(); // very low while catching up
const min_acceptable_tps_fee_multiplier = objJoint.ball ? 0 : storage.getMinAcceptableTpsFeeMultiplier();
const min_acceptable_tps_fee = current_tps_fee * min_acceptable_tps_fee_multiplier * count_units;
const author_addresses = objUnit.authors.map(a => a.address);
const bFromOP = isFromOP(author_addresses, objValidationState.last_ball_mci);
const recipients = storage.getTpsFeeRecipients(objUnit.earned_headers_commission_recipients, author_addresses);
for (let address in recipients) {
const share = recipients[address] / 100;
const [row] = await conn.query("SELECT tps_fees_balance FROM tps_fees_balances WHERE address=? AND mci<=? ORDER BY mci DESC LIMIT 1", [address, objValidationState.last_ball_mci]);
const tps_fees_balance = row ? row.tps_fees_balance : 0;
if (tps_fees_balance + objUnit.tps_fee * share < min_tps_fee * share)
return callback(`tps_fee ${objUnit.tps_fee} + tps fees balance ${tps_fees_balance} less than required ${min_tps_fee} for address ${address} whose share is ${share}`);
const tps_fee = tps_fees_balance / share + objUnit.tps_fee;
if (tps_fee < min_acceptable_tps_fee) {
if (!bFromOP)
return callback(createTransientError(`tps fee on address ${address} must be at least ${min_acceptable_tps_fee}, found ${tps_fee}`));
console.log(`unit from OP, hence accepting despite low tps fee on address ${address} which must be at least ${min_acceptable_tps_fee} but found ${tps_fee}`);
}
}
callback();
}
function validateHeadersCommissionRecipients(objUnit, cb){
if (objUnit.authors.length > 1 && typeof objUnit.earned_headers_commission_recipients !== "object")
return cb("must specify earned_headers_commission_recipients when more than 1 author");
if ("earned_headers_commission_recipients" in objUnit){
if (!isNonemptyArray(objUnit.earned_headers_commission_recipients))
return cb("empty earned_headers_commission_recipients array");
var total_earned_headers_commission_share = 0;
var prev_address = "";
for (var i=0; i<objUnit.earned_headers_commission_recipients.length; i++){
var recipient = objUnit.earned_headers_commission_recipients[i];
if (!isPositiveInteger(recipient.earned_headers_commission_share))
return cb("earned_headers_commission_share must be positive integer");
if (hasFieldsExcept(recipient, ["address", "earned_headers_commission_share"]))
return cb("unknowsn fields in recipient");
if (recipient.address <= prev_address)
return cb("recipient list must be sorted by address");
if (!isValidAddress(recipient.address))
return cb("invalid recipient address checksum");
total_earned_headers_commission_share += recipient.earned_headers_commission_share;
prev_address = recipient.address;
}
if (total_earned_headers_commission_share !== 100)
return cb("sum of earned_headers_commission_share is not 100");
}
cb();
}
function validateAuthors(conn, arrAuthors, objUnit, objValidationState, callback) {
if (objValidationState.bAA && arrAuthors.length !== 1)
throw Error("AA unit with multiple authors");
if (arrAuthors.length > constants.MAX_AUTHORS_PER_UNIT) // this is anti-spam. Otherwise an attacker would send nonserial balls signed by zillions of authors.
return callback("too many authors");
objValidationState.arrAddressesWithForkedPath = [];
var prev_address = "";
for (var i=0; i<arrAuthors.length; i++){
var objAuthor = arrAuthors[i];
if (objAuthor.address <= prev_address)
return callback("author addresses not sorted");
prev_address = objAuthor.address;
}
objValidationState.unit_hash_to_sign = objectHash.getUnitHashToSign(objUnit);
async.eachSeries(arrAuthors, function(objAuthor, cb){
validateAuthor(conn, objAuthor, objUnit, objValidationState, cb);
}, callback);
}
function validateAuthor(conn, objAuthor, objUnit, objValidationState, callback){
if (!isStringOfLength(objAuthor.address, 32))
return callback("wrong address length");
if (objValidationState.bAA && hasFieldsExcept(objAuthor, ["address"]))
throw Error("unknown fields in AA author");
if (!objValidationState.bAA) {
if (hasFieldsExcept(objAuthor, ["address", "authentifiers", "definition"]))
return callback("unknown fields in author");
if (!ValidationUtils.isNonemptyObject(objAuthor.authentifiers) && !objUnit.content_hash)
return callback("no authentifiers");
for (var path in objAuthor.authentifiers) {
if (!isNonemptyString(objAuthor.authentifiers[path]))
return callback("authentifiers must be nonempty strings");
if (objAuthor.authentifiers[path].length > constants.MAX_AUTHENTIFIER_LENGTH)
return callback("authentifier too long");
}
}
var bNonserial = false;
var bInitialDefinition = false;
if (objValidationState.bAA) {
storage.readAADefinition(conn, objAuthor.address, function (arrDefinition) {
if (!arrDefinition)