-
Notifications
You must be signed in to change notification settings - Fork 0
/
zingolib.js
650 lines (569 loc) · 22.4 KB
/
zingolib.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
const native = require('./native.node');
class ZingoLib {
constructor(uri, chain, monitorMempool) {
this.serveruri = uri;
this.chain = chain;
this.monitorMempool = monitorMempool;
this.syncInterval;
this.syncStatusInterval;
this.lastWalletBlockHeight;
this.lastServerBlockHeight;
this.inRefresh = false;
this.isSending = false;
}
async init() {
return new Promise(async (resolve, reject) => {
if(!native.zingolib_set_crypto_default_provider_to_ring()) {
reject("Error initializing crypto provider.")
};
if (native.zingolib_wallet_exists(this.serveruri, 'main')) {
const wallet = native.zingolib_init_from_b64(this.serveruri, 'main', this.monitorMempool);
if (wallet && !wallet.toLowerCase().startsWith('error')) {
console.log("Initializing existing wallet.");
}
else {
console.log("Error initializing wallet");
reject(wallet);
}
}
else {
console.log("No wallet configured, creating a new one.");
const res = native.zingolib_init_new(this.serveruri, 'main', this.monitorMempool);
if (res && !res.toLowerCase().startsWith('error')) {
const seed = await this.getWalletSeed();
console.log('Created new wallet, please save the seed:', seed);
}
else {
console.log("Error trying to create a new wallet", seed);
reject(seed);
}
}
await this.configure();
resolve("Ok");
});
}
async restore(seed, birthday) {
return new Promise((resolve, reject) => {
if(seed) {
console.log("Trying to initialize wallet from seed ...")
const res = native.zingolib_init_from_seed(this.serveruri, seed, birthday, this.chain, this.monitorMempool);
if(!res.toLowerCase().startsWith('error')) {
// const seedJson = JSON.parse(res);
console.log(`Seed imported, will sync from height ${birthday}`);
resolve(res);
}
else {
console.log("Error initializing from seed");
reject(seed);
}
}
});
}
async from_ufvk(ufvk, birthday) {
return new Promise((resolve, reject) => {
if(ufvk) {
console.log("Trying to initialize wallet from ufvk (watch only) ...")
const res = native.zingolib_init_from_ufvk(this.serveruri, ufvk, birthday, this.chain, this.monitorMempool);
if(!res.toLowerCase().startsWith('error')) {
const ufvkRes = res;
console.log(`ufvk imported, will sync from height ${birthday}`);
resolve(ufvkRes);
}
else {
console.log("Error initializing from ufvk:");
reject(res);
}
}
});
}
async sleep(ms) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(), ms);
});
}
async configure() {
try {
await this.stopSyncProcess();
await this.fetchInfoAndServerHeight();
// Save wallet
// const res = native.saveWallet();
// if (!res || res.toLowerCase().startsWith('error')) {
// console.log("Error saving wallet");
// }
// Do initial sync
this.doRefresh(false);
// Refresh wallet every 75 seconds
this.syncInterval = setInterval(() => {
this.doRefresh(false);
}, 75 * 1000);
}
catch (e) {
console.log("Couldn't configure the wallet", e);
return;
}
}
async stopSyncProcess() {
let res = await this.doSyncStatus();
let ss = JSON.parse(res);
while (ss.in_progress) {
await this.sleep(300);
this.setInterruptSyncAfterBatch(true);
console.log('stop sync process. in progress', ss.in_progress);
res = await this.doSyncStatus();
ss = JSON.parse(res);
}
console.log('stop sync process. STOPPED');
await this.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 setInterruptSyncAfterBatch(value) {
try {
const resultStr = await native.zingolib_execute_spawn('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 doRefresh(fullRefresh) {
if (this.syncStatusInterval) {
this.fetchWalletHeight();
console.log(`Already have a sync process launched. Wallet height is ${this.lastWalletBlockHeight}`);
return;
}
if (this.isSending) {
console.log("Wallet is sending, will sync after send is done.");
return;
}
this.fetchWalletHeight();
this.fetchInfoAndServerHeight();
if (this.lastWalletBlockHeight < this.lastServerBlockHeight || fullRefresh) {
this.inRefresh = true;
console.log(`Refresing wallet: ${this.lastServerBlockHeight - this.lastWalletBlockHeight} new blocks.`);
native.zingolib_execute_spawn('sync', '');
this.syncStatusInterval = setInterval(async () => {
this.fetchWalletHeight();
this.fetchInfoAndServerHeight();
if (this.lastWalletBlockHeight >= this.lastServerBlockHeight) {
clearInterval(this.syncStatusInterval);
this.syncStatusInterval = undefined;
console.log("Wallet is up to date!");
this.lastBlockHeight = this.lastServerBlockHeight;
this.inRefresh = false;
// await native.saveWallet();
}
else {
const ssStr = await this.doSyncStatus();
const ss = JSON.parse(ssStr);
if (!ss.in_progress) {
clearInterval(this.syncStatusInterval);
this.syncStatusInterval = undefined;
console.log("Wallet sync was interrupted ...");
this.lastBlockHeight = this.lastServerBlockHeight;
this.inRefresh = false;
// await native.saveWallet();
}
}
}, 2 * 1000);
}
else {
console.log(`No new blocks to sync.`);
}
}
async fetchInfoAndServerHeight() {
const res = await native.zingolib_execute_async('info', '');
if (res && !res.toLowerCase().startsWith('error')) {
const infoJson = JSON.parse(res);
this.infoObject = infoJson;
this.lastServerBlockHeight = infoJson.latest_block_height;
}
}
async fetchWalletHeight() {
try {
const heightStr = await native.zingolib_execute_async('height', '');
if (heightStr) {
if (heightStr.toLowerCase().startsWith('error')) {
console.log(`Error wallet height ${heightStr}`);
return;
}
} else {
console.log('Internal Error wallet height');
return;
}
const heightJSON = JSON.parse(heightStr);
this.lastWalletBlockHeight = heightJSON.height;
}
catch (error) {
console.log(`Critical Error wallet height ${error}`);
return;
}
return this.lastWalletBlockHeight;
}
async fetchTotalBalance() {
try {
const balStr = await native.zingolib_execute_async('balance', '');
console.log(balStr);
if (balStr) {
if (balStr.toLowerCase().startsWith('error')) {
console.log(`Error wallet balance ${balStr}`);
return 0;
}
} else {
console.log('Internal Error wallet balance');
return 0;
}
const balJson = JSON.parse(balStr);
// const cleanedString = balStr
// .replace(/[\[\]]/g, '')
// .replace(/(\s*\w+:\s*[\d_]+)/g, '$1,')
// .replace(/(\w+):/g, '"$1":')
// .replace(/_/g, '')
// .replace(/,\s*$/, '') // Remove trailing comma
// .trim(); // Trim any remaining whitespace or line breaks
// const balJson = JSON.parse(`{${cleanedString}}`);
// // console.log(balJson)
const totalBal = (balJson.sapling_balance + balJson.orchard_balance + balJson.transparent_balance) / 10**8;
return totalBal;
}
catch (error) {
console.log(`Critical Error wallet balance ${error}`);
return;
}
}
async fetchSpendableBalance() {
try {
const balStr = await native.zingolib_execute_async('spendablebalance', '');
if (balStr) {
if (balStr.toLowerCase().startsWith('error')) {
console.log(`Error wallet balance ${balStr}`);
return 0;
}
} else {
console.log('Internal Error wallet balance');
return 0;
}
const balJson = JSON.parse(balStr);
console.log(balJson)
// const totalBal = (balJson.sapling_balance + balJson.orchard_balance + balJson.transparent_balance) / 10**8;
// return totalBal;
}
catch (error) {
console.log(`Critical Error wallet balance ${error}`);
return;
}
}
async fetchNotes() {
try {
const notesStr = await native.zingolib_execute_async('notes', '');
if (notesStr) {
if (notesStr.toLowerCase().startsWith('error')) {
console.log(`Error wallet notes ${notesStr}`);
return;
}
} else {
console.log('Internal Error wallet notes');
return;
}
const notesJSON = JSON.parse(notesStr);
return notesJSON;
}
catch (error) {
console.log(`Critical Error wallet height ${error}`);
return;
}
}
async fetchAllAddresses() {
try {
const addrStr = await native.zingolib_execute_async('addresses', '');
if (addrStr) {
if (addrStr.toLowerCase().startsWith('error')) {
console.log(`Error getting addresses ${addrStr}`);
return;
}
} else {
console.log('Internal Error getting addresses');
return;
}
const addrJSON = JSON.parse(addrStr);
return addrJSON;
}
catch (error) {
console.log(`Critical Error getting addresses ${error}`);
return;
}
}
async getAddressesWithBalance() {
const addrList = await this.fetchAllAddresses();
const ab = [];
if (addrList) {
const notes = await this.fetchNotes();
addrList.forEach((addr) => {
// Sum of unspent UTXOs
const utxoValue = notes.utxos
.filter((n) => n.address == addr.address)
.reduce((acc, curr) => acc + curr.value, 0);
// Sum of sapling notes
const saplingValue = notes.unspent_sapling_notes
.filter((n) => n.address == addr.address)
.reduce((acc, curr) => acc + curr.value, 0);
// Sum of orchard notes
const orchardValue = notes.unspent_orchard_notes
.filter((n) => n.address == addr.address)
.reduce((acc, curr) => acc + curr.value, 0);
const totalValue = (utxoValue + saplingValue + orchardValue);
if(totalValue > 0) {
ab.push({
address: addr.address,
receivers: addr.receivers,
balance: totalValue
});
}
});
}
return ab;
}
async getAddressAndValueFromTx(tx) {
const allNotes = await this.fetchNotes();
let notes = [];
const txid = tx.txid.toString();
// Try orchard notes
notes = allNotes.unspent_orchard_notes.filter((n) => n.created_in_txid == txid);
if(notes.length == 0) notes = allNotes.pending_orchard_notes.filter((n) => n.created_in_txid == txid);
// Try sapling notes
if(notes.length == 0) notes = allNotes.unspent_sapling_notes.filter((n) => n.created_in_txid == txid);
if(notes.length == 0) notes = allNotes.pending_sapling_notes.filter((n) => n.created_in_txid == txid);
// Try transparent utxos
if(notes.length == 0) notes = allNotes.utxos.filter((n) => n.created_in_txid == txid);
if(notes.length == 0) notes = allNotes.pending_utxos.filter((n) => n.created_in_txid == txid);
const addrAndValue = notes.map((el) => {
return {
address: el.address,
value: el.value,
}
});
return addrAndValue;
}
async sendTransaction(sendJson) {
// First, get the previous send progress id, so we know which ID to track
const prevProgressStr = await native.zingolib_execute_async("sendprogress", "");
const prevProgressJSON = JSON.parse(prevProgressStr);
const prevSendId = prevProgressJSON.id;
let sendTxids = '';
let sendTxid = '';
this.isSending = true;
// Propose a tx
try {
console.log(`Sending ${JSON.stringify(sendJson)}`);
const resp = await native.zingolib_execute_async("send", JSON.stringify(sendJson));
console.log(`End Sending, response: ${resp}`);
}
catch(err) {
console.log(`Error sending Tx: ${err}`);
throw err;
}
// Confirm the tx ...
try {
console.log('Confirming');
const resp = await native.zingolib_execute_async("confirm", "");
console.log(`End Confirming, response: ${resp}`);
if (resp.toLowerCase().startsWith('error')) {
console.log(`Error confirming Tx: ${resp}`);
throw Error(resp);
}
else {
const respJSON = JSON.parse(resp);
if (respJSON.error) {
console.log(`Error confirming Tx: ${respJSON.error}`);
throw Error(respJSON.error);
}
else if (respJSON.txids) {
sendTxids = respJSON.txids.join(', ');
sendTxid = respJSON.txids[0];
}
else {
console.log(`Error confirming: no error, no txids `);
this.isSending = false;
throw Error('Error confirming: no error, no txids');
}
}
} catch (err) {
console.log(`Error confirming Tx: ${err}`);
this.isSending = false;
throw err;
}
// Return the promise, resolve with txid
return new Promise((resolve, reject) => {
const intervalID = setInterval(async () => {
const progressStr = await native.zingolib_execute_async("sendprogress", "");
const progressJSON = JSON.parse(progressStr);
if (progressJSON.id === prevSendId && !sendTxids) {
// Still not started, so wait for more time
return;
}
if (!progressJSON.txids && !progressJSON.error && !sendTxids) {
// Still processing
return;
}
// Finished processing
clearInterval(intervalID);
this.isSending = false;
if (progressJSON.txids) {
// And refresh data (full refresh)
this.doRefresh(true);
resolve(progressJSON.txids[0]);
}
if (progressJSON.error) {
reject(progressJSON.error);
}
if (sendTxids) {
// And refresh data (full refresh)
this.doRefresh(true);
resolve(sendTxid);
}
}, 2 * 1000); // Every two seconds
});
}
getTransactions() {
try {
const txnsStr = native.zingolib_get_value_transfers();
if (txnsStr) {
if (txnsStr.toLowerCase().startsWith('error')) {
console.log(`Error wallet transactions ${txnsStr}`);
return;
}
} else {
console.log('Internal Error wallet transactions');
return;
}
const txnsJSON = JSON.parse(txnsStr);
return txnsJSON;
}
catch (error) {
console.log(`Critical Error wallet transactions ${error}`);
return;
}
}
getTransactionsSummaries() {
try {
const txnsStr = native.zingolib_get_transaction_summaries();
if (txnsStr) {
if (txnsStr.toLowerCase().startsWith('error')) {
console.log(`Error wallet transactions summaries ${txnsStr}`);
return;
}
} else {
console.log('Internal Error wallet transactions summaries');
return;
}
const txnsJSON = JSON.parse(txnsStr);
return txnsJSON;
}
catch (error) {
console.log(`Critical Error wallet transactions summaries ${error}`);
return;
}
}
fetchLastTxId() {
const txListJson = this.getTransactionsSummaries();
if(txListJson && txListJson.transaction_summaries.length > 0) {
// console.log(txListJson.transaction_summaries)
return txListJson.transaction_summaries[txListJson.transaction_summaries.length - 1].txid;
}
else return -1;
}
async getDefaultFee() {
const feeStr = await native.zingolib_execute_async('defaultfee', '');
if(feeStr) {
const feeJson = JSON.parse(feeStr);
return parseFloat((feeJson.defaultfee / 10**8).toFixed(8));
}
else return 10000; // Fail safe
}
async getWalletSeed() {
const seedStr = await native.zingolib_execute_async('seed', '');
if(seedStr) {
const seedJson = JSON.parse(seedStr);
return seedJson;
}
else return "Error: Couldn't get wallet seed.";
}
async getWalletUfvk() {
const ufvkStr = await native.zingolib_execute_async('exportufvk', '');
if(ufvkStr) {
const ufvkJson = JSON.parse(ufvkStr);
return ufvkJson;
}
else return "Error: Couldn't get wallet ufvk.";
}
async parseAddress(addr) {
try {
const addrStr = await native.zingolib_execute_async('parse_address', addr);
if (addrStr) {
if (addrStr.toLowerCase().startsWith('error')) {
console.log(`Error parsing address ${addrStr}`);
return;
}
} else {
console.log('Internal Error parsing address');
return;
}
const addrJSON = JSON.parse(addrStr);
return addrJSON;
}
catch (error) {
console.log(`Critical Error parsing address ${error}`);
return;
}
}
async createNewAddress() {
try {
const addrStr = await native.zingolib_execute_async('new', 'zto');
if (addrStr) {
if (addrStr.toLowerCase().startsWith('error')) {
console.log(`Error creating address ${addrStr}`);
return;
}
} else {
console.log('Internal Error creating address');
return;
}
const addrNew = JSON.parse(addrStr);
const allAddr = await this.fetchAllAddresses();
const addrDetails = allAddr.filter((addr) => addr.address == addrNew[0]);
return addrDetails[0];
}
catch (error) {
console.log(`Critical Error parsing address ${error}`);
return;
}
}
async deinitialize() {
console.log("Safely shutting down zingolib ... ");
await this.stopSyncProcess();
await native.zingolib_execute_async('quit', '');
process.exit();
}
}
module.exports = ZingoLib;