-
Notifications
You must be signed in to change notification settings - Fork 1
/
validation.js
executable file
·2134 lines (1971 loc) · 90.1 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 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;
if (objectHash.getUnitHash(objUnit) !== objUnit.unit)
return false;
return true;
}
function validate(objJoint, callbacks) {
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);
}
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"]))
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 (!isNonemptyArray(objUnit.messages))
return callbacks.ifUnitError("missing or empty messages array");
if (objUnit.messages.length > constants.MAX_MESSAGES_PER_UNIT)
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 (!isNonemptyArray(objUnit.authors))
return callbacks.ifUnitError("missing or empty authors array");
if (objUnit.version !== constants.version)
return callbacks.ifUnitError("wrong version");
if (objUnit.alt !== constants.alt)
return callbacks.ifUnitError("wrong alt");
if (!storage.isGenesisUnit(objUnit.unit)){
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 (objJoint.unsigned)
objValidationState.bUnsigned = true;
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 start_time = null;
async.series(
[
function(cb){
db.takeConnectionFromPool(function(new_conn){
conn = new_conn;
start_time = Date.now();
conn.query("BEGIN", function(){cb();});
});
},
function(cb){
profiler.start();
checkDuplicate(conn, objUnit.unit, 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()
: validateHashTree(conn, objJoint, objValidationState, cb);
},
function(cb){
profiler.stop('validation-hash-tree');
profiler.start();
!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){
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){
profiler.stop('validation-messages');
if(err){
// 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
conn.query("COMMIT", 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");
conn.release();
unlock();
if (typeof err === "object"){
if (err.error_code === "unresolved_dependency")
callbacks.ifNeedParentUnits(err.arrMissingUnits);
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.start();
conn.query("COMMIT", function(){
var consumed_time = Date.now()-start_time;
profiler.add_result('validation', consumed_time);
console.log(objUnit.unit+" validation ok took "+consumed_time+"ms");
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, unit, cb){
conn.query("SELECT 1 FROM units WHERE unit=?", [unit], function(rows){
if (rows.length === 0)
return cb();
cb("unit "+unit+" already exists");
});
}
function validateHashTree(conn, objJoint, objValidationState, callback){
if (!objJoint.ball)
return callback();
var objUnit = objJoint.unit;
conn.query("SELECT unit FROM hash_tree_balls WHERE ball=?", [objJoint.ball], function(rows){
if (rows.length === 0)
return callback({error_code: "need_hash_tree", message: "ball "+objJoint.ball+" is not known in hash tree"});
if (rows[0].unit !== objUnit.unit)
return callback(createJointError("ball "+objJoint.ball+" unit "+objUnit.unit+" contradicts hash tree"));
conn.query(
"SELECT ball FROM hash_tree_balls WHERE unit IN(?) \n\
UNION \n\
SELECT ball FROM balls WHERE unit IN(?) \n\
ORDER BY ball",
[objUnit.parent_units, objUnit.parent_units],
function(prows){
if (prows.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
var arrParentBalls = prows.map(function(prow){ return prow.ball; });
if (!objJoint.skiplist_units)
return validateBallHash();
conn.query(
"SELECT ball FROM hash_tree_balls WHERE unit IN(?) \n\
UNION \n\
SELECT ball FROM balls WHERE unit IN(?) \n\
ORDER BY ball",
[objJoint.skiplist_units, objJoint.skiplist_units],
function(srows){
if (srows.length !== objJoint.skiplist_units.length)
return callback(createJointError("some skiplist balls not found"));
objValidationState.arrSkiplistBalls = srows.map(function(srow){ return srow.ball; });
validateBallHash();
}
);
function validateBallHash(){
var hash = objectHash.getBallHash(objUnit.unit, arrParentBalls, objValidationState.arrSkiplistBalls, !!objUnit.content_hash);
if (hash !== objJoint.ball)
return callback(createJointError("ball hash is wrong"));
callback();
}
}
);
});
}
// 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 validateParents(conn, objJoint, objValidationState, callback){
// avoid merging the obvious nonserials
function checkNoSameAddressInDifferentParents(){
if (objUnit.parent_units.length === 1)
return callback();
conn.query("SELECT address, COUNT(*) AS c FROM unit_authors WHERE unit IN(?) GROUP BY address HAVING c>1", [objUnit.parent_units], function(rows){
if (rows.length > 0)
return callback("some addresses found more than once in parents, e.g. "+rows[0].address);
return callback();
});
}
function readMaxParentLastBallMci(handleResult){
conn.query(
"SELECT MAX(lb_units.main_chain_index) AS max_parent_last_ball_mci \n\
FROM units JOIN units AS lb_units ON units.last_ball_unit=lb_units.unit \n\
WHERE units.unit IN(?)",
[objUnit.parent_units],
function(rows){
var max_parent_last_ball_mci = rows[0].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 (objUnit.parent_units.length > constants.MAX_PARENTS_PER_UNIT) // anti-spam
return callback("too many parents: "+objUnit.parent_units.length);
// 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
var createError = objJoint.ball ? createJointError : function(err){ return err; };
// 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 prev = "";
var arrMissingParentUnits = [];
var arrPrevParentUnitProps = [];
objValidationState.max_parent_limci = 0;
var join = objJoint.ball ? 'LEFT JOIN balls USING(unit) LEFT JOIN hash_tree_balls ON units.unit=hash_tree_balls.unit' : '';
var field = objJoint.ball ? ', IFNULL(balls.ball, hash_tree_balls.ball) AS ball' : '';
async.eachSeries(
objUnit.parent_units,
function(parent_unit, cb){
if (parent_unit <= prev)
return cb(createError("parent units not ordered"));
prev = parent_unit;
conn.query("SELECT units.*"+field+" FROM units "+join+" WHERE units.unit=?", [parent_unit], function(rows){
if (rows.length === 0){
arrMissingParentUnits.push(parent_unit);
return cb();
}
var objParentUnitProps = rows[0];
// already checked in validateHashTree that the parent ball is known, that's why we throw
if (objJoint.ball && objParentUnitProps.ball === null)
throw Error("no ball corresponding to parent unit "+parent_unit);
if (objParentUnitProps.latest_included_mc_index > objValidationState.max_parent_limci)
objValidationState.max_parent_limci = objParentUnitProps.latest_included_mc_index;
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);
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;
}
// this is redundant check, already checked in validateHashTree()
if (objJoint.ball){
var arrParentBalls = arrPrevParentUnitProps.map(function(objParentUnitProps){ return objParentUnitProps.ball; }).sort();
//if (arrParentBalls.indexOf(null) === -1){
var hash = objectHash.getBallHash(objUnit.unit, arrParentBalls, objValidationState.arrSkiplistBalls, !!objUnit.content_hash);
if (hash !== objJoint.ball)
throw Error("ball hash is wrong"); // shouldn't happen, already validated in validateHashTree()
//}
}
conn.query(
"SELECT is_stable, is_on_main_chain, main_chain_index, ball, (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.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);
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 <= 1300000 || 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 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 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(arrWitnesses);
});
}
function checkNoReferencesInWitnessAddressDefinitions(arrWitnesses){
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) ? callback("some witnesses have references in their addresses") : checkWitnessedLevelDidNotRetreat(arrWitnesses);
}
);
}
function checkWitnessedLevelDidNotRetreat(arrWitnesses){
storage.determineWitnessedLevelAndBestParent(conn, objUnit.parent_units, arrWitnesses, function(witnessed_level, best_parent_unit){
objValidationState.witnessed_level = witnessed_level;
objValidationState.best_parent_unit = best_parent_unit;
if (objValidationState.last_ball_mci < constants.witnessedLevelMustNotRetreatUpgradeMci) // not enforced
return callback();
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);
});
});
}
profiler.start();
var last_ball_unit = objUnit.last_ball_unit;
if (typeof objUnit.witness_list_unit === "string"){
storage.readWitnessList(conn, objUnit.witness_list_unit, function(arrWitnesses){
if (arrWitnesses.length === 0)
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)
return validateWitnessListMutations(arrWitnesses);
conn.query("SELECT sequence, is_stable, main_chain_index FROM units WHERE unit=?", [objUnit.witness_list_unit], function(unit_rows){
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;
profiler.stop('validation-witnesses-read-list');
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;
}
// 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 FROM unit_authors JOIN units USING(unit) \n\
WHERE address=definition_chash AND +sequence='good' AND is_stable=1 AND main_chain_index<=? AND address IN(?)",
[objValidationState.last_ball_mci, objUnit.witnesses],
function(rows){
if (rows[0].count_stable_good_witnesses !== constants.COUNT_WITNESSES)
return callback("some witnesses are not stable, not serial, or don't come before last ball");
profiler.stop('validation-witnesses-stable');
validateWitnessListMutations(objUnit.witnesses);
}
);
}
else
return callback("no witnesses or not enough witnesses");
}
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 (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 (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 arrAddressDefinition = objAuthor.definition;
if (isNonemptyArray(arrAddressDefinition)){
// todo: check that the address is really new?
validateAuthentifiers(arrAddressDefinition);
}
else if (!("definition" in objAuthor)){
if (!chash.isChashValid(objAuthor.address))
return callback("address checksum invalid");
if (objUnit.content_hash){ // nothing else to check
objValidationState.sequence = 'final-bad';
return callback();
}
// we check signatures using the latest address definition before last ball
storage.readDefinitionByAddress(conn, objAuthor.address, objValidationState.last_ball_mci, {
ifDefinitionNotFound: function(definition_chash){
callback("definition "+definition_chash+" bound to address "+objAuthor.address+" is not defined");
},
ifFound: function(arrAddressDefinition){
validateAuthentifiers(arrAddressDefinition);
}
});
}
else
return callback("bad type of definition");
function validateAuthentifiers(arrAddressDefinition){
Definition.validateAuthentifiers(
conn, objAuthor.address, null, arrAddressDefinition, objUnit, objValidationState, objAuthor.authentifiers,
function(err, res){
if (err) // error in address definition
return callback(err);
if (!res) // wrong signature or the like
return callback("authentifier verification failed");
checkSerialAddressUse();
}
);
}
function findConflictingUnits(handleConflictingUnits){
// var cross = (objValidationState.max_known_mci - objValidationState.max_parent_limci < 1000) ? 'CROSS' : '';
conn.query( // _left_ join forces use of indexes in units
/* "SELECT unit, is_stable \n\
FROM units \n\
"+cross+" JOIN unit_authors USING(unit) \n\
WHERE address=? AND (main_chain_index>? OR main_chain_index IS NULL) AND unit != ?",
[objAuthor.address, objValidationState.max_parent_limci, objUnit.unit],*/
"SELECT unit, is_stable, sequence, level \n\
FROM unit_authors \n\
CROSS JOIN units USING(unit) \n\
WHERE address=? AND _mci>? AND unit != ? \n\
UNION \n\
SELECT unit, is_stable, sequence, level \n\
FROM unit_authors \n\
CROSS JOIN units USING(unit) \n\
WHERE address=? AND _mci IS NULL AND unit != ? \n\
ORDER BY level DESC",
[objAuthor.address, objValidationState.max_parent_limci, objUnit.unit, objAuthor.address, objUnit.unit],
function(rows){
if (rows.length === 0)
return handleConflictingUnits([]);
var bAllSerial = rows.every(function(row){ return (row.sequence === 'good'); });
var arrConflictingUnitProps = [];
async.eachSeries(
rows,
function(row, cb){
graph.determineIfIncludedOrEqual(conn, row.unit, objUnit.parent_units, function(bIncluded){
if (!bIncluded)
arrConflictingUnitProps.push(row);
else if (bAllSerial)
return cb('done'); // all are serial and this one is included, therefore the earlier ones are included too
cb();
});
},
function(){
handleConflictingUnits(arrConflictingUnitProps);
}
);
}
);
}
function checkSerialAddressUse(){
var next = checkNoPendingChangeOfDefinitionChash;
findConflictingUnits(function(arrConflictingUnitProps){
if (arrConflictingUnitProps.length === 0){ // no conflicting units
// we can have 2 authors. If the 1st author gave bad sequence but the 2nd is good then don't overwrite
objValidationState.sequence = objValidationState.sequence || 'good';
return next();
}
var arrConflictingUnits = arrConflictingUnitProps.map(function(objConflictingUnitProps){ return objConflictingUnitProps.unit; });
breadcrumbs.add("========== found conflicting units "+arrConflictingUnits+" =========");
breadcrumbs.add("========== will accept a conflicting unit "+objUnit.unit+" =========");
objValidationState.arrAddressesWithForkedPath.push(objAuthor.address);
objValidationState.arrConflictingUnits = (objValidationState.arrConflictingUnits || []).concat(arrConflictingUnits);
bNonserial = true;
var arrUnstableConflictingUnitProps = arrConflictingUnitProps.filter(function(objConflictingUnitProps){
return (objConflictingUnitProps.is_stable === 0);
});
var bConflictsWithStableUnits = arrConflictingUnitProps.some(function(objConflictingUnitProps){
return (objConflictingUnitProps.is_stable === 1);
});
if (objValidationState.sequence !== 'final-bad') // if it were already final-bad because of 1st author, it can't become temp-bad due to 2nd author
objValidationState.sequence = bConflictsWithStableUnits ? 'final-bad' : 'temp-bad';
var arrUnstableConflictingUnits = arrUnstableConflictingUnitProps.map(function(objConflictingUnitProps){ return objConflictingUnitProps.unit; });
if (bConflictsWithStableUnits) // don't temp-bad the unstable conflicting units
return next();
if (arrUnstableConflictingUnits.length === 0)
return next();
// we don't modify the db during validation, schedule the update for the write
objValidationState.arrAdditionalQueries.push(
{sql: "UPDATE units SET sequence='temp-bad' WHERE unit IN(?) AND +sequence='good'", params: [arrUnstableConflictingUnits]});
next();
});
}
// don't allow contradicting pending keychanges.
// We don't trust pending keychanges even when they are serial, as another unit may arrive and make them nonserial
function checkNoPendingChangeOfDefinitionChash(){
var next = checkNoPendingDefinition;
//var filter = bNonserial ? "AND sequence='good'" : "";
conn.query(
"SELECT unit FROM address_definition_changes JOIN units USING(unit) \n\
WHERE address=? AND (is_stable=0 OR main_chain_index>? OR main_chain_index IS NULL)",
[objAuthor.address, objValidationState.last_ball_mci],
function(rows){
if (rows.length === 0)
return next();
if (!bNonserial || objValidationState.arrAddressesWithForkedPath.indexOf(objAuthor.address) === -1)
return callback("you can't send anything before your last keychange is stable and before last ball");
// from this point, our unit is nonserial
async.eachSeries(
rows,
function(row, cb){
graph.determineIfIncludedOrEqual(conn, row.unit, objUnit.parent_units, function(bIncluded){
if (bIncluded)
console.log("checkNoPendingChangeOfDefinitionChash: unit "+row.unit+" is included");
bIncluded ? cb("found") : cb();
});
},
function(err){
(err === "found")
? callback("you can't send anything before your last included keychange is stable and before last ball (self is nonserial)")
: next();
}
);
}
);
}
// We don't trust pending definitions even when they are serial, as another unit may arrive and make them nonserial,
// then the definition will be removed
function checkNoPendingDefinition(){
//var next = checkNoPendingOrRetrievableNonserialIncluded;
var next = validateDefinition;
//var filter = bNonserial ? "AND sequence='good'" : "";
// var cross = (objValidationState.max_known_mci - objValidationState.last_ball_mci < 1000) ? 'CROSS' : '';
conn.query( // _left_ join forces use of indexes in units
// "SELECT unit FROM units "+cross+" JOIN unit_authors USING(unit) \n\
// WHERE address=? AND definition_chash IS NOT NULL AND ( /* is_stable=0 OR */ main_chain_index>? OR main_chain_index IS NULL)",
// [objAuthor.address, objValidationState.last_ball_mci],
"SELECT unit FROM unit_authors WHERE address=? AND definition_chash IS NOT NULL AND _mci>? \n\
UNION \n\
SELECT unit FROM unit_authors WHERE address=? AND definition_chash IS NOT NULL AND _mci IS NULL",
[objAuthor.address, objValidationState.last_ball_mci, objAuthor.address],
function(rows){
if (rows.length === 0)
return next();
if (!bNonserial || objValidationState.arrAddressesWithForkedPath.indexOf(objAuthor.address) === -1)
return callback("you can't send anything before your last definition is stable and before last ball");
// from this point, our unit is nonserial
async.eachSeries(
rows,
function(row, cb){
graph.determineIfIncludedOrEqual(conn, row.unit, objUnit.parent_units, function(bIncluded){
if (bIncluded)
console.log("checkNoPendingDefinition: unit "+row.unit+" is included");
bIncluded ? cb("found") : cb();
});
},
function(err){
(err === "found")
? callback("you can't send anything before your last included definition is stable and before last ball (self is nonserial)")
: next();
}
);
}
);
}
// This was bad idea. An uncovered nonserial, if not archived, will block new units from this address forever.
/*
function checkNoPendingOrRetrievableNonserialIncluded(){
var next = validateDefinition;
conn.query(
"SELECT lb_units.main_chain_index FROM units JOIN units AS lb_units ON units.last_ball_unit=lb_units.unit \n\
WHERE units.is_on_main_chain=1 AND units.main_chain_index=?",
[objValidationState.last_ball_mci],
function(lb_rows){
var last_ball_of_last_ball_mci = (lb_rows.length > 0) ? lb_rows[0].main_chain_index : 0;
conn.query(
"SELECT unit FROM unit_authors JOIN units USING(unit) \n\
WHERE address=? AND (is_stable=0 OR main_chain_index>?) AND sequence!='good'",
[objAuthor.address, last_ball_of_last_ball_mci],
function(rows){
if (rows.length === 0)
return next();
if (!bNonserial)
return callback("you can't send anything before all your nonserial units are stable and before last ball of last ball");
// from this point, the unit is nonserial
async.eachSeries(
rows,
function(row, cb){
graph.determineIfIncludedOrEqual(conn, row.unit, objUnit.parent_units, function(bIncluded){
if (bIncluded)
console.log("checkNoPendingOrRetrievableNonserialIncluded: unit "+row.unit+" is included");
bIncluded ? cb("found") : cb();
});
},
function(err){
(err === "found")
? callback("you can't send anything before all your included nonserial units are stable \
and lie before last ball of last ball (self is nonserial)")
: next();
}
);
}
);
}
);
}
*/
function validateDefinition(){
if (!("definition" in objAuthor))
return callback();
// the rest assumes that the definition is explicitly defined
var arrAddressDefinition = objAuthor.definition;
storage.readDefinitionByAddress(conn, objAuthor.address, objValidationState.last_ball_mci, {
ifDefinitionNotFound: function(definition_chash){ // first use of the definition_chash (in particular, of the address, when definition_chash=address)
if (objectHash.getChash160(arrAddressDefinition) !== definition_chash)
return callback("wrong definition: "+objectHash.getChash160(arrAddressDefinition) +"!=="+ definition_chash);
callback();
},
ifFound: function(arrAddressDefinition2){ // arrAddressDefinition2 can be different
handleDuplicateAddressDefinition(arrAddressDefinition2);
}
});
}
function handleDuplicateAddressDefinition(arrAddressDefinition){
if (!bNonserial || objValidationState.arrAddressesWithForkedPath.indexOf(objAuthor.address) === -1)
return callback("duplicate definition of address "+objAuthor.address+", bNonserial="+bNonserial);
// todo: investigate if this can split the nodes
// in one particular case, the attacker changes his definition then quickly sends a new ball with the old definition - the new definition will not be active yet
if (objectHash.getChash160(arrAddressDefinition) !== objectHash.getChash160(objAuthor.definition))
return callback("unit definition doesn't match the stored definition");
callback(); // let it be for now. Eventually, at most one of the balls will be declared good
}
}
function validateMessages(conn, arrMessages, objUnit, objValidationState, callback){
console.log("validateMessages "+objUnit.unit);
async.forEachOfSeries(
arrMessages,
function(objMessage, message_index, cb){
validateMessage(conn, objMessage, message_index, objUnit, objValidationState, cb);
},
function(err){
if (err)
return callback(err);
if (!objValidationState.bHasBasePayment)
return callback("no base payment message");
callback();
}
);
}
function validateMessage(conn, objMessage, message_index, objUnit, objValidationState, callback) {
if (typeof objMessage.app !== "string")
return callback("no app");
if (!isStringOfLength(objMessage.payload_hash, constants.HASH_LENGTH))
return callback("wrong payload hash size");
if (typeof objMessage.payload_location !== "string")
return callback("no payload_location");
if (hasFieldsExcept(objMessage, ["app", "payload_hash", "payload_location", "payload", "payload_uri", "payload_uri_hash", "spend_proofs"]))
return callback("unknown fields in message");
if ("spend_proofs" in objMessage){
if (!Array.isArray(objMessage.spend_proofs) || objMessage.spend_proofs.length === 0 || objMessage.spend_proofs.length > constants.MAX_SPEND_PROOFS_PER_MESSAGE)
return callback("spend_proofs must be non-empty array max "+constants.MAX_SPEND_PROOFS_PER_MESSAGE+" elements");
var arrAuthorAddresses = objUnit.authors.map(function(author) { return author.address; } );
// spend proofs are sorted in the same order as their corresponding inputs
//var prev_spend_proof = "";
for (var i=0; i<objMessage.spend_proofs.length; i++){
var objSpendProof = objMessage.spend_proofs[i];
if (typeof objSpendProof !== "object")
return callback("spend_proof must be object");
if (hasFieldsExcept(objSpendProof, ["spend_proof", "address"]))
return callback("unknown fields in spend_proof");
//if (objSpendProof.spend_proof <= prev_spend_proof)
// return callback("spend_proofs not sorted");