-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzingo_litewallet.js
1494 lines (1301 loc) · 56.4 KB
/
zingo_litewallet.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
const native = require("./native.node");
const { TxDetail, Transaction, TotalBalance, Address, AddressBalance, WalletSettings, Info } = require('./utils/classes');
class LiteWallet {
constructor(url, chain, readOnly) {
this.url = url;
this.chain = chain || "main";
this.refreshTimerID;
this.updateTimerID;
this.syncStatusTimerID;
this.updateDataLock;
this.updateDataCtr;
this.lastWalletBlockHeight = 0;
this.lastServerBlockHeight = 0;
this.walletBirthday = 0;
this.infoObject;
this.walletSettings;
this.allAddresses;
this.transactionsList;
this.syncingStatus;
this.inRefresh = false;
this.inSend = false;
this.blocksPerBatch = 100;
this.prev_batch_num = -1;
this.prev_sync_id = -1;
this.prev_current_block = -1;
this.seconds_batch = 0;
this.seconds_block = 0;
this.batches = 0;
this.latest_block = -1;
this.sync_id = -1;
this.timers = [];
this.readOnly = readOnly;
this.updateDataLock = false;
this.updateDataCtr = 0;
}
restore(mnemonic, birthday, allowOverwrite) {
return new Promise(async (resolve, reject) => {
if(mnemonic) {
const birth = birthday || 0;
const result = await native.zingolib_initialize_new_from_phrase(this.url, mnemonic, birth, allowOverwrite, this.chain);
if (result.startsWith("Error")) {
reject(result);
}
resolve('success');
}
});
}
init() {
return new Promise(async (resolve, reject) => {
if(!native.zingolib_wallet_exists(this.chain)) {
console.log('Wallet not configured, creating new one!');
const res = native.zingolib_initialize_new(this.url, this.chain);
if(res.toString().toLowerCase().startsWith('error')) {
reject("Error: Couldn't create a wallet");
}
else {
const seed = await native.zingolib_execute_async("seed", "");
console.log("Wallet created! Please save the wallet seed:\n" + seed);
}
}
let res = native.zingolib_initialize_existing(this.url, this.chain);
if(res !== 'OK') {
reject('Something went wrong while initializing the wallet. \n'+ res + '\nQuitting ...');
return;
}
// First things first, I need to stop an existing sync process (if any)
// clean start.
await this.stopSyncProcess();
// every 30 seconds the App try to Sync the new blocks.
if (!this.refreshTimerID) {
this.refreshTimerID = setInterval(() => {
//console.log('interval refresh');
this.refreshSimple(false);
}, 30 * 1000); // 30 seconds
//console.log('create refresh timer', this.refreshTimerID);
this.timers.push(this.refreshTimerID);
}
// every 15 seconds the App update all data
if (!this.updateTimerID) {
this.updateTimerID = setInterval(() => {
//console.log('interval update', this.timers);
this.sanitizeTimers();
this.updateData();
}, 15 * 1000); // 15 secs
//console.log('create update timer', this.updateTimerID);
this.timers.push(this.updateTimerID);
}
// and now the array of timers...
let deleted = [];
for (var i = 0; i < this.timers.length; i++) {
if (this.timers[i] !== this.refreshTimerID && this.timers[i] !== this.updateTimerID) {
clearInterval(this.timers[i]);
deleted.push(i);
//console.log('kill item array timers', this.timers[i]);
}
}
// remove the cleared timers.
for (var i = 0; i < deleted.length; i++) {
this.timers.splice(deleted[i], 1);
}
// Load the current wallet data
await this.loadWalletData();
// Call the refresh after configure
this.refresh(true);
resolve("ok");
});
}
async rpc_getInfoObject() {
try {
const infoStr = await native.zingolib_execute_async('info', '');
if (infoStr) {
if (infoStr.toLowerCase().startsWith('error')) {
console.log(`Error info ${infoStr}`);
return {};
}
} else {
console.log('Internal Error info');
return {};
}
const infoJSON = await JSON.parse(infoStr);
const defaultFeeStr = await native.zingolib_execute_async('defaultfee', '');
if (defaultFeeStr) {
if (defaultFeeStr.toLowerCase().startsWith('error')) {
console.log(`Error defaultfee ${defaultFeeStr}`);
return {};
}
} else {
console.log('Internal Error defaultfee');
return {};
}
const defaultFeeJSON = await JSON.parse(defaultFeeStr);
let zingolibStr = await native.zingolib_execute_async('version', '');
if (zingolibStr) {
if (zingolibStr.toLowerCase().startsWith('error')) {
console.log(`Error zingolib version ${zingolibStr}`);
zingolibStr = '<error>';
}
} else {
console.log('Internal Error zingolib version');
zingolibStr = '<none>';
}
//const zingolibJSON = await JSON.parse(zingolibStr);
const info = new Info();
info.chain_name = infoJSON.chain_name;
info.latestBlock = infoJSON.latest_block_height;
info.serverUri = infoJSON.server_uri || '<none>';
info.connections = 1;
info.version = `${infoJSON.vendor}/${infoJSON.git_commit.substring(0, 6)}/${infoJSON.version}`;
info.verificationProgress = 1;
info.currencyName = infoJSON.chain_name === 'main' ? 'ZEC' : 'TAZ';
info.solps = 0;
info.defaultFee = defaultFeeJSON.defaultfee / 10 ** 8 || 10000 / 10 ** 8;
info.zingolib = zingolibStr;
return info;
}
catch (error) {
console.log(`Critical Error info and/or defaultfee ${error}`);
return {};
}
}
async rpc_fetchWallet(readOnly) {
if (readOnly) {
// viewing key
try {
const ufvkStr = await native.zingolib_execute_async('exportufvk', '');
if (ufvkStr) {
if (ufvkStr.toLowerCase().startsWith('error')) {
console.log(`Error ufvk ${ufvkStr}`);
return {};
}
} else {
console.log('Internal Error ufvk');
return {};
}
const ufvk = JSON.parse(ufvkStr);
return ufvk;
} catch (error) {
console.log(`Critical Error ufvk / get_birthday ${error}`);
return {};
}
} else {
// seed
try {
const seedStr = await native.zingolib_execute_async('seed', '');
if (seedStr) {
if (seedStr.toLowerCase().startsWith('error')) {
console.log(`Error seed ${seedStr}`);
return {};
}
} else {
console.log('Internal Error seed');
return {};
}
const RPCseed = JSON.parse(seedStr);
const seed = {};
if (RPCseed.seed) {
seed.seed = RPCseed.seed;
}
if (RPCseed.birthday) {
seed.birthday = RPCseed.birthday;
}
return seed;
} catch (error) {
console.log(`Critical Error seed ${error}`);
return {};
}
}
}
// We combine detailed transactions if they are sent to the same outgoing address in the same txid. This
// is usually done to split long memos.
// Remember to add up both amounts and combine memos
rpc_combineTxDetailsByAddress(txdetails) {
// First, group by outgoing address.
const m = new Map();
txdetails
.filter(i => i.address !== undefined)
.forEach(i => {
const coll = m.get(i.address);
if (!coll) {
m.set(i.address, [i]);
} else {
coll.push(i);
}
});
// Reduce the groups to a single TxDetail, combining memos and summing amounts
const reducedDetailedTxns = [];
m.forEach((txns, toaddr) => {
const totalAmount = txns.reduce((sum, i) => sum + i.amount, 0);
const memos = txns
.filter(i => i.memos && i.memos.length > 0)
.map(i => {
const combinedMemo = i.memos
.filter(memo => memo)
.map(memo => {
const rex = /\((\d+)\/(\d+)\)((.|[\r\n])*)/;
const tags = memo.match(rex);
if (tags && tags.length >= 4) {
return { num: parseInt(tags[1], 10), memo: tags[3] };
}
// Just return as is
return { num: 0, memo };
})
.sort((a, b) => a.num - b.num)
.map(a => a.memo);
return combinedMemo && combinedMemo.length > 0 ? combinedMemo.join('') : undefined;
})
.map(a => a);
const detail = new TxDetail();
detail.address = toaddr,
detail.amount = totalAmount,
detail.memos = (memos && memos.length > 0 ? [memos.join('')] : undefined)
reducedDetailedTxns.push(detail);
});
return reducedDetailedTxns;
}
// We combine detailed transactions if they are received to the same pool in the same txid. This
// is usually done to split long memos.
// Remember to add up both amounts and combine memos
rpc_combineTxDetailsByPool(txdetails) {
// First, group by pool.
const m = new Map();
txdetails
.filter(i => i.pool !== undefined)
.forEach(i => {
const coll = m.get(i.pool);
if (!coll) {
m.set(i.pool, [i]);
} else {
coll.push(i);
}
});
// Reduce the groups to a single TxDetail, combining memos and summing amounts
const reducedDetailedTxns = [];
m.forEach((txns, pool) => {
const totalAmount = txns.reduce((sum, i) => sum + i.amount, 0);
const memos = txns
.filter(i => i.memos && i.memos.length > 0)
.map(i => {
const combinedMemo = i.memos
.filter(memo => memo)
.map(memo => {
const rex = /\((\d+)\/(\d+)\)((.|[\r\n])*)/;
const tags = memo.match(rex);
if (tags && tags.length >= 4) {
return { num: parseInt(tags[1], 10), memo: tags[3] };
}
// Just return as is
return { num: 0, memo };
})
.sort((a, b) => a.num - b.num)
.map(a => a.memo);
return combinedMemo && combinedMemo.length > 0 ? combinedMemo.join('') : undefined;
})
.map(a => a);
const detail = new TxDetail();
detail.address = '';
detail.amount = totalAmount;
detail.memos = (memos && memos.length > 0 ? [memos.join('')] : undefined);
detail.pool = pool;
reducedDetailedTxns.push(detail);
});
return reducedDetailedTxns;
}
async rpc_setInterruptSyncAfterBatch(value) {
try {
const resultStr = await native.zingolib_execute_async('interrupt_sync_after_batch', value);
if (resultStr) {
if (resultStr.toLowerCase().startsWith('error')) {
console.log(`Error setting interrupt_sync_after_batch ${resultStr}`);
}
} else {
console.log('Internal Error setting interrupt_sync_after_batch');
}
} catch (error) {
console.log(`Critical Error setting interrupt_sync_after_batch ${error}`);
}
}
async rpc_doRescan() {
return new Promise(async (resolve, reject) => {
try {
const rescanStr = await native.zingolib_execute_spawn("rescan", "");
if (rescanStr) {
if (rescanStr.toLowerCase().startsWith('error')) {
console.log(`Error rescan ${rescanStr}`);
reject(rescanStr);
}
} else {
console.log('Internal Error rescan');
reject('Error: Internal RPC Error: rescan');
}
await this.fetchInfoAndServerHeight();
const res = {
result: 'success',
latest_block: this.lastServerBlockHeight
}
resolve(JSON.stringify(res));
} catch (error) {
console.log(`Critical Error rescan ${error}`);
reject(`Error: ${error}`);
}
});
}
async rpc_doSync() {
return new Promise(async (resolve, reject) => {
try {
const syncStr = await native.zingolib_execute_spawn('sync', '');
if (syncStr) {
if (syncStr.toLowerCase().startsWith('error')) {
console.log(`Error sync ${syncStr}`);
reject(syncStr);
}
} else {
console.log('Internal Error sync');
reject('Error: Internal RPC Error: sync');
}
await this.fetchInfoAndServerHeight();
const res = {
result: 'success',
latest_block: this.lastServerBlockHeight
}
resolve(JSON.stringify(res));
} catch (error) {
console.log(`Critical Error sync ${error}`);
reject(`Error: ${error}`);
}
});
}
async rpc_doSave() {
try {
const saveStr = await native.zingolib_execute_async('save','');
if (saveStr) {
if (saveStr.toLowerCase().startsWith('error')) {
console.log(`Error save ${saveStr}`);
}
} else {
console.log('Internal Error save');
}
} catch (error) {
console.log(`Critical Error save ${error}`);
}
}
async stopSyncProcess() {
let returnStatus = await this.doSyncStatus();
if (returnStatus.toLowerCase().startsWith('error')) {
return;
}
let ss = {};
try {
ss = await JSON.parse(returnStatus);
} catch (e) {
return;
}
console.log('stop sync process. in progress', ss.in_progress);
while (ss.in_progress) {
// interrupting sync process
await this.rpc_setInterruptSyncAfterBatch('true');
// sleep for half second
await this.sleep(500);
returnStatus = await this.doSyncStatus();
ss = await JSON.parse(returnStatus);
console.log('stop sync process. in progress', ss.in_progress);
}
console.log('stop sync process. STOPPED');
// NOT interrupting sync process
await this.rpc_setInterruptSyncAfterBatch('false');
}
async doSyncStatus() {
try {
const syncStatusStr = await native.zingolib_execute_async('syncstatus', '');
if (syncStatusStr) {
if (syncStatusStr.toLowerCase().startsWith('error')) {
console.log(`Error sync status ${syncStatusStr}`);
return syncStatusStr;
}
} else {
console.log('Internal Error sync status');
return 'Error: Internal RPC Error: sync status';
}
return syncStatusStr;
} catch (error) {
console.log(`Critical Error sync status ${error}`);
return `Error: ${error}`;
}
}
async sanitizeTimers() {
// and now the array of timers...
let deleted = [];
for (var i = 0; i < this.timers.length; i++) {
if (
this.timers[i] !== this.refreshTimerID &&
this.timers[i] !== this.updateTimerID &&
this.timers[i] !== this.syncStatusTimerID
) {
clearInterval(this.timers[i]);
deleted.push(i);
//console.log('sanitize - kill item array timers', this.timers[i]);
}
}
// remove the cleared timers.
for (var i = 0; i < deleted.length; i++) {
this.timers.splice(deleted[i], 1);
}
}
async loadWalletData() {
await this.fetchTotalBalance();
await this.fetchTandZandOTransactionsSummaries();
await this.fetchWalletSettings();
await this.fetchInfoAndServerHeight();
}
async updateData() {
//console.log("Update data triggered");
if (this.updateDataLock) {
//console.log("Update lock, returning");
return;
}
this.updateDataCtr += 1;
if ((this.inRefresh || this.inSend) && this.updateDataCtr % 5 !== 0) {
// We're refreshing, or sending, in which case update every 5th time
return;
}
this.updateDataLock = true;
await this.fetchWalletHeight();
await this.fetchWalletBirthday();
await this.fetchInfoAndServerHeight();
// And fetch the rest of the data.
await this.loadWalletData();
//console.log(`Finished update data at ${lastServerBlockHeight}`);
this.updateDataLock = false;
}
async refresh(fullRefresh, fullRescan) {
// If we're in refresh, we don't overlap
if (this.inRefresh) {
//console.log('in refresh is true');
return;
}
if (this.syncStatusTimerID) {
//console.log('syncStatusTimerID exists already');
return;
}
// And fetch the rest of the data.
await this.loadWalletData();
await this.fetchWalletHeight();
await this.fetchWalletBirthday();
await this.fetchInfoAndServerHeight();
if (!this.lastServerBlockHeight) {
//console.log('the last server block is zero');
return;
}
// if it's sending now, don't fire the sync process.
if (
fullRefresh ||
fullRescan ||
!this.lastWalletBlockHeight ||
this.lastWalletBlockHeight < this.lastServerBlockHeight
) {
// If the latest block height has changed, make sure to sync. This will happen in a new thread
this.inRefresh = true;
this.prev_batch_num = -1;
this.prev_sync_id = -1;
this.seconds_batch = 0;
this.seconds_block = 0;
this.batches = 0;
this.latest_block = -1;
this.prev_current_block = -1;
// This is async, so when it is done, we finish the refresh.
if (fullRescan) {
// clean the transaction list before.
this.transactionsList = [];
this.totalBalance.orchardBal = 0;
this.privateBal = 0;
this.transparentBal = 0;
this.spendableOrchard = 0;
this.spendablePrivate = 0;
this.total = 0;
this.rpc_doRescan()
.then(result => {
console.log('rescan finished', result);
if (result && !result.toLowerCase().startsWith('error')) {
const resultJSON = JSON.parse(result);
if (resultJSON.result === 'success' && resultJSON.latest_block) {
this.latest_block = resultJSON.latest_block;
}
}
})
.catch(error => console.log('rescan error', error));
//.finally(() => {
// with the new feature shardtree I can get an error here, but
// doesn't mean the sync/rescan process is finished, I have to
// rely on syncstatus finished instead
//this.inRefresh = false;
//});
} else {
this.rpc_doSync()
.then(result => {
console.log('sync finished', result);
if (result && !result.toLowerCase().startsWith('error')) {
const resultJSON = JSON.parse(result);
if (resultJSON.result === 'success' && resultJSON.latest_block) {
this.latest_block = resultJSON.latest_block;
}
}
})
.catch(error => console.log('sync error', error));
//.finally(() => {
// with the new feature shardtree I can get an error here, but
// doesn't mean the sync/rescan process is finished, I have to
// rely on syncstatus finished instead
//this.inRefresh = false;
//this.keepAwake(false);
//});
}
// We need to wait for the sync to finish. The sync is done when
this.syncStatusTimerID = setInterval(async () => {
const returnStatus = await this.doSyncStatus();
if (returnStatus.toLowerCase().startsWith('error')) {
return;
}
let ss = {};
try {
ss = JSON.parse(returnStatus);
} catch (e) {
return;
}
// console.log('sync wallet birthday', this.walletBirthday);
//console.log('sync', this.syncStatusTimerID);
console.log(
'synced',
ss.synced_blocks,
'trial_decryptions',
ss.trial_decryptions_blocks,
'txn_scan',
ss.txn_scan_blocks,
'witnesses',
ss.witnesses_updated,
'TOTAL',
ss.total_blocks,
'batch_num',
ss.batch_num,
'batch_total',
ss.batch_total,
'end_block',
ss.end_block,
'start_block',
ss.start_block,
);
//console.log('--------------------------------------');
// synchronize status
if (this.syncStatusTimerID) {
this.inRefresh = ss.in_progress;
}
this.sync_id = ss.sync_id;
// if the sync_id change then reset the %
if (this.prev_sync_id !== this.sync_id) {
if (this.prev_sync_id !== -1) {
// And fetch the rest of the data.
await this.loadWalletData();
await this.fetchWalletHeight();
await this.fetchWalletBirthday();
await this.fetchInfoAndServerHeight();
await this.rpc_doSave();
//console.log('sync status', ss);
//console.log(`new sync process id: ${this.sync_id}. Save the wallet.`);
this.prev_batch_num = -1;
this.seconds_batch = 0;
this.seconds_block = 0;
this.batches = 0;
}
this.prev_sync_id = this.sync_id;
}
// Post sync updates
let synced_blocks = ss.synced_blocks || 0;
let trial_decryptions_blocks = ss.trial_decryptions_blocks || 0;
let txn_scan_blocks = ss.txn_scan_blocks || 0;
let witnesses_updated = ss.witnesses_updated || 0;
// just in case
if (synced_blocks < 0) {
synced_blocks = 0;
}
if (synced_blocks > this.blocksPerBatch) {
synced_blocks = this.blocksPerBatch;
}
if (trial_decryptions_blocks < 0) {
trial_decryptions_blocks = 0;
}
if (trial_decryptions_blocks > this.blocksPerBatch) {
trial_decryptions_blocks = this.blocksPerBatch;
}
if (txn_scan_blocks < 0) {
txn_scan_blocks = 0;
}
if (txn_scan_blocks > this.blocksPerBatch) {
txn_scan_blocks = this.blocksPerBatch;
}
if (witnesses_updated < 0) {
witnesses_updated = 0;
}
if (witnesses_updated > this.blocksPerBatch) {
witnesses_updated = this.blocksPerBatch;
}
const batch_total = ss.batch_total || 0;
const batch_num = ss.batch_num || 0;
const end_block = ss.end_block || 0; // lower
// I want to know what was the first block of the current sync process
let process_end_block = 0;
// when the App is syncing the new blocks and sync finished really fast
// the synstatus have almost all of the fields undefined.
// if we have latest_block means that the sync process finished in that block
if (end_block === 0 && batch_num === 0) {
process_end_block = this.latest_block !== -1 ? this.latest_block : this.lastServerBlockHeight;
} else {
process_end_block = end_block - batch_num * this.blocksPerBatch;
}
//const progress_blocks = (synced_blocks + trial_decryptions_blocks + txn_scan_blocks) / 3;
const progress_blocks = (synced_blocks + trial_decryptions_blocks + witnesses_updated) / 3;
// And fetch the rest of the data.
//await this.loadWalletData();
//await this.fetchWalletHeight();
//await this.fetchWalletBirthday();
//await this.fetchServerHeight();
let current_block = end_block + progress_blocks;
if (current_block > this.lastServerBlockHeight) {
current_block = this.lastServerBlockHeight;
}
current_block = parseInt(current_block.toFixed(0), 10);
// if the current block is stalled I need to restart the App
let syncProcessStalled = false;
if (this.prev_current_block !== -1) {
//console.log(
// 'BEFORE prev current block',
// this.prev_current_block,
// 'current block',
// current_block,
// 'seconds',
// this.seconds_block,
// 'blocks',
// current_block - this.prev_current_block,
//);
if (current_block > 0 && this.prev_current_block === current_block) {
this.seconds_block += 5;
// 5 minutes
if (this.seconds_block >= 300) {
this.seconds_block = 0;
syncProcessStalled = true;
}
}
if (current_block > 0 && this.prev_current_block !== current_block) {
this.seconds_block = 0;
syncProcessStalled = false;
}
}
//console.log(
// 'AFTER prev current block',
// this.prev_current_block,
// 'current block',
// current_block,
// 'seconds',
// this.seconds_block,
// 'stalled',
// syncProcessStalled,
//);
// if current block is lower than the previous current block
// The user need to see something not confusing.
if (current_block > 0 && this.prev_current_block !== -1 && current_block < this.prev_current_block) {
//console.log('blocks down', current_block - this.prev_current_block);
// I decided to add only one fake block because otherwise could seems stalled
// the user expect every 5 seconds the blocks change...
current_block = this.prev_current_block + 1;
}
this.prev_current_block = current_block;
this.seconds_batch += 5;
//console.log('interval sync/rescan, secs', this.seconds_batch, 'timer', this.syncStatusTimerID);
// store SyncStatus object for a new screen
this.syncingStatus = {
syncID: this.sync_id,
totalBatches: batch_total,
currentBatch: ss.in_progress ? batch_num + 1 : 0,
lastBlockWallet: this.lastWalletBlockHeight,
currentBlock: current_block,
inProgress: ss.in_progress,
lastError: ss.last_error,
blocksPerBatch: this.blocksPerBatch,
secondsPerBatch: this.seconds_batch,
process_end_block: process_end_block,
lastBlockServer: this.lastServerBlockHeight,
syncProcessStalled: syncProcessStalled,
};
// Close the poll timer if the sync finished(checked via promise above)
if (!this.inRefresh) {
// We are synced. Cancel the poll timer
if (this.syncStatusTimerID) {
clearInterval(this.syncStatusTimerID);
this.syncStatusTimerID = undefined;
}
// And fetch the rest of the data.
await this.loadWalletData();
await this.fetchWalletHeight();
await this.fetchWalletBirthday();
await this.fetchInfoAndServerHeight();
await this.rpc_doSave();
// store SyncStatus object for a new screen
this.syncingStatus = {
syncID: this.sync_id,
totalBatches: 0,
currentBatch: 0,
lastBlockWallet: this.lastWalletBlockHeight,
currentBlock: current_block,
inProgress: false,
lastError: ss.last_error,
blocksPerBatch: this.blocksPerBatch,
secondsPerBatch: 0,
process_end_block: process_end_block,
lastBlockServer: this.lastServerBlockHeight,
syncProcessStalled: false,
};
//console.log('sync status', ss);
//console.log(`Finished refresh at ${this.lastWalletBlockHeight} id: ${this.sync_id}`);
} else {
// If we're doing a long sync, every time the batch_num changes, save the wallet
if (this.prev_batch_num !== batch_num) {
// if finished batches really fast, the App have to save the wallet delayed.
if (this.prev_batch_num !== -1 && this.batches >= 1) {
// And fetch the rest of the data.
await this.loadWalletData();
await this.fetchWalletHeight();
await this.fetchWalletBirthday();
await this.fetchInfoAndServerHeight();
await this.rpc_doSave();
this.batches = 0;
//console.log('sync status', ss);
//console.log(
// `@@@@@@@@@@@ Saving because batch num changed ${this.prevBatchNum} - ${batch_num}. seconds: ${this.seconds_batch}`,
//);
}
this.batches += batch_num - this.prev_batch_num;
this.prev_batch_num = batch_num;
this.seconds_batch = 0;
}
// save wallet every 15 seconds in the same batch.
/* altum suggestion - remove the mid-batch saving...
if (this.seconds_batch > 0 && this.seconds_batch % 15 === 0) {
// And fetch the rest of the data.
await this.loadWalletData();
await this.fetchWalletHeight();
await this.fetchWalletBirthday();
await this.fetchInfoAndServerHeight();
await this.rpc_doSave();
// store SyncStatus object for a new screen
this.syncingStatus = {
syncID: this.sync_id,
totalBatches: batch_total,
currentBatch: ss.in_progress ? batch_num + 1 : 0,
lastBlockWallet: this.lastWalletBlockHeight,
currentBlock: current_block,
inProgress: ss.in_progress,
lastError: ss.last_error,
blocksPerBatch: this.blocksPerBatch,
secondsPerBatch: this.seconds_batch,
process_end_block: process_end_block,
lastBlockServer: this.lastServerBlockHeight,
syncProcessStalled: false,
};
//console.log('sync status', ss);
//console.log(`@@@@@@@@@@@Saving wallet. seconds: ${this.seconds_batch}`);
}
*/
}
}, 5000);
//console.log('create sync/rescan timer', this.syncStatusTimerID);
this.timers.push(this.syncStatusTimerID);
} else {
// Already at the latest block
console.log('Already have latest block, waiting for next refresh');
// Here I know the sync process is over, I need to inform to the UI.
this.syncingStatus = {
syncID: this.sync_id,
totalBatches: 0,
currentBatch: 0,
lastBlockWallet: this.lastWalletBlockHeight,
currentBlock: this.lastWalletBlockHeight,
inProgress: false,
lastError: '',
blocksPerBatch: this.blocksPerBatch,
secondsPerBatch: 0,
process_end_block: this.lastServerBlockHeight,
lastBlockServer: this.lastServerBlockHeight,
syncProcessStalled: false,
};
}
}
async refreshSimple(fullRefresh) {
if (this.syncStatusTimerID) {
console.log("Already have a sync process launched", this.syncStatusTimerID);
return;
}
if(this.inSend) {
console.log("Wallet is sending, will sync after send is done.");
return;
}
await this.fetchWalletHeight();
// await this.fetchWalletBirthday();
await this.fetchInfoAndServerHeight();
// And fetch the rest of the data.
await this.loadWalletData();
if(!this.lastWalletBlockHeight || this.lastWalletBlockHeight < this.lastServerBlockHeight || fullRefresh) {
console.log('Refreshing wallet: ' + (this.lastServerBlockHeight - this.lastWalletBlockHeight) + ' new blocks.');
this.updateDataLock = true;
this.inRefresh = true;
native.zingolib_execute_spawn('sync', '');
let retryCount = 0;
this.syncStatusTimerID = setInterval(async () => {
await this.fetchWalletHeight();
await this.fetchInfoAndServerHeight();
// retryCount ++;
if(retryCount > 30 || this.lastWalletBlockHeight >= this.lastServerBlockHeight) {
clearInterval(this.syncStatusTimerID);
this.syncStatusTimerID = undefined;
console.log('Wallet is up to date!');
await this.loadWalletData();
this.lastBlockHeight = this.lastServerBlockHeight;
this.inRefresh = false;
await this.rpc_doSave();
this.updateDataLock = false;
}
else {
const ssStr = await this.doSyncStatus();
const ss = JSON.parse(ssStr);
if (!ss.in_progress) {
clearInterval(this.syncStatusTimerID);
this.syncStatusTimerID = undefined;
await this.loadWalletData();
this.lastWalletBlockHeight = this.lastServerBlockHeight;
this.inRefresh = false;
await this.rpc_doSave();