-
Notifications
You must be signed in to change notification settings - Fork 0
/
aa_composer.js
1857 lines (1785 loc) · 67.4 KB
/
aa_composer.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 Decimal = require('decimal.js');
var _ = require('lodash');
var async = require('async');
var constants = require('./constants.js');
var string_utils = require("./string_utils.js");
var storage = require('./storage.js');
var db = require('./db.js');
var ValidationUtils = require("./validation_utils.js");
var objectLength = require("./object_length.js");
var objectHash = require("./object_hash.js");
var validation = require("./validation.js");
var formulaParser = require('./formula/evaluation.js');
var kvstore = require('./kvstore.js');
var eventBus = require('./event_bus.js');
var mutex = require('./mutex.js');
var writer = require('./writer.js');
var conf = require('./conf.js');
var getFormula = require('./formula/common.js').getFormula;
var hasCases = require('./formula/common.js').hasCases;
var assignField = require('./formula/common.js').assignField;
var assignObject = require('./formula/common.js').assignObject;
var wrappedObject = formulaParser.wrappedObject;
var toJsType = formulaParser.toJsType;
var isNonnegativeInteger = ValidationUtils.isNonnegativeInteger;
var isNonemptyArray = ValidationUtils.isNonemptyArray;
var isNonemptyObject = ValidationUtils.isNonemptyObject;
var isEmptyObjectOrArray = ValidationUtils.isEmptyObjectOrArray;
var testnetAAsDefinedByAAsAreActiveImmediatelyUpgradeMci = 1167000;
var TRANSFER_INPUT_SIZE = 0 // type: "transfer" omitted
+ 44 // unit
+ 8 // message_index
+ 8; // output_index
var TRANSFER_INPUT_KEYS_SIZE = "unit".length + "message_index".length + "output_index".length;
var OUTPUT_SIZE = 32 + 8; // address + amount
var OUTPUT_KEYS_SIZE = "address".length + "amount".length;
const CHECK_BALANCES_INTERVAL = conf.CHECK_BALANCES_INTERVAL || 600 * 1000;
eventBus.on('new_aa_triggers', function () {
mutex.lock(["write"], function (unlock) {
unlock(); // we don't need to block writes, we requested the lock just to wait that the current write completes
handleAATriggers();
});
});
function handleAATriggers() {
mutex.lock(['aa_triggers'], function (unlock) {
db.query(
"SELECT aa_triggers.mci, aa_triggers.unit, address, definition \n\
FROM aa_triggers \n\
CROSS JOIN units USING(unit) \n\
CROSS JOIN aa_addresses USING(address) \n\
ORDER BY aa_triggers.mci, level, aa_triggers.unit, address",
function (rows) {
var arrPostedUnits = [];
async.eachSeries(
rows,
function (row, cb) {
var arrDefinition = JSON.parse(row.definition);
handlePrimaryAATrigger(row.mci, row.unit, row.address, arrDefinition, arrPostedUnits, cb);
},
function () {
arrPostedUnits.forEach(function (objUnit) {
eventBus.emit('new_aa_unit', objUnit);
});
unlock();
}
);
}
);
});
}
function handlePrimaryAATrigger(mci, unit, address, arrDefinition, arrPostedUnits, onDone) {
db.takeConnectionFromPool(function (conn) {
conn.query("BEGIN", function () {
var batch = kvstore.batch();
readMcUnit(conn, mci, function (objMcUnit) {
readUnit(conn, unit, function (objUnit) {
var arrResponses = [];
var trigger = getTrigger(objUnit, address);
trigger.initial_address = trigger.address;
trigger.initial_unit = trigger.unit;
handleTrigger(conn, batch, trigger, {}, {}, arrDefinition, address, mci, objMcUnit, false, arrResponses, function(){
conn.query("DELETE FROM aa_triggers WHERE mci=? AND unit=? AND address=?", [mci, unit, address], function(){
var batch_start_time = Date.now();
batch.write({ sync: true }, function(err){
console.log("AA batch write took "+(Date.now()-batch_start_time)+'ms');
if (err)
throw Error("AA composer: batch write failed: "+err);
conn.query("COMMIT", function () {
conn.release();
if (arrResponses.length > 1) {
// copy updatedStateVars to all responses
if (arrResponses[0].updatedStateVars)
for (var i = 1; i < arrResponses.length; i++)
arrResponses[i].updatedStateVars = arrResponses[0].updatedStateVars;
// merge all changes of balances if the same AA was called more than once
let assocBalances = {};
for (let { aa_address, balances } of arrResponses)
assocBalances[aa_address] = balances; // overwrite if repeated
for (let r of arrResponses) {
r.balances = assocBalances[r.aa_address];
r.allBalances = assocBalances;
}
}
else
arrResponses[0].allBalances = { [address]: arrResponses[0].balances };
arrResponses.forEach(function (objAAResponse) {
if (objAAResponse.objResponseUnit)
arrPostedUnits.push(objAAResponse.objResponseUnit);
eventBus.emit('aa_response', objAAResponse);
eventBus.emit('aa_response_to_unit-'+objAAResponse.trigger_unit, objAAResponse);
eventBus.emit('aa_response_to_address-'+objAAResponse.trigger_address, objAAResponse);
eventBus.emit('aa_response_from_aa-'+objAAResponse.aa_address, objAAResponse);
});
onDone();
});
});
});
});
});
});
});
});
}
// estimates the effects of an AA trigger before it gets stable.
// stateVars and assocBalances are updated after the function returns.
// The estimation is not 100% accurate, e.g. storage_size is ignored, unit validation errors are not caught
function estimatePrimaryAATrigger(objUnit, address, stateVars, assocBalances, onDone) {
if (!onDone)
return new Promise(resolve => estimatePrimaryAATrigger(objUnit, address, stateVars, assocBalances, resolve));
db.takeConnectionFromPool(function (conn) {
conn.query("BEGIN", function () {
storage.readAADefinition(conn, address, arrDefinition => {
if (!arrDefinition)
throw Error("AA not found: " + address)
readLastUnit(conn, function (objMcUnit) {
// rewrite timestamp in case our last unit is old (light or unsynced full)
objMcUnit.timestamp = objUnit.timestamp || Math.round(Date.now() / 1000);
if (objUnit.main_chain_index)
objMcUnit.main_chain_index = objUnit.main_chain_index;
var mci = objMcUnit.main_chain_index;
var arrResponses = [];
var trigger = getTrigger(objUnit, address);
trigger.initial_address = trigger.address;
trigger.initial_unit = trigger.unit;
var trigger_opts = {
bAir: true,
conn,
trigger,
params: {},
stateVars,
assocBalances, // balances _before_ the trigger, not including the coins received in the trigger
arrDefinition,
address,
mci,
objMcUnit,
arrResponses,
onDone: function () {
// remove the 'updated' flag for future triggers
for (var aa in stateVars) {
var addressVars = stateVars[aa];
for (var var_name in addressVars) {
var state = addressVars[var_name];
if (state.updated) {
delete state.updated;
state.old_value = state.value;
state.original_old_value = state.value;
}
}
}
conn.query("ROLLBACK", function () {
conn.release();
// copy updatedStateVars to all responses
if (arrResponses.length > 1 && arrResponses[0].updatedStateVars)
for (var i = 1; i < arrResponses.length; i++)
arrResponses[i].updatedStateVars = arrResponses[0].updatedStateVars;
onDone(arrResponses);
});
},
}
handleTrigger(trigger_opts);
});
});
});
});
}
var lightBatch = {
put: function () { },
del: function () { },
clear: function () { },
write: function () {
throw Error("attempting to write a batch in a light client");
}
};
function validateAATriggerObject(trigger, handle) {
if (!ValidationUtils.isNonemptyObject(trigger))
return handle("no trigger");
if (!ValidationUtils.isNonemptyObject(trigger.outputs))
return handle("no trigger outputs");
if (!ValidationUtils.isValidAddress(trigger.address))
return handle("bad trigger address");
var arrAssets = Object.keys(trigger.outputs).filter(function(asset) {return asset !== 'base'});
if (arrAssets.length >= constants.MAX_MESSAGES_PER_UNIT)
return handle("too many assets");
if (!ValidationUtils.isPositiveInteger(trigger.outputs.base))
return handle("no base payment");
if (arrAssets.length === 0)
return handle();
if (!arrAssets.every(function(asset){return ValidationUtils.isPositiveInteger(trigger.outputs[asset])}))
return handle("invalid output amount")
// we have to check that assets exist otherwise foreign key constraint would fail when inserting fake outputs
db.query("SELECT 1 FROM assets WHERE unit IN (?)", [arrAssets], function(rows) {
if (rows.length !== arrAssets.length)
return handle("unknown asset");
else
return handle();
});
}
function dryRunPrimaryAATrigger(trigger, address, arrDefinition, onDone) {
db.takeConnectionFromPool(function (conn) {
conn.query("BEGIN", function () {
var batch = conf.bLight ? lightBatch : kvstore.batch();
readLastStableMcUnit(conn, function (mci, objMcUnit) {
trigger.unit = objMcUnit.unit;
if (!trigger.address)
trigger.address = objMcUnit.authors[0].address;
trigger.initial_address = trigger.address;
trigger.initial_unit = trigger.unit;
var fPrepare = function (cb) {
insertFakeOutputsIntoMcUnit(conn, objMcUnit, trigger.outputs, address, cb);
};
fPrepare(function () {
var arrResponses = [];
handleTrigger(conn, batch, trigger, {}, {}, arrDefinition, address, mci, objMcUnit, false, arrResponses, function () {
revertResponsesInCaches(arrResponses);
batch.clear();
conn.query("ROLLBACK", function () {
conn.release();
onDone(arrResponses);
});
});
});
});
});
});
}
function readLastStableMcUnit(conn, handleMciAndUnit) {
conn.query(
"SELECT unit, main_chain_index FROM units WHERE +is_on_main_chain=1 AND +is_stable=1 \n\
ORDER BY main_chain_index DESC LIMIT 1",
function (rows) {
if (rows.length !== 1)
throw Error("found " + rows.length + " last stable MC units");
var row = rows[0];
readUnit(conn, row.unit, function (objUnit) {
handleMciAndUnit(row.main_chain_index, objUnit);
});
}
);
}
function insertFakeOutputsIntoMcUnit(conn, objMcUnit, outputs, address, onDone) {
// this ensures we have the funds on AA address in case the response unit tries to send the received funds somewhere else
console.log('inserting fake outputs into unit ' + objMcUnit.unit);
var arrQueries = [];
var message_index = objMcUnit.messages.length;
for (var asset in outputs) {
conn.addQuery(arrQueries,
"INSERT INTO outputs (unit, message_index, output_index, asset, address, amount) VALUES(?, ?,0, ?, ?, ?)",
[objMcUnit.unit, message_index, asset === 'base' ? null : asset, address, outputs[asset]]);
message_index++;
}
async.series(arrQueries, onDone);
}
function readMcUnit(conn, mci, handleUnit) {
conn.query("SELECT unit FROM units WHERE main_chain_index=? AND is_on_main_chain=1", [mci], function (rows) {
if (rows.length !== 1)
throw Error("found " + rows.length + " MC units on MCI " + mci);
readUnit(conn, rows[0].unit, handleUnit);
});
}
function readLastUnit(conn, handleUnit) {
conn.query("SELECT unit, main_chain_index FROM units ORDER BY main_chain_index DESC LIMIT 1", function (rows) {
if (rows.length !== 1 || !rows[0].main_chain_index) {
if (!conf.bLight)
throw Error("found " + rows.length + " last units");
var objMcUnit = {
unit: 'mcunit',
witness_list_unit: 'mcwitnesslistunit',
last_ball_unit: 'mclastballunit',
last_ball: 'mclastball',
timestamp: Math.round(Date.now() / 1000),
main_chain_index: 1e9,
};
return handleUnit(objMcUnit);
}
readUnit(conn, rows[0].unit, handleUnit);
});
}
function readUnit(conn, unit, handleUnit) {
storage.readJoint(conn, unit, {
ifNotFound: function () {
throw Error("unit not found: " + unit);
},
ifFound: function (objJoint) {
handleUnit(objJoint.unit);
}
});
}
function getTrigger(objUnit, receiving_address) {
var trigger = { address: objUnit.authors[0].address, unit: objUnit.unit, outputs: {} };
objUnit.messages.forEach(function (message) {
if (message.app === 'data' && !trigger.data) // use the first data mesage, ignore the subsequent ones
trigger.data = message.payload;
else if (message.app === 'payment') {
var payload = message.payload;
var asset = payload.asset || 'base';
payload.outputs.forEach(function (output) {
if (output.address === receiving_address) {
if (!trigger.outputs[asset])
trigger.outputs[asset] = 0;
trigger.outputs[asset] += output.amount; // in case there are several outputs
}
});
}
});
if (Object.keys(trigger.outputs).length === 0)
throw Error("no outputs to " + receiving_address);
return trigger;
}
// the result is onDone(objResponseUnit, bBounced)
function handleTrigger(conn, batch, trigger, params, stateVars, arrDefinition, address, mci, objMcUnit, bSecondary, arrResponses, onDone) {
var trigger_opts;
if (arguments.length === 1) {
trigger_opts = conn;
conn = trigger_opts.conn;
batch = trigger_opts.batch;
trigger = trigger_opts.trigger;
params = trigger_opts.params;
stateVars = trigger_opts.stateVars;
arrDefinition = trigger_opts.arrDefinition;
address = trigger_opts.address;
mci = trigger_opts.mci;
objMcUnit = trigger_opts.objMcUnit;
bSecondary = trigger_opts.bSecondary;
arrResponses = trigger_opts.arrResponses;
onDone = trigger_opts.onDone;
// extra options:
// trigger_opts.bAir
// trigger_opts.assocBalances
if (!!trigger_opts.bAir !== !!trigger_opts.assocBalances)
throw Error("assocBalances and bAir do not match");
}
else
trigger_opts = { conn, batch, trigger, params, stateVars, arrDefinition, address, mci, objMcUnit, bSecondary, arrResponses, onDone };
if (arrDefinition[0] !== 'autonomous agent')
throw Error('bad AA definition ' + arrDefinition);
if (!trigger.initial_address)
trigger.initial_address = trigger.address;
if (!trigger.initial_unit)
trigger.initial_unit = trigger.unit;
var error_message = '';
var responseVars = {};
var template = arrDefinition[1];
if (template.base_aa) { // parameterized AA
if (params && Object.keys(params).length > 0)
throw Error("unexpected params");
storage.readAADefinition(conn, template.base_aa, function (arrBaseDefinition) {
if (!arrBaseDefinition)
throw Error("base AA not found: " + template.base_aa);
console.log("redirecting to base AA " + template.base_aa + " with params " + JSON.stringify(template.params));
trigger_opts.params = template.params;
trigger_opts.arrDefinition = arrBaseDefinition;
handleTrigger(trigger_opts);
});
return;
}
var bounce_fees = template.bounce_fees || {base: constants.MIN_BYTES_BOUNCE_FEE};
if (!bounce_fees.base)
bounce_fees.base = constants.MIN_BYTES_BOUNCE_FEE;
// console.log('===== trigger.outputs', trigger.outputs);
var objValidationState = {
last_ball_mci: mci,
last_ball_timestamp: objMcUnit.timestamp,
mc_unit: objMcUnit.unit,
assocBalances: {},
number_of_responses: arrResponses.length,
arrPreviousAAResponses: arrResponses.map(objAAResponse => ({
unit_obj: objAAResponse.objResponseUnit || false,
trigger_unit: objAAResponse.trigger_unit,
trigger_address: objAAResponse.trigger_address,
aa_address: objAAResponse.aa_address,
})),
};
var bWithKeys = (mci >= constants.includeKeySizesUpgradeMci);
var FULL_TRANSFER_INPUT_SIZE = TRANSFER_INPUT_SIZE + (bWithKeys ? TRANSFER_INPUT_KEYS_SIZE : 0);
var byte_balance;
var storage_size;
var objStateUpdate;
var count = 0;
var originalStateVars = _.cloneDeep(stateVars);
var originalBalances;
if (bSecondary)
updateOriginalOldValues();
// add the coins received in the trigger
function updateInitialAABalances(cb) {
if (trigger_opts.assocBalances) {
if (!trigger_opts.assocBalances[address])
trigger_opts.assocBalances[address] = {};
originalBalances = _.cloneDeep(trigger_opts.assocBalances);
for (var asset in trigger.outputs)
trigger_opts.assocBalances[address][asset] = (trigger_opts.assocBalances[address][asset] || 0) + trigger.outputs[asset];
objValidationState.assocBalances = trigger_opts.assocBalances;
byte_balance = trigger_opts.assocBalances[address].base || 0;
storage_size = 0;
return cb();
}
objValidationState.assocBalances[address] = {};
var arrAssets = Object.keys(trigger.outputs);
conn.query(
"SELECT asset, balance FROM aa_balances WHERE address=?",
[address],
function (rows) {
var arrQueries = [];
// 1. update balances of existing assets
rows.forEach(function (row) {
if (constants.bTestnet && mci < testnetAAsDefinedByAAsAreActiveImmediatelyUpgradeMci)
reintroduceBalanceBug(address, row);
if (!trigger.outputs[row.asset]) {
objValidationState.assocBalances[address][row.asset] = row.balance;
return;
}
conn.addQuery(
arrQueries,
"UPDATE aa_balances SET balance=balance+? WHERE address=? AND asset=? ",
[trigger.outputs[row.asset], address, row.asset]
);
objValidationState.assocBalances[address][row.asset] = row.balance + trigger.outputs[row.asset];
});
// 2. insert balances of new assets
var arrExistingAssets = rows.map(function (row) { return row.asset; });
var arrNewAssets = _.difference(arrAssets, arrExistingAssets);
if (arrNewAssets.length > 0) {
var arrValues = arrNewAssets.map(function (asset) {
objValidationState.assocBalances[address][asset] = trigger.outputs[asset];
return "(" + conn.escape(address) + ", " + conn.escape(asset) + ", " + trigger.outputs[asset] + ")"
});
conn.addQuery(arrQueries, "INSERT INTO aa_balances (address, asset, balance) VALUES "+arrValues.join(', '));
}
byte_balance = objValidationState.assocBalances[address].base;
if (trigger.outputs.base === undefined && mci < constants.aa3UpgradeMci) // bug-compatible
byte_balance = undefined;
if (!bSecondary)
conn.addQuery(arrQueries, "SAVEPOINT initial_balances");
async.series(arrQueries, function () {
conn.query("SELECT storage_size FROM aa_addresses WHERE address=?", [address], function (rows) {
if (rows.length === 0)
throw Error("AA not found? " + address);
storage_size = rows[0].storage_size;
objValidationState.storage_size = storage_size;
cb();
});
});
}
);
}
function updateFinalAABalances(arrConsumedOutputs, objUnit, cb) {
if (trigger_opts.bAir)
throw Error("updateFinalAABalances shouldn't be called with bAir");
var assocDeltas = {};
var arrNewAssets = [];
arrConsumedOutputs.forEach(function (output) {
if (!assocDeltas[output.asset])
assocDeltas[output.asset] = 0;
assocDeltas[output.asset] -= output.amount;
// this might happen if there is another pending invocation of our AA that created the outputs we are spending now
if (!objValidationState.assocBalances[address][output.asset])
arrNewAssets.push(output.asset);
});
objUnit.messages.forEach(function (message) {
if (message.app !== 'payment')
return;
var payload = message.payload;
var asset = payload.asset || 'base';
payload.outputs.forEach(function (output) {
if (output.address !== address)
return;
if (!assocDeltas[asset]) { // it can happen if the asset was issued by AA
assocDeltas[asset] = 0;
arrNewAssets.push(asset);
}
assocDeltas[asset] += output.amount;
});
});
var arrQueries = [];
if (arrNewAssets.length > 0) {
var arrValues = arrNewAssets.map(function (asset) { return "(" + conn.escape(address) + ", " + conn.escape(asset) + ", 0)"; });
conn.addQuery(arrQueries, "INSERT "+conn.getIgnore()+" INTO aa_balances (address, asset, balance) VALUES "+arrValues.join(', '));
}
for (var asset in assocDeltas) {
if (assocDeltas[asset]) {
conn.addQuery(arrQueries, "UPDATE aa_balances SET balance=balance+? WHERE address=? AND asset=?", [assocDeltas[asset], address, asset]);
if (!objValidationState.assocBalances[address][asset])
objValidationState.assocBalances[address][asset] = 0;
objValidationState.assocBalances[address][asset] += assocDeltas[asset];
}
}
if (assocDeltas.base)
byte_balance += assocDeltas.base;
async.series(arrQueries, cb);
}
function evaluateAA(arrDefinition, cb) {
var locals = {};
var f = getFormula(arrDefinition[1].getters);
if (f === null) // no getters
return replace(arrDefinition, 1, '', locals, cb);
// evaluate getters before everything else as they can define a few functions
delete arrDefinition[1].getters;
var opts = {
conn: conn,
formula: f,
trigger: trigger,
params: params,
locals: locals,
stateVars: stateVars,
responseVars: responseVars,
bStatementsOnly: true,
bGetters: true,
objValidationState: objValidationState,
address: address
};
formulaParser.evaluate(opts, function (err, res) {
if (res === null)
return cb(err.bounce_message || "formula " + f + " failed: " + err);
replace(arrDefinition, 1, '', locals, cb);
});
}
// note that app=definition is also replaced using the current trigger and vars, its code has to generate "{}"-formulas in order to be dynamic
function replace(obj, name, path, locals, cb) {
count++;
if (count % 100 === 0) // interrupt the call stack
return setImmediate(replace, obj, name, path, locals, cb);
locals = _.clone(locals);
var value = obj[name];
if (typeof name === 'string') {
var f = getFormula(name);
if (f !== null) {
var opts = {
conn: conn,
formula: f,
trigger: trigger,
params: params,
locals: _.clone(locals),
stateVars: stateVars,
responseVars: responseVars,
objValidationState: objValidationState,
address: address
};
return formulaParser.evaluate(opts, function (err, res) {
if (res === null)
return cb(err.bounce_message || "formula " + f + " failed: "+err);
delete obj[name];
if (res === '')
return cb(); // the key is just removed from the object
if (typeof res !== 'string')
return cb("result of formula " + name + " is not a string: " + res);
if (ValidationUtils.hasOwnProperty(obj, res))
return cb("duplicate key " + res + " calculated from " + name);
if (getFormula(res) !== null)
return cb("calculated value of " + name + " looks like a formula again: " + res);
assignField(obj, res, value);
replace(obj, res, path, locals, cb);
});
}
}
if (typeof value === 'number' || typeof value === 'boolean')
return cb();
if (typeof value === 'string') {
var f = getFormula(value);
if (f === null)
return cb();
// console.log('path', path, 'name', name, 'f', f);
var bStateUpdates = (path === '/messages/state');
if (bStateUpdates) {
if (objStateUpdate)
return cb("second state update formula: " + f + ", existing: " + objStateUpdate.formula);
objStateUpdate = {formula: f, locals: locals};
return cb();
}
var opts = {
conn: conn,
formula: f,
trigger: trigger,
params: params,
locals: locals,
stateVars: stateVars,
responseVars: responseVars,
objValidationState: objValidationState,
address: address,
bObjectResultAllowed: true
};
formulaParser.evaluate(opts, function (err, res) {
// console.log('--- f', f, '=', res, typeof res);
if (res === null)
return cb(err.bounce_message || "formula " + f + " failed: "+err);
if (res === '' || isEmptyObjectOrArray(res)) { // signals that the key should be removed (only empty string or array or object, cannot be false as it is a valid value for asset properties)
if (typeof name === 'string')
delete obj[name];
else
assignField(obj, name, null);
}
else
assignField(obj, name, res);
cb();
});
}
else if (hasCases(value)) {
var thecase;
async.eachSeries(
value.cases,
function (acase, cb2) {
if (!("if" in acase)) {
thecase = acase;
return cb2('done');
}
var f = getFormula(acase.if);
if (f === null)
return cb2("case if is not a formula: " + acase.if);
var locals_tmp = _.clone(locals); // separate copy for each iteration of eachSeries
var opts = {
conn: conn,
formula: f,
trigger: trigger,
params: params,
locals: locals_tmp,
stateVars: stateVars,
responseVars: responseVars,
objValidationState: objValidationState,
address: address
};
formulaParser.evaluate(opts, function (err, res) {
if (res === null)
return cb2(err.bounce_message || "formula " + acase.if + " failed: " + err);
if (res) {
thecase = acase;
locals = locals_tmp;
return cb2('done');
}
cb2(); // try next
});
},
function (err) {
if (!err)
return cb("neither case is true in " + name);
if (err !== 'done')
return cb(err);
var replacement_value = thecase[name];
if (!replacement_value)
throw Error("a case was selected but no replacement value in " + name);
assignField(obj, name, replacement_value);
if (!thecase.init)
return replace(obj, name, path, locals, cb);
var f = getFormula(thecase.init);
if (f === null)
return cb("case init is not a formula: " + thecase.init);
var opts = {
conn: conn,
formula: f,
trigger: trigger,
params: params,
locals: locals,
stateVars: stateVars,
responseVars: responseVars,
bStatementsOnly: true,
objValidationState: objValidationState,
address: address
};
formulaParser.evaluate(opts, function (err, res) {
if (res === null)
return cb(err.bounce_message || "formula " + f + " failed: " + err);
replace(obj, name, path, locals, cb);
});
}
);
}
else if (typeof value === 'object' && (typeof value.if === 'string' || typeof value.init === 'string')) {
function evaluateIf(cb2) {
if (typeof value.if !== 'string')
return cb2();
var f = getFormula(value.if);
if (f === null)
return cb("if is not a formula: " + value.if);
var opts = {
conn: conn,
formula: f,
trigger: trigger,
params: params,
locals: locals,
stateVars: stateVars,
responseVars: responseVars,
objValidationState: objValidationState,
address: address
};
formulaParser.evaluate(opts, function (err, res) {
if (res === null)
return cb(err.bounce_message || "formula " + value.if + " failed: " + err);
if (!res) {
if (typeof name === 'string')
delete obj[name];
else
assignField(obj, name, null); // will be removed
return cb();
}
delete value.if;
cb2();
});
}
evaluateIf(function () {
if (typeof value.init !== 'string')
return replace(obj, name, path, locals, cb);
var f = getFormula(value.init);
if (f === null)
return cb("init is not a formula: " + value.init);
var opts = {
conn: conn,
formula: f,
trigger: trigger,
params: params,
locals: locals,
stateVars: stateVars,
responseVars: responseVars,
bStatementsOnly: true,
objValidationState: objValidationState,
address: address
};
formulaParser.evaluate(opts, function (err, res) {
if (res === null)
return cb(err.bounce_message || "formula " + value.init + " failed: " + err);
delete value.init;
replace(obj, name, path, locals, cb);
});
});
}
else if (Array.isArray(value)) {
async.eachOfSeries(
value,
function (elem, i, cb2) {
replace(value, i, path, _.clone(locals), cb2);
},
function (err) {
if (err)
return cb(err);
var replacement_value = value.filter(function (elem) { return (elem !== null); });
if (replacement_value.length === 0) {
if (typeof name === 'string')
delete obj[name];
else
assignField(obj, name, null); // to be removed
return cb();
}
assignField(obj, name, replacement_value);
cb();
}
);
}
else if (isNonemptyObject(value)) {
async.eachSeries(
Object.keys(value),
function (key, cb2) {
replace(value, key, path + '/' + key, _.clone(locals), cb2);
},
function (err) {
if (err)
return cb(err);
if (Object.keys(value).length === 0) {
if (typeof name === 'string')
delete obj[name];
else
assignField(obj, name, null); // to be removed
return cb();
}
cb();
}
);
}
else
throw Error('unknown type of value in ' + name);
}
function pickParents(handleParents) {
if (trigger_opts.bAir)
throw Error("pickParents shouldn't be called with bAir");
// first look for a chain of AAs stemming from the MC unit
conn.query(
"SELECT units.unit \n\
FROM units CROSS JOIN unit_authors USING(unit) CROSS JOIN aa_addresses USING(address) \n\
WHERE latest_included_mc_index=? AND aa_addresses.mci<=? \n\
ORDER BY level DESC LIMIT 1",
[mci, mci],
function (rows) {
if (rows.length > 0)
return handleParents([rows[0].unit]);
// next, check if there is an AA stemming from a recent MCI
conn.query(
"SELECT units.unit, latest_included_mc_index \n\
FROM units CROSS JOIN unit_authors USING(unit) CROSS JOIN aa_addresses USING(address) \n\
WHERE (main_chain_index>? OR main_chain_index IS NULL) AND aa_addresses.mci<=? \n\
ORDER BY latest_included_mc_index DESC, level DESC LIMIT 1",
[mci, mci],
function (rows) {
if (rows.length > 0) {
var row = rows[0];
if (row.latest_included_mc_index >= mci)
throw Error("limci of last AA > mci");
return handleParents([row.unit, objMcUnit.unit].sort());
}
handleParents([objMcUnit.unit]);
}
);
}
);
}
var bBouncing = false;
function bounce(error) {
console.log('bouncing with error', error, new Error().stack);
objStateUpdate = null;
error_message = error_message ? (error_message + ', then ' + error) : error;
if (trigger_opts.bAir) {
assignObject(stateVars, originalStateVars); // restore state vars
assignObject(trigger_opts.assocBalances, originalBalances); // restore balances
if (!bSecondary) {
for (let a in trigger.outputs)
if (bounce_fees[a])
trigger_opts.assocBalances[address][a] = (trigger_opts.assocBalances[address][a] || 0) + bounce_fees[a];
}
}
if (bBouncing)
return finish(null);
bBouncing = true;
if (bSecondary)
return finish(null);
if ((trigger.outputs.base || 0) < bounce_fees.base)
return finish(null);
var messages = [];
for (var asset in trigger.outputs) {
var amount = trigger.outputs[asset];
var fee = bounce_fees[asset] || 0;
if (fee > amount)
return finish(null);
if (fee === amount)
continue;
var bounced_amount = amount - fee;
messages.push({app: 'payment', payload: {asset: asset, outputs: [{address: trigger.address, amount: bounced_amount}]}});
}
if (messages.length === 0)
return finish(null);
sendUnit(messages);
}
// with bAir option, we don't send or save a real unit
function sendDummyUnit(messages) {
console.log('AA ' + address + ': send dummy unit with messages', JSON.stringify(messages, null, '\t'));
var objUnit = messages.length ? {
unit: 'dummy' + Date.now(),
authors: [{ address: address }],
messages: messages,
} : null;
executeStateUpdateFormula(objUnit, function (err) {
if (err)
return bounce(err);
// update balances
var arrOutputAddresses = [];
messages.forEach(message => {
if (message.app !== 'payment')
return;
var asset = message.payload.asset || 'base';
message.payload.outputs.forEach(output => {
if (output.amount !== 0 && arrOutputAddresses.indexOf(output.address) === -1)
arrOutputAddresses.push(output.address);
if (!trigger_opts.assocBalances[address][asset])
trigger_opts.assocBalances[address][asset] = 0;
if (output.amount === undefined) // send all
output.amount = trigger_opts.assocBalances[address][asset];
// deduct from this AA's balance. It can get negative if we are issuing coins but in this case balance[] is probably meaningless
trigger_opts.assocBalances[address][asset] -= output.amount;
});
});
if (arrOutputAddresses.length === 0)
return finish(objUnit);
if (trigger_opts.assocBalances[address].base < 0)
return bounce("not enough balance in base");
let arrAssetsWithNegativeBalances = [];
for (let asset in trigger_opts.assocBalances[address])
if (asset !== 'base' && trigger_opts.assocBalances[address][asset] < 0)
arrAssetsWithNegativeBalances.push(asset);
async.eachSeries(
arrAssetsWithNegativeBalances,
function (asset, cb) {
storage.loadAssetWithListOfAttestedAuthors(conn, asset, mci, [address], true, function (err, objAsset) {
if (err)
return cb(err);
if (objAsset.issued_by_definer_only && address !== objAsset.definer_address)
return cb("not enough balance in " + asset); // and we are not the issuer
cb();
});
},
function (err) {
if (err)
return bounce(err);
fixStateVars();
addResponse(objUnit, function () {
handleSecondaryTriggers(objUnit, arrOutputAddresses);
});
}
);
});
}
function sendUnit(messages) {
if (trigger_opts.bAir)
return sendDummyUnit(messages);
console.log('send unit with messages', JSON.stringify(messages, null, '\t'));
var arrUsedOutputIds = [];
var arrConsumedOutputs = [];
function completeMessage(message) {
message.payload_location = 'inline';
message.payload_hash = objectHash.getBase64Hash(message.payload, true);
}
function completePaymentPayload(payload, additional_amount, cb) {
var asset = payload.asset || null;
var is_base = (asset === null) ? 1 : 0;
if (!payload.inputs && bWithKeys && is_base)
additional_amount += "inputs".length;
payload.inputs = [];
var total_amount = 0;
var send_all_outputs = payload.outputs.filter(function (output) { return (output.amount === undefined); });
if (send_all_outputs.length > 1)
return cb(send_all_outputs.length + " send-all outputs");
var send_all_output = send_all_outputs[0];
// send-all output looks like {address: "BASE32"}, its size is 32 since it has no amount.
// remove the send-all output from size calculation, it might be added later
if (send_all_output && is_base){
additional_amount -= 32 + (bWithKeys ? "address".length : 0);
// we add a change output to AA to keep balance above storage_size
if (storage_size > FULL_TRANSFER_INPUT_SIZE && mci >= constants.aaStorageSizeUpgradeMci){
additional_amount += OUTPUT_SIZE + (bWithKeys ? OUTPUT_KEYS_SIZE : 0);
payload.outputs.push({ address: address, amount: storage_size });
}
}
var target_amount = payload.outputs.reduce(function (acc, output) { return acc + (output.amount || 0); }, additional_amount);
var bFound = false;
function iterateUnspentOutputs(rows) {
for (var i = 0; i < rows.length; i++){
var row = rows[i];
var input = { unit: row.unit, message_index: row.message_index, output_index: row.output_index };
arrUsedOutputIds.push(row.output_id);
arrConsumedOutputs.push({asset: asset || 'base', amount: row.amount});
payload.inputs.push(input);
total_amount += row.amount;
if (is_base)
target_amount += FULL_TRANSFER_INPUT_SIZE;
if (total_amount < target_amount)
continue;
if (total_amount === target_amount && payload.outputs.length > 0) {
bFound = true;
if (send_all_output)
continue;
else
break;
}
var additional_output_size = is_base ? OUTPUT_SIZE + (bWithKeys ? OUTPUT_KEYS_SIZE : 0) : 0; // the same for send-all
var change_amount = total_amount - (target_amount + additional_output_size);