-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage.js
1989 lines (1830 loc) · 72.7 KB
/
storage.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 async = require('async');
var _ = require('lodash');
var db = require('./db.js');
var conf = require('./conf.js');
var objectHash = require("./object_hash.js");
var constants = require("./constants.js");
var mutex = require('./mutex.js');
var archiving = require('./archiving.js');
var eventBus = require('./event_bus.js');
var profiler = require('./profiler.js');
var ValidationUtils = require("./validation_utils.js");
var testnetAssetsDefinedByAAsAreVisibleImmediatelyUpgradeMci = 1167000;
var bCordova = (typeof window === 'object' && window.cordova);
var MAX_INT32 = Math.pow(2, 31) - 1;
var genesis_ball = objectHash.getBallHash(constants.GENESIS_UNIT);
var MAX_ITEMS_IN_CACHE = 300;
var assocKnownUnits = {};
var assocCachedUnits = {};
var assocCachedUnitAuthors = {};
var assocCachedUnitWitnesses = {};
var assocCachedAssetInfos = {};
var assocUnstableUnits = {};
var assocStableUnits = {};
var assocStableUnitsByMci = {};
var assocBestChildren = {};
var assocHashTreeUnitsByBall = {};
var assocUnstableMessages = {};
var min_retrievable_mci = null;
initializeMinRetrievableMci();
let last_aa_response_id = null;
initializeLastAAResponseId();
function readUnit(unit, cb) {
if (!cb)
return new Promise(resolve => readUnit(unit, resolve));
readJoint(db, unit, {
ifFound: function (objJoint) {
cb(objJoint.unit);
},
ifNotFound: function () {
cb(null);
}
});
}
function readJointJsonFromStorage(conn, unit, cb) {
var kvstore = require('./kvstore.js');
if (!bCordova)
return kvstore.get('j\n' + unit, cb);
conn.query("SELECT json FROM joints WHERE unit=?", [unit], function (rows) {
cb((rows.length === 0) ? null : rows[0].json);
});
}
function readJoint(conn, unit, callbacks, bSql) {
if (bSql)
return readJointDirectly(conn, unit, callbacks);
readJointJsonFromStorage(conn, unit, function(strJoint){
if (!strJoint)
return callbacks.ifNotFound();
var objJoint = JSON.parse(strJoint);
// light wallets don't have last_ball, don't verify their hashes
if (!conf.bLight && !isCorrectHash(objJoint.unit, unit))
throw Error("wrong hash of unit "+unit);
conn.query("SELECT main_chain_index, "+conn.getUnixTimestamp("creation_date")+" AS timestamp, sequence FROM units WHERE unit=?", [unit], function(rows){
if (rows.length === 0)
throw Error("unit found in kv but not in sql: "+unit);
var row = rows[0];
if (objJoint.unit.version === constants.versionWithoutTimestamp)
objJoint.unit.timestamp = parseInt(row.timestamp);
objJoint.unit.main_chain_index = row.main_chain_index;
callbacks.ifFound(objJoint, row.sequence);
});
});
/*
if (!conf.bSaveJointJson)
return readJointDirectly(conn, unit, callbacks);
conn.query("SELECT json FROM joints WHERE unit=?", [unit], function(rows){
if (rows.length === 0)
return readJointDirectly(conn, unit, callbacks);
var objJoint = JSON.parse(rows[0].json);
if (!objJoint.ball){ // got there because of an old bug
conn.query("DELETE FROM joints WHERE unit=?", [unit]);
return readJointDirectly(conn, unit, callbacks);
}
callbacks.ifFound(objJoint);
});
*/
}
function readJointDirectly(conn, unit, callbacks, bRetrying) {
// console.log("\nreading unit "+unit);
if (min_retrievable_mci === null){
console.log("min_retrievable_mci not known yet");
setTimeout(function(){
readJointDirectly(conn, unit, callbacks);
}, 1000);
return;
}
//profiler.start();
conn.query(
"SELECT units.unit, version, alt, witness_list_unit, last_ball_unit, balls.ball AS last_ball, is_stable, \n\
content_hash, headers_commission, payload_commission, main_chain_index, timestamp, "+conn.getUnixTimestamp("units.creation_date")+" AS received_timestamp \n\
FROM units LEFT JOIN balls ON last_ball_unit=balls.unit WHERE units.unit=?",
[unit],
function(unit_rows){
if (unit_rows.length === 0){
//profiler.stop('read');
return callbacks.ifNotFound();
}
var objUnit = unit_rows[0];
var objJoint = {unit: objUnit};
var main_chain_index = objUnit.main_chain_index;
//delete objUnit.main_chain_index;
objUnit.timestamp = parseInt((objUnit.version === constants.versionWithoutTimestamp) ? objUnit.received_timestamp : objUnit.timestamp);
delete objUnit.received_timestamp;
var bFinalBad = !!objUnit.content_hash;
var bStable = objUnit.is_stable;
delete objUnit.is_stable;
objectHash.cleanNulls(objUnit);
var bVoided = (objUnit.content_hash && main_chain_index < min_retrievable_mci);
var bRetrievable = (main_chain_index >= min_retrievable_mci || main_chain_index === null);
if (!conf.bLight && !objUnit.last_ball && !isGenesisUnit(unit))
throw Error("no last ball in unit "+JSON.stringify(objUnit));
// unit hash verification below will fail if:
// 1. the unit was received already voided, i.e. its messages are stripped and content_hash is set
// 2. the unit is still retrievable (e.g. we are syncing)
// In this case, bVoided=false hence content_hash will be deleted but the messages are missing
if (bVoided){
//delete objUnit.last_ball;
//delete objUnit.last_ball_unit;
delete objUnit.headers_commission;
delete objUnit.payload_commission;
}
else
delete objUnit.content_hash;
async.series([
function(callback){ // parents
conn.query(
"SELECT parent_unit \n\
FROM parenthoods \n\
WHERE child_unit=? \n\
ORDER BY parent_unit",
[unit],
function(rows){
if (rows.length === 0)
return callback();
objUnit.parent_units = rows.map(function(row){ return row.parent_unit; });
callback();
}
);
},
function(callback){ // ball
if (bRetrievable && !isGenesisUnit(unit))
return callback();
// include the .ball field even if it is not stable yet, because its parents might have been changed
// and the receiver should not attempt to verify them
conn.query("SELECT ball FROM balls WHERE unit=?", [unit], function(rows){
if (rows.length === 0)
return callback();
objJoint.ball = rows[0].ball;
callback();
});
},
function(callback){ // skiplist
if (bRetrievable)
return callback();
conn.query("SELECT skiplist_unit FROM skiplist_units WHERE unit=? ORDER BY skiplist_unit", [unit], function(rows){
if (rows.length === 0)
return callback();
objJoint.skiplist_units = rows.map(function(row){ return row.skiplist_unit; });
callback();
});
},
function(callback){ // witnesses
conn.query("SELECT address FROM unit_witnesses WHERE unit=? ORDER BY address", [unit], function(rows){
if (rows.length > 0)
objUnit.witnesses = rows.map(function(row){ return row.address; });
callback();
});
},
function(callback){ // earned_headers_commission_recipients
if (bVoided)
return callback();
conn.query("SELECT address, earned_headers_commission_share FROM earned_headers_commission_recipients \
WHERE unit=? ORDER BY address",
[unit],
function(rows){
if (rows.length > 0)
objUnit.earned_headers_commission_recipients = rows;
callback();
}
);
},
function(callback){ // authors
conn.query("SELECT address, definition_chash FROM unit_authors WHERE unit=? ORDER BY address", [unit], function(rows){
objUnit.authors = [];
async.eachSeries(
rows,
function(row, cb){
var author = {address: row.address};
function onAuthorDone(){
objUnit.authors.push(author);
cb();
}
if (bVoided)
return onAuthorDone();
author.authentifiers = {};
conn.query(
"SELECT path, authentifier FROM authentifiers WHERE unit=? AND address=?",
[unit, author.address],
function(sig_rows){
for (var i=0; i<sig_rows.length; i++)
author.authentifiers[sig_rows[i].path] = sig_rows[i].authentifier;
// if definition_chash is defined:
if (row.definition_chash){
readDefinition(conn, row.definition_chash, {
ifFound: function(arrDefinition){
author.definition = arrDefinition;
onAuthorDone();
},
ifDefinitionNotFound: function(definition_chash){
throw Error("definition "+definition_chash+" not defined");
}
});
}
else
onAuthorDone();
}
);
},
function(){
callback();
}
);
});
},
function(callback){ // messages
if (bVoided)
return callback();
conn.query(
"SELECT app, payload_hash, payload_location, payload, payload_uri, payload_uri_hash, message_index \n\
FROM messages WHERE unit=? ORDER BY message_index", [unit],
function(rows){
if (rows.length === 0){
// likely voided
// if (conf.bLight)
// throw new Error("no messages in unit "+unit);
return callback(); // in full clients, any errors will be caught by verifying unit hash
}
objUnit.messages = [];
async.eachSeries(
rows,
function(row, cb){
var objMessage = row;
var message_index = row.message_index;
delete objMessage.message_index;
objectHash.cleanNulls(objMessage);
objUnit.messages.push(objMessage);
function addSpendProofs(){
conn.query(
"SELECT spend_proof, address FROM spend_proofs WHERE unit=? AND message_index=? ORDER BY spend_proof_index",
[unit, message_index],
function(proof_rows){
if (proof_rows.length === 0)
return cb();
objMessage.spend_proofs = [];
for (var i=0; i<proof_rows.length; i++){
var objSpendProof = proof_rows[i];
if (objUnit.authors.length === 1) // single-authored
delete objSpendProof.address;
objMessage.spend_proofs.push(objSpendProof);
}
cb();
}
);
}
if (objMessage.payload_location !== "inline")
return addSpendProofs();
switch(objMessage.app){
case "address_definition_change":
conn.query(
"SELECT definition_chash, address FROM address_definition_changes WHERE unit=? AND message_index=?",
[unit, message_index],
function(dch_rows){
if (dch_rows.length === 0)
throw Error("no definition change?");
objMessage.payload = dch_rows[0];
if (objUnit.authors.length === 1) // single-authored
delete objMessage.payload.address;
addSpendProofs();
}
);
break;
case "poll":
conn.query(
"SELECT question FROM polls WHERE unit=? AND message_index=?", [unit, message_index],
function(poll_rows){
if (poll_rows.length !== 1)
throw Error("no poll question or too many?");
objMessage.payload = {question: poll_rows[0].question};
conn.query("SELECT choice FROM poll_choices WHERE unit=? ORDER BY choice_index", [unit], function(ch_rows){
if (ch_rows.length === 0)
throw Error("no choices?");
objMessage.payload.choices = ch_rows.map(function(choice_row){ return choice_row.choice; });
addSpendProofs();
});
}
);
break;
case "vote":
conn.query(
"SELECT poll_unit, choice FROM votes WHERE unit=? AND message_index=?", [unit, message_index],
function(vote_rows){
if (vote_rows.length !== 1)
throw Error("no vote choice or too many?");
objMessage.payload = {unit: vote_rows[0].poll_unit, choice: vote_rows[0].choice};
addSpendProofs();
}
);
break;
case "asset":
conn.query(
"SELECT cap, is_private, is_transferrable, auto_destroy, fixed_denominations, \n\
issued_by_definer_only, cosigned_by_definer, spender_attested, \n\
issue_condition, transfer_condition \n\
FROM assets WHERE unit=? AND message_index=?",
[unit, message_index],
function(asset_rows){
if (asset_rows.length !== 1)
throw Error("no asset or too many?");
objMessage.payload = asset_rows[0];
objectHash.cleanNulls(objMessage.payload);
objMessage.payload.is_private = !!objMessage.payload.is_private;
objMessage.payload.is_transferrable = !!objMessage.payload.is_transferrable;
objMessage.payload.auto_destroy = !!objMessage.payload.auto_destroy;
objMessage.payload.fixed_denominations = !!objMessage.payload.fixed_denominations;
objMessage.payload.issued_by_definer_only = !!objMessage.payload.issued_by_definer_only;
objMessage.payload.cosigned_by_definer = !!objMessage.payload.cosigned_by_definer;
objMessage.payload.spender_attested = !!objMessage.payload.spender_attested;
if (objMessage.payload.issue_condition)
objMessage.payload.issue_condition = JSON.parse(objMessage.payload.issue_condition);
if (objMessage.payload.transfer_condition)
objMessage.payload.transfer_condition = JSON.parse(objMessage.payload.transfer_condition);
var addAttestors = function(next){
if (!objMessage.payload.spender_attested)
return next();
conn.query(
"SELECT attestor_address FROM asset_attestors \n\
WHERE unit=? AND message_index=? ORDER BY attestor_address",
[unit, message_index],
function(att_rows){
if (att_rows.length === 0)
throw Error("no attestors?");
objMessage.payload.attestors = att_rows.map(function(att_row){
return att_row.attestor_address;
});
next();
}
);
};
var addDenominations = function(next){
if (!objMessage.payload.fixed_denominations)
return next();
conn.query(
"SELECT denomination, count_coins FROM asset_denominations \n\
WHERE asset=? ORDER BY denomination",
[unit],
function(denom_rows){
if (denom_rows.length === 0)
throw Error("no denominations?");
objMessage.payload.denominations = denom_rows.map(function(denom_row){
var denom = {denomination: denom_row.denomination};
if (denom_row.count_coins)
denom.count_coins = denom_row.count_coins;
return denom;
});
next();
}
);
};
async.series([addAttestors, addDenominations], addSpendProofs);
}
);
break;
case "asset_attestors":
conn.query(
"SELECT attestor_address, asset FROM asset_attestors \n\
WHERE unit=? AND message_index=? ORDER BY attestor_address",
[unit, message_index],
function(att_rows){
if (att_rows.length === 0)
throw Error("no attestors?");
objMessage.payload = {asset: att_rows[0].asset};
if (att_rows.length > 1
&& att_rows.some(function(att_row){ return (att_row.asset !== objMessage.payload.asset) }))
throw Error("different assets in attestor list");
objMessage.payload.attestors = att_rows.map(function(att_row){ return att_row.attestor_address;});
addSpendProofs();
}
);
break;
case "data_feed":
conn.query(
"SELECT feed_name, `value`, int_value FROM data_feeds WHERE unit=? AND message_index=?", [unit, message_index],
function(df_rows){
if (df_rows.length === 0)
throw Error("no data feed?");
objMessage.payload = {};
df_rows.forEach(function(df_row){
objMessage.payload[df_row.feed_name] =
(typeof df_row.value === 'string') ? df_row.value : Number(df_row.int_value);
});
addSpendProofs();
}
);
break;
case "profile":
case "attestation": // maybe later we'll store profiles and attestations in some structured form
case "data":
case "definition_template":
objMessage.payload = JSON.parse(objMessage.payload);
addSpendProofs();
break;
case "payment":
objMessage.payload = {};
var prev_asset;
var prev_denomination;
var readInputs = function(cb2){
conn.query(
"SELECT type, denomination, assets.fixed_denominations, \n\
src_unit AS unit, src_message_index AS message_index, src_output_index AS output_index, \n\
from_main_chain_index, to_main_chain_index, serial_number, amount, address, asset \n\
FROM inputs \n\
LEFT JOIN assets ON asset=assets.unit \n\
WHERE inputs.unit=? AND inputs.message_index=? \n\
ORDER BY input_index",
[unit, message_index],
function(input_rows){
objMessage.payload.inputs = [];
for (var i=0; i<input_rows.length; i++){
var input = input_rows[i];
if (!input.address && !conf.bLight) // may be NULL for light (light clients are reading units e.g. after receiving payment notification)
throw Error("readJoint: input address is NULL");
var asset = input.asset;
var denomination = input.denomination;
if (i>0){
if (asset !== prev_asset)
throw Error("different assets in inputs?");
if (denomination !== prev_denomination)
throw Error("different denominations in inputs?");
}
if (i === 0 && asset){
objMessage.payload.asset = asset;
if (input.fixed_denominations)
objMessage.payload.denomination = denomination;
}
delete input.asset;
delete input.denomination;
delete input.fixed_denominations;
objectHash.cleanNulls(input);
if (input.type === "transfer" || objUnit.authors.length === 1)
delete input.address;
if (input.type === "transfer")
delete input.type;
objMessage.payload.inputs.push(input);
if (i === 0){
prev_asset = asset;
prev_denomination = denomination;
}
}
cb2();
}
);
};
var readOutputs = function(cb2){
objMessage.payload.outputs = [];
conn.query( // we don't select blinding because it's absent on public payments
"SELECT address, amount, asset, denomination \n\
FROM outputs WHERE unit=? AND message_index=? ORDER BY output_index",
[unit, message_index],
function(output_rows){
for (var i=0; i<output_rows.length; i++){
var output = output_rows[i];
if (output.asset !== prev_asset)
throw Error("different assets in outputs?");
if (output.denomination !== prev_denomination)
throw Error("different denominations in outputs?");
delete output.asset;
delete output.denomination;
objMessage.payload.outputs.push(output);
}
cb2();
}
);
};
async.series(
[readInputs, readOutputs],
addSpendProofs
);
break;
default:
addSpendProofs();
}
},
callback
);
} // message rows
);
}
], function(){
//profiler.stop('read');
// verify unit hash. Might fail if the unit was archived while reading, in this case retry
// light wallets don't have last_ball, don't verify their hashes
if (!conf.bLight && !isCorrectHash(objUnit, unit)){
if (bRetrying)
throw Error("unit hash verification failed, unit: "+unit+", objUnit: "+JSON.stringify(objUnit));
console.log("unit hash verification failed, will retry");
return setTimeout(function(){
readJointDirectly(conn, unit, callbacks, true);
}, 60*1000);
}
if (!conf.bSaveJointJson || !bStable || (bFinalBad && bRetrievable) || bRetrievable)
return callbacks.ifFound(objJoint);
conn.query("INSERT "+db.getIgnore()+" INTO joints (unit, json) VALUES (?,?)", [unit, JSON.stringify(objJoint)], function(){
callbacks.ifFound(objJoint);
});
});
}
);
}
function isCorrectHash(objUnit, unit){
try{
return (objectHash.getUnitHash(objUnit) === unit);
}
catch(e){
//throw Error(e.message);
console.log('storage.isCorrectHash: '+ e.message);
return false;
}
}
// add .ball even if it is not retrievable
function readJointWithBall(conn, unit, handleJoint) {
readJoint(conn, unit, {
ifNotFound: function(){
throw Error("joint not found, unit "+unit);
},
ifFound: function(objJoint){
if (objJoint.ball)
return handleJoint(objJoint);
conn.query("SELECT ball FROM balls WHERE unit=?", [unit], function(rows){
if (rows.length === 1)
objJoint.ball = rows[0].ball;
handleJoint(objJoint);
});
}
});
}
function readWitnessList(conn, unit, handleWitnessList, bAllowEmptyList){
var arrWitnesses = assocCachedUnitWitnesses[unit];
if (arrWitnesses)
return handleWitnessList(arrWitnesses);
conn.query("SELECT address FROM unit_witnesses WHERE unit=? ORDER BY address", [unit], function(rows){
if (!bAllowEmptyList && rows.length === 0)
throw Error("witness list of unit "+unit+" not found");
if (rows.length > 0 && rows.length !== constants.COUNT_WITNESSES)
throw Error("wrong number of witnesses in unit "+unit);
arrWitnesses = rows.map(function(row){ return row.address; });
if (rows.length > 0)
assocCachedUnitWitnesses[unit] = arrWitnesses;
handleWitnessList(arrWitnesses);
});
}
function readWitnesses(conn, unit, handleWitnessList){
if (!handleWitnessList)
return new Promise(resolve => readWitnesses(conn, unit, resolve));
var arrWitnesses = assocCachedUnitWitnesses[unit];
if (arrWitnesses)
return handleWitnessList(arrWitnesses);
conn.query("SELECT witness_list_unit FROM units WHERE unit=?", [unit], function(rows){
if (rows.length === 0)
throw Error("unit "+unit+" not found");
var witness_list_unit = rows[0].witness_list_unit;
readWitnessList(conn, witness_list_unit ? witness_list_unit : unit, function(arrWitnesses){
assocCachedUnitWitnesses[unit] = arrWitnesses;
handleWitnessList(arrWitnesses);
});
});
}
function determineIfWitnessAddressDefinitionsHaveReferences(conn, arrWitnesses, handleResult){
conn.query(
"SELECT 1 FROM address_definition_changes JOIN definitions USING(definition_chash) \n\
WHERE address IN(?) AND has_references=1 \n\
UNION \n\
SELECT 1 FROM definitions WHERE definition_chash IN(?) AND has_references=1 \n\
LIMIT 1",
[arrWitnesses, arrWitnesses],
function(rows){
handleResult(rows.length > 0);
}
);
}
function determineWitnessedLevelAndBestParent(conn, arrParentUnits, arrWitnesses, handleWitnessedLevelAndBestParent){
var arrCollectedWitnesses = [];
var my_best_parent_unit;
var count = 0;
function addWitnessesAndGoUp(start_unit){
count++;
if (count % 100 === 0)
return setImmediate(addWitnessesAndGoUp, start_unit);
readStaticUnitProps(conn, start_unit, function (props) {
var best_parent_unit = props.best_parent_unit;
var level = props.level;
if (level === null)
throw Error("null level in updateWitnessedLevel");
if (level === 0) // genesis
return handleWitnessedLevelAndBestParent(0, my_best_parent_unit);
readUnitAuthors(conn, start_unit, function(arrAuthors){
for (var i=0; i<arrAuthors.length; i++){
var address = arrAuthors[i];
if (arrWitnesses.indexOf(address) !== -1 && arrCollectedWitnesses.indexOf(address) === -1)
arrCollectedWitnesses.push(address);
}
(arrCollectedWitnesses.length < constants.MAJORITY_OF_WITNESSES)
? addWitnessesAndGoUp(best_parent_unit) : handleWitnessedLevelAndBestParent(level, my_best_parent_unit);
});
});
}
determineBestParent(conn, {parent_units: arrParentUnits, witness_list_unit: 'none'}, arrWitnesses, function(best_parent_unit){
if (!best_parent_unit)
return handleWitnessedLevelAndBestParent();
// throw Error("no best parent of "+arrParentUnits.join(', ')+", witnesses "+arrWitnesses.join(', '));
my_best_parent_unit = best_parent_unit;
addWitnessesAndGoUp(best_parent_unit);
});
}
/*
function readWitnessesOnMcUnit(conn, main_chain_index, handleWitnesses){
conn.query( // we read witnesses from MC unit (users can cheat with side-chains)
"SELECT address \n\
FROM units \n\
JOIN unit_witnesses ON(units.unit=unit_witnesses.unit OR units.witness_list_unit=unit_witnesses.unit) \n\
WHERE main_chain_index=? AND is_on_main_chain=1",
[main_chain_index],
function(witness_rows){
if (witness_rows.length === 0)
throw "no witness list on MC unit "+main_chain_index;
if (witness_rows.length !== constants.COUNT_WITNESSES)
throw "wrong number of witnesses on MC unit "+main_chain_index;
var arrWitnesses = witness_rows.map(function(witness_row){ return witness_row.address; });
handleWitnesses(arrWitnesses);
}
);
}*/
function readDefinitionChashByAddress(conn, address, max_mci, handle){
if (!handle)
return new Promise(resolve => readDefinitionChashByAddress(conn, address, max_mci, resolve));
if (max_mci == null || max_mci == undefined)
max_mci = MAX_INT32;
// try to find last definition change, otherwise definition_chash=address
conn.query(
"SELECT definition_chash FROM address_definition_changes CROSS JOIN units USING(unit) \n\
WHERE address=? AND is_stable=1 AND sequence='good' AND main_chain_index<=? ORDER BY main_chain_index DESC LIMIT 1",
[address, max_mci],
function(rows){
var definition_chash = (rows.length > 0) ? rows[0].definition_chash : address;
handle(definition_chash);
});
}
// max_mci must be stable
function readDefinitionByAddress(conn, address, max_mci, callbacks){
readDefinitionChashByAddress(conn, address, max_mci, function(definition_chash){
readDefinitionAtMci(conn, definition_chash, max_mci, callbacks);
});
}
// max_mci must be stable
function readDefinitionAtMci(conn, definition_chash, max_mci, callbacks){
var sql = "SELECT definition FROM definitions CROSS JOIN unit_authors USING(definition_chash) CROSS JOIN units USING(unit) \n\
WHERE definition_chash=? AND is_stable=1 AND sequence='good' AND main_chain_index<=?";
var params = [definition_chash, max_mci];
conn.query(sql, params, function(rows){
if (rows.length === 0)
return callbacks.ifDefinitionNotFound(definition_chash);
callbacks.ifFound(JSON.parse(rows[0].definition));
});
}
function readDefinition(conn, definition_chash, callbacks){
conn.query("SELECT definition FROM definitions WHERE definition_chash=?", [definition_chash], function(rows){
if (rows.length === 0)
return callbacks.ifDefinitionNotFound(definition_chash);
callbacks.ifFound(JSON.parse(rows[0].definition));
});
}
function readAADefinition(conn, address, handleDefinition) {
if (!handleDefinition)
return new Promise(resolve => readAADefinition(conn, address, (arrDefinition, unit, storage_size) => resolve({ arrDefinition, unit, storage_size })));
conn.query("SELECT definition, unit, storage_size FROM aa_addresses WHERE address=?", [address], function (rows) {
if (rows.length !== 1)
return handleDefinition(null);
var arrDefinition = JSON.parse(rows[0].definition);
if (arrDefinition[0] !== 'autonomous agent')
throw Error("non-AA definition in AA unit");
handleDefinition(arrDefinition, rows[0].unit, rows[0].storage_size);
});
}
function readBaseAADefinitionAndParams(conn, address, handleDefinitionAndParams) {
if (!handleDefinitionAndParams)
return new Promise(resolve => readBaseAADefinitionAndParams(conn, address, (arrBaseDefinition, params, storage_size) => resolve({ arrBaseDefinition, params, storage_size })));
readAADefinition(conn, address, function (arrDefinition, unit, storage_size) {
if (!arrDefinition)
return handleDefinitionAndParams(null);
var base_aa = arrDefinition[1].base_aa;
if (!base_aa)
return handleDefinitionAndParams(arrDefinition, null, storage_size);
readAADefinition(conn, base_aa, function (arrBaseDefinition) {
if (!arrBaseDefinition)
throw Error("base AA not found: " + base_aa);
handleDefinitionAndParams(arrBaseDefinition, arrDefinition[1].params, storage_size);
});
});
}
function readAAGetters(conn, address, handleGetters) {
if (!handleGetters)
return new Promise(resolve => readAAGetters(conn, address, resolve));
conn.query("SELECT getters, base_aa FROM aa_addresses WHERE address=?", [address], function (rows) {
if (rows.length !== 1)
return handleGetters(null);
var row = rows[0];
if (row.getters && row.base_aa)
throw Error("both getters and base AA");
if (row.base_aa)
return readAAGetters(conn, row.base_aa, handleGetters);
if (!row.getters)
return handleGetters({});
var assocGetters = JSON.parse(row.getters);
handleGetters(assocGetters);
});
}
function readAAGetterProps(conn, address, func_name, handleGetterProps) {
if (!handleGetterProps)
return new Promise(resolve => readAAGetterProps(conn, address, func_name, resolve));
readAAGetters(conn, address, function (getters) {
if (!getters)
return handleGetterProps(null);
if (!ValidationUtils.hasOwnProperty(getters, func_name))
return handleGetterProps(null);
handleGetterProps(getters[func_name]);
});
}
function getUnconfirmedAADefinition(address) {
for (var unit in assocUnstableMessages) {
var objUnit = assocUnstableUnits[unit] || assocStableUnits[unit]; // just stabilized
if (!objUnit)
throw Error("unstable unit " + unit + " not in assoc");
var messages = assocUnstableMessages[unit];
for (var i = 0; i < messages.length; i++) {
var message = messages[i];
if (message.app !== 'definition')
continue;
var payload = message.payload;
if (payload.address === address)
return payload.definition;
}
}
return null;
}
// arrAddresses is an array of AA addresses whose definitions are posted by other AAs
function getUnconfirmedAADefinitionsPostedByAAs(arrAddresses) {
var payloads = [];
for (var unit in assocUnstableMessages) {
var objUnit = assocUnstableUnits[unit] || assocStableUnits[unit]; // just stabilized
if (!objUnit)
throw Error("unstable unit " + unit + " not in assoc");
if (!objUnit.bAA)
continue;
assocUnstableMessages[unit].forEach(function (message) {
if (message.app !== 'definition')
return;
var payload = message.payload;
if (arrAddresses.indexOf(payload.address) >= 0)
payloads.push(payload);
});
}
return payloads;
}
function insertAADefinitions(conn, arrPayloads, unit, mci, bForAAsOnly, onDone) {
if (!onDone)
return new Promise(resolve => insertAADefinitions(conn, arrPayloads, unit, mci, bForAAsOnly, resolve));
var aa_validation = require("./aa_validation.js");
async.eachSeries(
arrPayloads,
function (payload, cb) {
var address = payload.address;
var json = JSON.stringify(payload.definition);
var base_aa = payload.definition[1].base_aa;
var bAlreadyPostedByUnconfirmedAA = false;
var readGetterProps = function (aa_address, func_name, cb) {
if (conf.bLight)
return cb({ complexity: 0, count_ops: 0, count_args: null });
readAAGetterProps(conn, aa_address, func_name, cb);
};
aa_validation.determineGetterProps(payload.definition, readGetterProps, function (getters) {
conn.query("INSERT " + db.getIgnore() + " INTO aa_addresses (address, definition, unit, mci, base_aa, getters) VALUES (?,?, ?,?, ?,?)", [address, json, unit, mci, base_aa, getters ? JSON.stringify(getters) : null], function (res) {
if (res.affectedRows === 0) { // already exists
if (bForAAsOnly){
console.log("ignoring repeated definition of AA " + address + " in AA unit " + unit);
return cb();
}
var old_payloads = getUnconfirmedAADefinitionsPostedByAAs([address]);
if (old_payloads.length === 0) {
console.log("ignoring repeated definition of AA " + address + " in unit " + unit);
return cb();
}
// we need to recalc the balances to reflect the payments received from non-AAs between definition and stabilization
bAlreadyPostedByUnconfirmedAA = true;
console.log("will recalc balances after repeated definition of AA " + address + " in unit " + unit);
}
if (conf.bLight)
return cb();
var verb = bAlreadyPostedByUnconfirmedAA ? "REPLACE" : "INSERT";
var or_sent_by_aa = bAlreadyPostedByUnconfirmedAA ? "OR EXISTS (SELECT 1 FROM unit_authors CROSS JOIN aa_addresses USING(address) WHERE unit_authors.unit=outputs.unit)" : "";
conn.query(
verb + " INTO aa_balances (address, asset, balance) \n\
SELECT address, IFNULL(asset, 'base'), SUM(amount) AS balance \n\
FROM outputs CROSS JOIN units USING(unit) \n\
WHERE address=? AND is_spent=0 AND (main_chain_index<? " + or_sent_by_aa + ") \n\
GROUP BY address, asset", // not including the outputs on the current mci, which will trigger the AA and be accounted for separately
[address, mci],
function () {
conn.query(
"INSERT " + db.getIgnore() + " INTO addresses (address) VALUES (?)", [address],
function () {
// can emit again if bAlreadyPostedByUnconfirmedAA, that's ok, the watchers will learn that the AA became now available to non-AAs
process.nextTick(function () { // don't call it synchronously with event emitter
eventBus.emit("aa_definition_saved", payload, unit);
});
cb();
}
);
}
);
});
});
},
onDone
);
}
function readAABalances(conn, address, handleBalances) {
if (!handleBalances)
return new Promise(resolve => readAABalances(conn, address, resolve));
conn.query("SELECT asset, balance FROM aa_balances WHERE address=?", [address], function (rows) {
var assocBalances = {};
rows.forEach(function (row) {
assocBalances[row.asset] = row.balance;
});
handleBalances(assocBalances);
});
}
function parseStateVar(type_and_value) {
if (typeof type_and_value !== 'string')
throw Error("bad type of value " + type_and_value + ": " + (typeof type_and_value));
if (type_and_value[1] !== "\n")
throw Error("bad value: " + type_and_value);
var type = type_and_value[0];
var value = type_and_value.substr(2);
if (type === 's')
return value;
else if (type === 'n')
return parseFloat(value);
else if (type === 'j')
return JSON.parse(value);
else
throw Error("unknown type in " + type_and_value);
}
function readAAStateVar(address, var_name, handleResult) {
if (!handleResult)
return new Promise(resolve => readAAStateVar(address, var_name, resolve));
var kvstore = require('./kvstore.js');
kvstore.get("st\n" + address + "\n" + var_name, function (type_and_value) {
if (type_and_value === undefined)
return handleResult();
handleResult(parseStateVar(type_and_value));
});
}
function readAAStateVars(address, var_prefix_from, var_prefix_to, limit, handle) {
if (arguments.length <= 2) {
handle = var_prefix_from;
var_prefix_from = '';
var_prefix_to = '';
limit = 0;
}
if (!handle)
return new Promise(resolve => readAAStateVars(address, var_prefix_from, var_prefix_to, limit, resolve));
var options = {};
options.gte = "st\n" + address + "\n" + var_prefix_from;
options.lte = "st\n" + address + "\n" + var_prefix_to + "\uFFFF";
if (limit)
options.limit = limit;
var assignField = require('./formula/common.js').assignField;
var objStateVars = {}
var handleData = function (data){
assignField(objStateVars, data.key.slice(36), parseStateVar(data.value));
}
var kvstore = require('./kvstore.js');
var stream = kvstore.createReadStream(options);
stream.on('data', handleData)
.on('end', function(){
handle(objStateVars);
})
.on('error', function(error){
throw Error('error from data stream: '+error);
});
}
function readFreeJoints(ifFoundFreeBall, onDone){
db.query("SELECT units.unit FROM units LEFT JOIN archived_joints USING(unit) WHERE is_free=1 AND archived_joints.unit IS NULL", function(rows){
async.each(rows, function(row, cb){
readJoint(db, row.unit, {
ifNotFound: function(){
throw Error("free ball lost");
},
ifFound: function(objJoint){
ifFoundFreeBall(objJoint);
cb();
}
});
}, onDone);
});
}
function isGenesisUnit(unit){
return (unit === constants.GENESIS_UNIT);
}
function isGenesisBall(ball){
return (ball === genesis_ball);