forked from byteball/ocore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
definition.js
1428 lines (1349 loc) · 51.7 KB
/
definition.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 crypto = require('crypto');
var _ = require('lodash');
var async = require('async');
var constants = require('./constants.js');
var conf = require('./conf.js');
var storage = require('./storage.js');
var db = require('./db.js');
var ecdsaSig = require('./signature.js');
var merkle = require('./merkle.js');
var ValidationUtils = require("./validation_utils.js");
var objectHash = require("./object_hash.js");
var formulaParser = require('./formula/index');
var Decimal = require('decimal.js');
var dataFeeds = require('./data_feeds.js');
var assignField = require('./formula/common.js').assignField;
var hasFieldsExcept = ValidationUtils.hasFieldsExcept;
var isStringOfLength = ValidationUtils.isStringOfLength;
var isNonemptyString = ValidationUtils.isNonemptyString;
var isInteger = ValidationUtils.isInteger;
var isNonnegativeInteger = ValidationUtils.isNonnegativeInteger;
var isPositiveInteger = ValidationUtils.isPositiveInteger;
var isNonemptyArray = ValidationUtils.isNonemptyArray;
var isNonemptyObject = ValidationUtils.isNonemptyObject;
var isArrayOfLength = ValidationUtils.isArrayOfLength;
var isValidAddress = ValidationUtils.isValidAddress;
var isValidBase64 = ValidationUtils.isValidBase64;
function pathIncludesOneOfAuthentifiers(path, arrAuthentifierPaths, bAssetCondition){
if (bAssetCondition)
throw Error('pathIncludesOneOfAuthentifiers called in asset condition');
for (var i=0; i<arrAuthentifierPaths.length; i++){
var authentifier_path = arrAuthentifierPaths[i];
if (authentifier_path.substr(0, path.length) === path)
return true;
}
return false;
}
// validate definition of address or asset spending conditions
function validateDefinition(conn, arrDefinition, objUnit, objValidationState, arrAuthentifierPaths, bAssetCondition, handleResult){
function getFilterError(filter){
if (!filter)
return "no filter";
if (hasFieldsExcept(filter, ["what", "asset", "type", "address", "amount", "amount_at_least", "amount_at_most"]))
return "unknown fields in filter";
if (filter.what !== "input" && filter.what !== "output")
return "invalid what="+filter.what;
if (bAssetCondition && filter.asset === "this asset" && objValidationState.bDefiningPrivateAsset)
return "private asset cannot reference itself";
if ("asset" in filter && !(filter.asset === "base" || isStringOfLength(filter.asset, constants.HASH_LENGTH) || bAssetCondition && filter.asset === "this asset"))
return "invalid asset: "+filter.asset;
if (filter.what === "output"){
if ("type" in filter)
return "output canot have type";
}
if ("type" in filter && filter.type !== "issue" && filter.type !== "transfer")
return "invalid type: "+filter.type;
if (bAssetCondition && (filter.address === 'this address' || filter.address === 'other address'))
return "asset condition cannot reference this/other address";
if ("address" in filter && !isValidAddress(filter.address) && filter.address !== 'this address' && (filter.address !== 'other address' || objValidationState.last_ball_mci < constants.otherAddressInDefinitionUpgradeMci)) // it is ok if the address was never used yet
return "invalid address: "+filter.address;
if ("amount" in filter && !isPositiveInteger(filter.amount))
return "amount must be positive int";
if ("amount_at_least" in filter && !isPositiveInteger(filter.amount_at_least))
return "amount_at_least must be positive int";
if ("amount_at_most" in filter && !isPositiveInteger(filter.amount_at_most))
return "amount_at_most must be positive int";
if (filter.amount && (filter.amount_at_least || filter.amount_at_most))
return "can't have amount and amount_at_least/most at the same time";
return null;
}
// it is difficult to ease this condition for bAssetCondition:
// we might allow _this_ asset (the asset this condition is attached to) to be private but we might have only part of this asset's payments disclosed,
// some parties may see more disclosed than others.
function determineIfAnyOfAssetsIsPrivate(arrAssets, cb){
if (arrAssets.length === 0)
return cb(false);
conn.query("SELECT 1 FROM assets WHERE unit IN(?) AND is_private=1 LIMIT 1", [arrAssets], function(rows){
cb(rows.length > 0);
});
}
function needToEvaluateNestedAddress(path){
if (!arrAuthentifierPaths) // no signatures, just validating a new definition
return true;
if (objValidationState.last_ball_mci < constants.skipEvaluationOfUnusedNestedAddressUpgradeMci) // skipping is enabled after this mci
return true;
return pathIncludesOneOfAuthentifiers(path, arrAuthentifierPaths, bAssetCondition);
}
function evaluate(arr, path, bInNegation, cb){
complexity++;
count_ops++;
if (complexity > constants.MAX_COMPLEXITY)
return cb("complexity exceeded at "+path);
if (count_ops > constants.MAX_OPS)
return cb("number of ops exceeded at "+path);
if (!isArrayOfLength(arr, 2))
return cb("expression must be 2-element array");
var op = arr[0];
var args = arr[1];
switch(op){
case 'or':
case 'and':
if (!Array.isArray(args))
return cb(op+" args must be array");
if (args.length < 2)
return cb(op+" must have at least 2 options");
var count_options_with_sig = 0;
var index = -1;
async.eachSeries(
args,
function(arg, cb2){
index++;
evaluate(arg, path+'.'+index, bInNegation, function(err, bHasSig){
if (err)
return cb2(err);
if (bHasSig)
count_options_with_sig++;
cb2();
});
},
function(err){
if (err)
return cb(err);
cb(null, op === "and" && count_options_with_sig > 0 || op === "or" && count_options_with_sig === args.length);
}
);
break;
case 'r of set':
if (hasFieldsExcept(args, ["required", "set"]))
return cb("unknown fields in "+op);
if (!isPositiveInteger(args.required))
return cb("required must be positive");
if (!Array.isArray(args.set))
return cb("set must be array");
if (args.set.length < 2)
return cb("set must have at least 2 options");
if (args.required > args.set.length)
return cb("required must be <= than set length");
//if (args.required === args.set.length)
// return cb("required must be strictly less than set length, use and instead");
//if (args.required === 1)
// return cb("required must be more than 1, use or instead");
var count_options_with_sig = 0;
var index = -1;
async.eachSeries(
args.set,
function(arg, cb2){
index++;
evaluate(arg, path+'.'+index, bInNegation, function(err, bHasSig){
if (err)
return cb2(err);
if (bHasSig)
count_options_with_sig++;
cb2();
});
},
function(err){
if (err)
return cb(err);
var count_options_without_sig = args.set.length - count_options_with_sig;
cb(null, args.required > count_options_without_sig);
}
);
break;
case 'weighted and':
if (hasFieldsExcept(args, ["required", "set"]))
return cb("unknown fields in "+op);
if (!isPositiveInteger(args.required))
return cb("required must be positive");
if (!Array.isArray(args.set))
return cb("set must be array");
if (args.set.length < 2)
return cb("set must have at least 2 options");
var weight_of_options_with_sig = 0;
var total_weight = 0;
var index = -1;
async.eachSeries(
args.set,
function(arg, cb2){
index++;
if (hasFieldsExcept(arg, ["value", "weight"]))
return cb2("unknown fields in weighted set element");
if (!isPositiveInteger(arg.weight))
return cb2("weight must be positive int");
total_weight += arg.weight;
evaluate(arg.value, path+'.'+index, bInNegation, function(err, bHasSig){
if (err)
return cb2(err);
if (bHasSig)
weight_of_options_with_sig += arg.weight;
cb2();
});
},
function(err){
if (err)
return cb(err);
if (args.required > total_weight)
return cb("required must be <= than total weight");
var weight_of_options_without_sig = total_weight - weight_of_options_with_sig;
cb(null, args.required > weight_of_options_without_sig);
}
);
break;
case 'sig':
if (bInNegation)
return cb(op+" cannot be negated");
if (bAssetCondition)
return cb("asset condition cannot have "+op);
if (hasFieldsExcept(args, ["algo", "pubkey"]))
return cb("unknown fields in "+op);
if (args.algo === "secp256k1")
return cb("default algo must not be explicitly specified");
if ("algo" in args && args.algo !== "secp256k1")
return cb("unsupported sig algo");
if (!isStringOfLength(args.pubkey, constants.PUBKEY_LENGTH))
return cb("wrong pubkey length");
return cb(null, true);
case 'hash':
if (bInNegation)
return cb(op+" cannot be negated");
if (bAssetCondition)
return cb("asset condition cannot have "+op);
if (hasFieldsExcept(args, ["algo", "hash"]))
return cb("unknown fields in "+op);
if (args.algo === "sha256")
return cb("default algo must not be explicitly specified");
if ("algo" in args && args.algo !== "sha256")
return cb("unsupported hash algo");
if (!ValidationUtils.isValidBase64(args.hash, constants.HASH_LENGTH))
return cb("wrong base64 hash");
return cb();
case 'address':
if (objValidationState.bNoReferences)
return cb("no references allowed in address definition");
if (bInNegation)
return cb(op+" cannot be negated");
if (bAssetCondition)
return cb("asset condition cannot have "+op);
var other_address = args;
if (!isValidAddress(other_address))
return cb("invalid address");
storage.readDefinitionByAddress(conn, other_address, objValidationState.last_ball_mci, {
ifFound: function(arrInnerAddressDefinition){
console.log("inner address:", arrInnerAddressDefinition);
needToEvaluateNestedAddress(path) ? evaluate(arrInnerAddressDefinition, path, bInNegation, cb) : cb(null, true);
},
ifDefinitionNotFound: function(definition_chash){
// if (objValidationState.bAllowUnresolvedInnerDefinitions)
// return cb(null, true);
var bAllowUnresolvedInnerDefinitions = true;
var arrDefiningAuthors = objUnit.authors.filter(function(author){
return (author.address === other_address && author.definition && objectHash.getChash160(author.definition) === definition_chash);
});
if (arrDefiningAuthors.length === 0) // no address definition in the current unit
return bAllowUnresolvedInnerDefinitions ? cb(null, true) : cb("definition of inner address "+other_address+" not found");
if (arrDefiningAuthors.length > 1)
throw Error("more than 1 address definition");
var arrInnerAddressDefinition = arrDefiningAuthors[0].definition;
needToEvaluateNestedAddress(path) ? evaluate(arrInnerAddressDefinition, path, bInNegation, cb) : cb(null, true);
}
});
break;
case 'definition template':
// ['definition template', ['unit', {param1: 'value1'}]]
if (objValidationState.bNoReferences)
return cb("no references allowed in address definition");
if (!isArrayOfLength(args, 2))
return cb("2-element array expected in "+op);
var unit = args[0];
var params = args[1];
if (!isStringOfLength(unit, constants.HASH_LENGTH))
return cb("unit must be 44 bytes long");
if (!ValidationUtils.isNonemptyObject(params))
return cb("params must be non-empty object");
for (var key in params)
if (typeof params[key] !== "string" && typeof params[key] !== "number")
return cb("each param must be string or number");
conn.query(
"SELECT payload FROM messages JOIN units USING(unit) \n\
WHERE unit=? AND app='definition_template' AND main_chain_index<=? AND +sequence='good' AND is_stable=1",
[unit, objValidationState.last_ball_mci],
function(rows){
if (rows.length !== 1)
return cb("template not found or too many");
var template = rows[0].payload;
var arrTemplate = JSON.parse(template);
try{
var arrFilledTemplate = replaceInTemplate(arrTemplate, params);
console.log(require('util').inspect(arrFilledTemplate, {depth: null}));
}
catch(e){
if (e instanceof NoVarException)
return cb(e.toString());
else
throw e;
}
evaluate(arrFilledTemplate, path, bInNegation, cb);
}
);
break;
case 'seen address':
if (objValidationState.bNoReferences)
return cb("no references allowed in address definition");
if (!isValidAddress(args)) // it is ok if the address was never used yet
return cb("invalid seen address");
return cb();
case 'seen definition change':
case 'has definition change':
if (objValidationState.bNoReferences)
return cb("no references allowed in address definition");
if (!isArrayOfLength(args, 2))
return cb(op+" must have 2 args");
var changed_address = args[0];
var new_definition_chash = args[1];
if (bAssetCondition && (changed_address === 'this address' || new_definition_chash === 'this address' || changed_address === 'other address' || new_definition_chash === 'other address'))
return cb("asset condition cannot reference this/other address in "+op);
if (!isValidAddress(changed_address) && changed_address !== 'this address') // it is ok if the address was never used yet
return cb("invalid changed address");
if (!isValidAddress(new_definition_chash) && new_definition_chash !== 'this address' && new_definition_chash !== 'any')
return cb("invalid new definition chash");
if (new_definition_chash === 'any' && objValidationState.last_ball_mci < constants.anyDefinitionChangeUpgradeMci)
return cb("too early use of 'any' in new_definition_chash");
return cb();
case 'attested':
if (objValidationState.bNoReferences)
return cb("no references allowed in address definition");
if (!isArrayOfLength(args, 2))
return cb(op+" must have 2 args");
var attested_address = args[0];
var arrAttestors = args[1];
if (bAssetCondition && attested_address === 'this address')
return cb("asset condition cannot reference this address in "+op);
if (!isValidAddress(attested_address) && attested_address !== 'this address') // it is ok if the address was never used yet
return cb("invalid attested address");
if (!ValidationUtils.isNonemptyArray(arrAttestors))
return cb("no attestors");
for (var i=0; i<arrAttestors.length; i++)
if (!isValidAddress(arrAttestors[i]))
return cb("invalid attestor address "+arrAttestors[i]);
if (objValidationState.last_ball_mci < constants.attestedInDefinitionUpgradeMci)
return cb(op+" not enabled yet");
return cb();
case 'cosigned by':
if (bInNegation)
return cb(op+" cannot be negated");
if (!isValidAddress(args)) // it is ok if the address was never used yet
return cb("invalid cosigner address");
return cb();
case 'not':
evaluate(args, path, true, cb);
break;
case 'in data feed':
if (objValidationState.bNoReferences)
return cb("no references allowed in address definition");
if (!Array.isArray(args))
return cb(op+" arg must be array");
if (args.length !== 4 && args.length !== 5)
return cb(op+" must have 4 or 5 args");
var arrAddresses = args[0];
var feed_name = args[1];
var relation = args[2];
var value = args[3];
var min_mci = args[4];
if (!isNonemptyArray(arrAddresses))
return cb("no addresses in "+op);
for (var i=0; i<arrAddresses.length; i++)
if (!isValidAddress(arrAddresses[i])) // it is ok if the address was never used yet
return cb("address "+arrAddresses[i]+" not valid");
complexity += arrAddresses.length-1; // 1 complexity point for each address (1 point was already counted)
if (!isNonemptyString(relation))
return cb("no relation");
if (["=", ">", "<", ">=", "<=", "!="].indexOf(relation) === -1)
return cb("invalid relation: "+relation);
if (!isNonemptyString(feed_name))
return cb("no feed_name");
if (feed_name.length > constants.MAX_DATA_FEED_NAME_LENGTH)
return cb("feed_name too long");
if (typeof value === "string"){
if (!isNonemptyString(value))
return cb("no value");
if (value.length > constants.MAX_DATA_FEED_VALUE_LENGTH)
return cb("value too long");
}
else if (typeof value === "number"){
if (!isInteger(value))
return cb("no fractional values allowed");
}
else
return cb("invalid value");
if (typeof min_mci !== 'undefined' && !isNonnegativeInteger(min_mci))
return cb(op+": invalid min_mci");
return cb();
case 'in merkle':
if (bInNegation)
return cb(op+" cannot be negated");
if (objValidationState.bNoReferences)
return cb("no references allowed in address definition");
if (bAssetCondition)
return cb("asset condition cannot have "+op);
if (!Array.isArray(args))
return cb(op+" arg must be array");
if (args.length !== 3 && args.length !== 4)
return cb(op+" must have 3 or 4 args");
var arrAddresses = args[0];
var feed_name = args[1];
var element = args[2];
var min_mci = args[3];
if (!isNonemptyArray(arrAddresses))
return cb("no addresses in "+op);
for (var i=0; i<arrAddresses.length; i++)
if (!isValidAddress(arrAddresses[i])) // it is ok if the address was never used yet
return cb("address "+arrAddresses[i]+" not valid");
complexity += arrAddresses.length-1; // 1 complexity point for each address (1 point was already counted)
if (!isNonemptyString(feed_name))
return cb("no feed_name");
if (feed_name.length > constants.MAX_DATA_FEED_NAME_LENGTH)
return cb("feed_name too long");
// if (!isStringOfLength(element_hash, constants.HASH_LENGTH))
// return cb("incorrect length of element hash");
if (!element.match(/[\w ~,.\/\\;:!@#$%^&*\(\)=+\[\]\{\}<>\?|-]{1,100}/))
return cb("incorrect format of merkled element");
if (typeof min_mci !== 'undefined' && !isNonnegativeInteger(min_mci))
return cb(op+": invalid min_mci");
return cb();
case 'mci':
case 'age':
case 'timestamp':
var relation = args[0];
var value = args[1];
if (!isNonemptyString(relation))
return cb("no relation");
if (["=", ">", "<", ">=", "<=", "!="].indexOf(relation) === -1)
return cb("invalid relation: "+relation);
if (!isNonnegativeInteger(value))
return cb(op+" must be a non-neg number");
if (op === 'timestamp' && objValidationState.last_ball_mci < constants.timestampUpgradeMci)
return cb('timestamp op not allowed yet');
return cb();
case 'has':
case 'has one':
case 'seen':
if (objValidationState.bNoReferences)
return cb("no references allowed in address definition");
var err = getFilterError(args);
if (err)
return cb(err);
if (op === 'seen'){
if (!args.address)
return cb('seen must specify address');
if (args.address === 'other address')
return cb('seen cannot be other address');
if (args.what === 'input' && (args.amount || args.amount_at_least || args.amount_at_most))
return cb('amount not allowed in seen input');
}
if (!args.asset || args.asset === 'base' || bAssetCondition && args.asset === "this asset")
return cb();
determineIfAnyOfAssetsIsPrivate([args.asset], function(bPrivate){
if (bPrivate)
return cb("asset must be public");
cb();
});
break;
case 'has equal':
case 'has one equal':
if (objValidationState.bNoReferences)
return cb("no references allowed in address definition");
if (hasFieldsExcept(args, ["equal_fields", "search_criteria"]))
return cb("unknown fields in "+op);
if (!isNonemptyArray(args.equal_fields))
return cb("no equal_fields");
var assocUsedFields = {};
for (var i=0; i<args.equal_fields.length; i++){
var field = args.equal_fields[i];
if (assocUsedFields[field])
return cb("duplicate "+field);
assocUsedFields[field] = true;
if (["asset", "address", "amount", "type"].indexOf(field) === -1)
return cb("unknown field: "+field);
}
if (!isArrayOfLength(args.search_criteria, 2))
return cb("search_criteria must be 2-elements array");
var arrAssets = [];
for (var i=0; i<2; i++){
var filter = args.search_criteria[i];
var err = getFilterError(filter);
if (err)
return cb(err);
if (!(filter.asset || filter.asset === 'base' || bAssetCondition && filter.asset === "this asset"))
arrAssets.push(filter.asset);
}
if (args.equal_fields.indexOf("type") >= 0 && (args.search_criteria[0].what === "output" || args.search_criteria[1].what === "output"))
return cb("outputs cannot have type");
if (arrAssets.length === 0)
return cb();
determineIfAnyOfAssetsIsPrivate(arrAssets, function(bPrivate){
bPrivate ? cb("all assets must be public") : cb();
});
break;
case 'sum':
if (objValidationState.bNoReferences)
return cb("no references allowed in address definition");
if (hasFieldsExcept(args, ["filter", "equals", "at_least", "at_most"]))
return cb("unknown fields in "+op);
var err = getFilterError(args.filter);
if (err)
return cb(err);
if (args.filter.amount || args.filter.amount_at_least || args.filter.amount_at_most)
return cb("sum filter cannot restrict amounts");
if ("equals" in args && !isNonnegativeInteger(args.equals))
return cb("equals must be nonnegative int");
if ("at_least" in args && !isPositiveInteger(args.at_least))
return cb("at_least must be positive int");
if ("at_most" in args && !isPositiveInteger(args.at_most))
return cb("at_most must be positive int");
if ("equals" in args && ("at_least" in args || "at_most" in args))
return cb("can't have equals and at_least/at_most at the same time")
if (!("equals" in args) && !("at_least" in args) && !("at_most" in args))
return cb("at least one of equals, at_least, at_most must be specified");
if (!args.filter.asset || args.filter.asset === 'base' || bAssetCondition && args.filter.asset === "this asset")
return cb();
determineIfAnyOfAssetsIsPrivate([args.filter.asset], function(bPrivate){
bPrivate ? cb("asset must be public") : cb();
});
break;
case 'formula':
if (objValidationState.last_ball_mci < constants.formulaUpgradeMci)
return cb("formulas not allowed at this mci yet");
formulaParser.validate({ formula: args, complexity: complexity, count_ops: count_ops, mci: objValidationState.last_ball_mci, locals: {} }, function (result) {
complexity = result.complexity;
count_ops = result.count_ops;
cb(result.error);
});
break;
default:
return cb("unknown op: "+op);
}
}
var complexity = 0;
var count_ops = 0;
evaluate(arrDefinition, 'r', false, function(err, bHasSig){
if (err)
return handleResult(err);
if (!bHasSig && !bAssetCondition)
return handleResult("each branch must have a signature");
if (complexity > constants.MAX_COMPLEXITY)
return handleResult("complexity exceeded");
if (count_ops > constants.MAX_OPS)
return handleResult("number of ops exceeded");
handleResult();
});
}
function evaluateAssetCondition(conn, asset, arrDefinition, objUnit, objValidationState, cb){
validateAuthentifiers(conn, null, asset, arrDefinition, objUnit, objValidationState, null, cb);
}
// also validates address definition
function validateAuthentifiers(conn, address, this_asset, arrDefinition, objUnit, objValidationState, assocAuthentifiers, cb){
function evaluate(arr, path, cb2){
var op = arr[0];
var args = arr[1];
switch(op){
case 'or':
// ['or', [list of options]]
var res = false;
var index = -1;
async.eachSeries(
args,
function(arg, cb3){
index++;
evaluate(arg, path+'.'+index, function(arg_res){
res = res || arg_res;
cb3(); // check all members, even if required minimum already found
//res ? cb3("found") : cb3();
});
},
function(){
cb2(res);
}
);
break;
case 'and':
// ['and', [list of requirements]]
var res = true;
var index = -1;
async.eachSeries(
args,
function(arg, cb3){
index++;
evaluate(arg, path+'.'+index, function(arg_res){
res = res && arg_res;
cb3(); // check all members, even if required minimum already found
//res ? cb3() : cb3("found");
});
},
function(){
cb2(res);
}
);
break;
case 'r of set':
// ['r of set', {required: 2, set: [list of options]}]
var count = 0;
var index = -1;
async.eachSeries(
args.set,
function(arg, cb3){
index++;
evaluate(arg, path+'.'+index, function(arg_res){
if (arg_res)
count++;
cb3(); // check all members, even if required minimum already found, so that we don't allow invalid sig on unchecked path
//(count < args.required) ? cb3() : cb3("found");
});
},
function(){
cb2(count >= args.required);
}
);
break;
case 'weighted and':
// ['weighted and', {required: 15, set: [{value: boolean_expr, weight: 10}, {value: boolean_expr, weight: 20}]}]
var weight = 0;
var index = -1;
async.eachSeries(
args.set,
function(arg, cb3){
index++;
evaluate(arg.value, path+'.'+index, function(arg_res){
if (arg_res)
weight += arg.weight;
cb3(); // check all members, even if required minimum already found
//(weight < args.required) ? cb3() : cb3("found");
});
},
function(){
cb2(weight >= args.required);
}
);
break;
case 'sig':
// ['sig', {algo: 'secp256k1', pubkey: 'base64'}]
//console.log(op, path);
var signature = assocAuthentifiers[path];
if (!signature)
return cb2(false);
arrUsedPaths.push(path);
var algo = args.algo || 'secp256k1';
if (algo === 'secp256k1'){
if (objValidationState.bUnsigned && signature[0] === "-") // placeholder signature
return cb2(true);
var res = ecdsaSig.verify(objValidationState.unit_hash_to_sign, signature, args.pubkey);
if (!res)
fatal_error = "bad signature at path "+path;
cb2(res);
}
break;
case 'hash':
// ['hash', {algo: 'sha256', hash: 'base64'}]
if (!assocAuthentifiers[path])
return cb2(false);
arrUsedPaths.push(path);
var algo = args.algo || 'sha256';
if (algo === 'sha256'){
var res = (args.hash === crypto.createHash("sha256").update(assocAuthentifiers[path], "utf8").digest("base64"));
if (!res)
fatal_error = "bad hash at path "+path;
cb2(res);
}
break;
case 'address':
// ['address', 'BASE32']
if (!pathIncludesOneOfAuthentifiers(path, arrAuthentifierPaths, bAssetCondition))
return cb2(false);
var other_address = args;
storage.readDefinitionByAddress(conn, other_address, objValidationState.last_ball_mci, {
ifFound: function(arrInnerAddressDefinition){
evaluate(arrInnerAddressDefinition, path, cb2);
},
ifDefinitionNotFound: function(definition_chash){
var arrDefiningAuthors = objUnit.authors.filter(function(author){
return (author.address === other_address && author.definition && objectHash.getChash160(author.definition) === definition_chash);
});
if (arrDefiningAuthors.length === 0) // no definition in the current unit
return cb2(false);
if (arrDefiningAuthors.length > 1)
throw Error("more than 1 address definition");
var arrInnerAddressDefinition = arrDefiningAuthors[0].definition;
evaluate(arrInnerAddressDefinition, path, cb2);
}
});
break;
case 'definition template':
// ['definition template', ['unit', {param1: 'value1'}]]
var unit = args[0];
var params = args[1];
conn.query(
"SELECT payload FROM messages JOIN units USING(unit) \n\
WHERE unit=? AND app='definition_template' AND main_chain_index<=? AND +sequence='good' AND is_stable=1",
[unit, objValidationState.last_ball_mci],
function(rows){
if (rows.length !== 1)
throw Error("not 1 template");
var template = rows[0].payload;
var arrTemplate = JSON.parse(template);
var arrFilledTemplate = replaceInTemplate(arrTemplate, params);
evaluate(arrFilledTemplate, path, cb2);
}
);
break;
case 'seen address':
// ['seen address', 'BASE32']
var seen_address = args;
conn.query(
"SELECT 1 FROM unit_authors CROSS JOIN units USING(unit) \n\
WHERE address=? AND main_chain_index<=? AND sequence='good' AND is_stable=1 \n\
LIMIT 1",
[seen_address, objValidationState.last_ball_mci],
function(rows){
cb2(rows.length > 0);
}
);
break;
case 'seen definition change':
// ['seen definition change', ['BASE32', 'BASE32']]
var changed_address = args[0];
var new_definition_chash = args[1];
if (changed_address === 'this address')
changed_address = address;
if (new_definition_chash === 'this address')
new_definition_chash = address;
var and_definition_chash = (new_definition_chash === 'any') ? '' : 'AND definition_chash='+db.escape(new_definition_chash);
conn.query(
"SELECT 1 FROM address_definition_changes CROSS JOIN units USING(unit) \n\
WHERE address=? "+and_definition_chash+" AND main_chain_index<=? AND sequence='good' AND is_stable=1 \n\
LIMIT 1",
[changed_address, objValidationState.last_ball_mci],
function(rows){
cb2(rows.length > 0);
}
);
break;
case 'seen':
// ['seen', {what: 'input', asset: 'asset or base', type: 'transfer'|'issue', amount_at_least: 123, amount_at_most: 123, amount: 123, address: 'BASE32'}]
var filter = args;
if (filter.what !== 'input' && filter.what !== 'output')
throw Error("invalid what: " + filter.what);
var sql = "SELECT 1 FROM "+filter.what+"s CROSS JOIN units USING(unit) \n\
LEFT JOIN assets ON asset=assets.unit \n\
WHERE main_chain_index<=? AND sequence='good' AND is_stable=1 AND (asset IS NULL OR is_private=0) ";
var params = [objValidationState.last_ball_mci];
if (filter.asset){
if (filter.asset === 'base')
sql += " AND asset IS NULL ";
else{
sql += " AND asset=? ";
params.push(filter.asset);
}
}
if (filter.type){
sql += " AND type=? ";
params.push(filter.type);
}
if (filter.address){
sql += " AND address=? ";
params.push((filter.address === 'this address') ? address : filter.address);
}
if (filter.what === 'output'){
if (filter.amount_at_least){
sql += " AND amount>=? ";
params.push(filter.amount_at_least);
}
if (filter.amount_at_most){
sql += " AND amount<=? ";
params.push(filter.amount_at_most);
}
if (filter.amount){
sql += " AND amount=? ";
params.push(filter.amount);
}
}
sql += " LIMIT 1";
conn.query(sql, params, function(rows){
cb2(rows.length > 0);
});
break;
case 'attested':
// ['attested', ['BASE32', ['BASE32']]]
var attested_address = args[0];
var arrAttestors = args[1];
if (attested_address === 'this address')
attested_address = address;
storage.filterAttestedAddresses(
conn, {arrAttestorAddresses: arrAttestors}, objValidationState.last_ball_mci, [attested_address], function(arrFilteredAddresses){
cb2(arrFilteredAddresses.length > 0);
}
);
break;
case 'cosigned by':
// ['cosigned by', 'BASE32']
var cosigner_address = args;
var arrAuthorAddresses = objUnit.authors.map(function(author){ return author.address; });
console.log(op+" "+arrAuthorAddresses.indexOf(cosigner_address));
cb2(arrAuthorAddresses.indexOf(cosigner_address) >= 0);
break;
case 'not':
// useful for conditions such as: after timestamp but there's still no searched value in datafeed
// sig, hash, and address cannot be negated
evaluate(args, path, function(not_res){
cb2(!not_res);
});
break;
case 'in data feed':
// ['in data feed', [['BASE32'], 'data feed name', '=', 'expected value']]
var arrAddresses = args[0];
var feed_name = args[1];
var relation = args[2];
var value = args[3];
var min_mci = args[4] || 0;
dataFeeds.dataFeedExists(arrAddresses, feed_name, relation, value, min_mci, objValidationState.last_ball_mci, false, cb2);
/*
var value_condition;
var index;
var params = [arrAddresses, feed_name];
if (typeof value === "string"){
index = 'byNameStringValue';
var isNumber = /^-?\d+\.?\d*$/.test(value);
if (isNumber){
var bForceNumericComparison = (['>','>=','<','<='].indexOf(relation) >= 0);
var plus_0 = bForceNumericComparison ? '+0' : '';
value_condition = '(value'+plus_0+relation+value+' OR int_value'+relation+value+')';
// params.push(value, value);
}
else{
value_condition = 'value'+relation+conn.escape(value);
// params.push(value);
}
}
else{
index = 'byNameIntValue';
value_condition = 'int_value'+relation+value;
// params.push(value);
}
params.push(objValidationState.last_ball_mci, min_mci);
var getOptimalQuery = function(handleSql) {
var rareFeedSql = "SELECT 1 FROM data_feeds " + db.forceIndex(index) + " CROSS JOIN units USING(unit) CROSS JOIN unit_authors USING(unit) \n\
WHERE address IN(?) AND feed_name=? AND " + value_condition + " \n\
AND main_chain_index<=? AND main_chain_index>=? AND sequence='good' AND is_stable=1 LIMIT 1";
var rareOracleSql = "SELECT 1 FROM unit_authors CROSS JOIN data_feeds USING(unit) CROSS JOIN units USING(unit) \n\
WHERE address IN(?) AND feed_name=? AND " + value_condition + " \n\
AND main_chain_index<=? AND main_chain_index>=? AND sequence='good' AND is_stable=1 LIMIT 1";
var recentFeedSql = "SELECT 1 FROM data_feeds CROSS JOIN units USING(unit) CROSS JOIN unit_authors USING(unit) \n\
WHERE +address IN(?) AND +feed_name=? AND " + value_condition + " \n\
AND +main_chain_index<=? AND +main_chain_index>=? AND +sequence='good' AND +is_stable=1 ORDER BY data_feeds.rowid DESC LIMIT 1";
// first, see how often this data feed is posted
conn.query("SELECT 1 FROM data_feeds " + db.forceIndex(index) + " WHERE feed_name=? AND " + value_condition + " LIMIT 100,1", [feed_name], function (dfrows) {
console.log('feed ' + feed_name + ': dfrows.length=' + dfrows.length);
// for rare feeds, use the data feed index; for frequent feeds, scan starting from the most recent one
if (dfrows.length === 0)
return handleSql(rareFeedSql);
// next, see how often the oracle address posts
conn.query("SELECT 1 FROM unit_authors WHERE address IN(?) LIMIT 100,1", [arrAddresses], function (arows) {
console.log('oracles ' + arrAddresses.join(', ') + ': arows.length=' + arows.length);
if (arows.length === 0)
return handleSql(rareOracleSql);
if (conf.storage !== 'sqlite')
return handleSql(rareFeedSql);
handleSql(recentFeedSql);
});
});
}
getOptimalQuery(function (sql) {
conn.query(sql, params, function(rows){
console.log(op+" "+feed_name+" "+rows.length);
cb2(rows.length > 0);
});
});
*/
break;
case 'in merkle':
// ['in merkle', [['BASE32'], 'data feed name', 'expected value']]
if (!assocAuthentifiers[path])
return cb2(false);
arrUsedPaths.push(path);
var arrAddresses = args[0];
var feed_name = args[1];
var element = args[2];
var min_mci = args[3] || 0;
var serialized_proof = assocAuthentifiers[path];
var proof = merkle.deserializeMerkleProof(serialized_proof);
// console.error('merkle root '+proof.root);
if (!merkle.verifyMerkleProof(element, proof)){
fatal_error = "bad merkle proof at path "+path;
return cb2(false);
}
dataFeeds.dataFeedExists(arrAddresses, feed_name, '=', proof.root, min_mci, objValidationState.last_ball_mci, false, cb2);
/*
conn.query(
"SELECT 1 FROM data_feeds CROSS JOIN units USING(unit) JOIN unit_authors USING(unit) \n\
WHERE address IN(?) AND feed_name=? AND value=? AND main_chain_index<=? AND main_chain_index>=? AND sequence='good' AND is_stable=1 \n\
LIMIT 1",
[arrAddresses, feed_name, proof.root, objValidationState.last_ball_mci, min_mci],
function(rows){
if (rows.length === 0)
fatal_error = "merkle proof at path "+path+" not found";
cb2(rows.length > 0);
}
);
*/
break;
case 'timestamp':
var relation = args[0];
var timestamp = args[1];
switch(relation){
case '>': return cb2(objValidationState.last_ball_timestamp > timestamp);
case '>=': return cb2(objValidationState.last_ball_timestamp >= timestamp);
case '<': return cb2(objValidationState.last_ball_timestamp < timestamp);
case '<=': return cb2(objValidationState.last_ball_timestamp <= timestamp);
case '=': return cb2(objValidationState.last_ball_timestamp === timestamp);
case '!=': return cb2(objValidationState.last_ball_timestamp !== timestamp);
default: throw Error('unknown relation in mci: '+relation);
}
break;
case 'mci':
var relation = args[0];
var mci = args[1];
switch(relation){
case '>': return cb2(objValidationState.last_ball_mci > mci);
case '>=': return cb2(objValidationState.last_ball_mci >= mci);
case '<': return cb2(objValidationState.last_ball_mci < mci);
case '<=': return cb2(objValidationState.last_ball_mci <= mci);
case '=': return cb2(objValidationState.last_ball_mci === mci);
case '!=': return cb2(objValidationState.last_ball_mci !== mci);
default: throw Error('unknown relation in mci: '+relation);
}
break;
case 'age':
var relation = args[0];
var age = args[1];
if (["=", ">", "<", ">=", "<=", "!="].indexOf(relation) === -1)
throw Error("invalid relation in age: "+relation);
augmentMessagesAndContinue(function(){
var arrSrcUnits = [];
for (var i=0; i<objValidationState.arrAugmentedMessages.length; i++){
var message = objValidationState.arrAugmentedMessages[i];
if (message.app !== 'payment' || !message.payload)
continue;
var inputs = message.payload.inputs;
for (var j=0; j<inputs.length; j++){
var input = inputs[j];