forked from ZcashFoundation/zecwallet
-
Notifications
You must be signed in to change notification settings - Fork 3
/
rpc.cpp
1267 lines (1030 loc) · 44.2 KB
/
rpc.cpp
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
#include "rpc.h"
#include "addressbook.h"
#include "settings.h"
#include "senttxstore.h"
#include "turnstile.h"
#include "version.h"
#include "websockets.h"
using json = nlohmann::json;
RPC::RPC(MainWindow* main) {
auto cl = new ConnectionLoader(main, this);
// Execute the load connection async, so we can set up the rest of RPC properly.
QTimer::singleShot(1, [=]() { cl->loadConnection(); });
this->main = main;
this->ui = main->ui;
this->turnstile = new Turnstile(this, main);
// Setup balances table model
balancesTableModel = new BalancesTableModel(main->ui->balancesTable);
main->ui->balancesTable->setModel(balancesTableModel);
// Setup transactions table model
transactionsTableModel = new TxTableModel(ui->transactionsTable);
main->ui->transactionsTable->setModel(transactionsTableModel);
// Set up timer to refresh Price
priceTimer = new QTimer(main);
QObject::connect(priceTimer, &QTimer::timeout, [=]() {
if (Settings::getInstance()->getAllowFetchPrices())
refreshZECPrice();
});
priceTimer->start(Settings::priceRefreshSpeed); // Every hour
// Set up a timer to refresh the UI every few seconds
timer = new QTimer(main);
QObject::connect(timer, &QTimer::timeout, [=]() {
refresh();
});
timer->start(Settings::updateSpeed);
// Set up the timer to watch for tx status
txTimer = new QTimer(main);
QObject::connect(txTimer, &QTimer::timeout, [=]() {
watchTxStatus();
});
// Start at every 10s. When an operation is pending, this will change to every second
txTimer->start(Settings::updateSpeed);
usedAddresses = new QMap<QString, bool>();
}
RPC::~RPC() {
delete timer;
delete txTimer;
delete transactionsTableModel;
delete balancesTableModel;
delete turnstile;
delete utxos;
delete allBalances;
delete usedAddresses;
delete zaddresses;
delete taddresses;
delete conn;
}
void RPC::setEZcashd(QProcess* p) {
ezcashd = p;
if (ezcashd && ui->tabWidget->widget(4) == nullptr) {
ui->tabWidget->addTab(main->zcashdtab, "ycashd");
}
}
// Called when a connection to ycashd is available.
void RPC::setConnection(Connection* c) {
if (c == nullptr) return;
delete conn;
this->conn = c;
ui->statusBar->showMessage("Ready!");
// See if we need to remove the reindex/rescan flags from the ycash.conf file
auto zcashConfLocation = Settings::getInstance()->getZcashdConfLocation();
Settings::removeFromZcashConf(zcashConfLocation, "rescan");
Settings::removeFromZcashConf(zcashConfLocation, "reindex");
// If we're allowed to get the Zec Price, get the prices
if (Settings::getInstance()->getAllowFetchPrices())
refreshZECPrice();
// If we're allowed to check for updates, check for a new release
if (Settings::getInstance()->getCheckForUpdates())
checkForUpdate();
// Force update, because this might be coming from a settings update
// where we need to immediately refresh
refresh(true);
}
void RPC::getTAddresses(const std::function<void(json)>& cb) {
json payload = {
{"jsonrpc", "1.0"},
{"id", "someid"},
{"method", "getaddressesbyaccount"},
{"params", {""}}
};
conn->doRPCWithDefaultErrorHandling(payload, cb);
}
void RPC::getZAddresses(const std::function<void(json)>& cb) {
json payload = {
{"jsonrpc", "1.0"},
{"id", "someid"},
{"method", "z_listaddresses"},
};
conn->doRPCWithDefaultErrorHandling(payload, cb);
}
void RPC::getTransparentUnspent(const std::function<void(json)>& cb) {
json payload = {
{"jsonrpc", "1.0"},
{"id", "someid"},
{"method", "listunspent"},
{"params", {0}} // Get UTXOs with 0 confirmations as well.
};
conn->doRPCWithDefaultErrorHandling(payload, cb);
}
void RPC::getZUnspent(const std::function<void(json)>& cb) {
json payload = {
{"jsonrpc", "1.0"},
{"id", "someid"},
{"method", "z_listunspent"},
{"params", {0}} // Get UTXOs with 0 confirmations as well.
};
conn->doRPCWithDefaultErrorHandling(payload, cb);
}
void RPC::newZaddr(bool sapling, const std::function<void(json)>& cb) {
json payload = {
{"jsonrpc", "1.0"},
{"id", "someid"},
{"method", "z_getnewaddress"},
{"params", { sapling ? "sapling" : "sprout" }},
};
conn->doRPCWithDefaultErrorHandling(payload, cb);
}
void RPC::newTaddr(const std::function<void(json)>& cb) {
json payload = {
{"jsonrpc", "1.0"},
{"id", "someid"},
{"method", "getnewaddress"},
};
conn->doRPCWithDefaultErrorHandling(payload, cb);
}
void RPC::getZPrivKey(QString addr, const std::function<void(json)>& cb) {
json payload = {
{"jsonrpc", "1.0"},
{"id", "someid"},
{"method", "z_exportkey"},
{"params", { addr.toStdString() }},
};
conn->doRPCWithDefaultErrorHandling(payload, cb);
}
void RPC::getTPrivKey(QString addr, const std::function<void(json)>& cb) {
json payload = {
{"jsonrpc", "1.0"},
{"id", "someid"},
{"method", "dumpprivkey"},
{"params", { addr.toStdString() }},
};
conn->doRPCWithDefaultErrorHandling(payload, cb);
}
void RPC::importZPrivKey(QString addr, bool rescan, const std::function<void(json)>& cb) {
json payload = {
{"jsonrpc", "1.0"},
{"id", "someid"},
{"method", "z_importkey"},
{"params", { addr.toStdString(), (rescan? "yes" : "no") }},
};
conn->doRPCWithDefaultErrorHandling(payload, cb);
}
void RPC::importTPrivKey(QString addr, bool rescan, const std::function<void(json)>& cb) {
json payload = {
{"jsonrpc", "1.0"},
{"id", "someid"},
{"method", "importprivkey"},
{"params", { addr.toStdString(), (rescan? "yes" : "no") }},
};
conn->doRPCWithDefaultErrorHandling(payload, cb);
}
void RPC::validateAddress(QString address, const std::function<void(json)>& cb) {
QString method = Settings::isZAddress(address) ? "z_validateaddress" : "validateaddress";
json payload = {
{"jsonrpc", "1.0"},
{"id", "someid"},
{"method", method.toStdString() },
{"params", { address.toStdString() } },
};
conn->doRPCWithDefaultErrorHandling(payload, cb);
}
void RPC::getBalance(const std::function<void(json)>& cb) {
json payload = {
{"jsonrpc", "1.0"},
{"id", "someid"},
{"method", "z_gettotalbalance"},
{"params", {0}} // Get Unconfirmed balance as well.
};
conn->doRPCWithDefaultErrorHandling(payload, cb);
}
void RPC::getTransactions(const std::function<void(json)>& cb) {
json payload = {
{"jsonrpc", "1.0"},
{"id", "someid"},
{"method", "listtransactions"}
};
conn->doRPCWithDefaultErrorHandling(payload, cb);
}
void RPC::sendZTransaction(json params, const std::function<void(json)>& cb,
const std::function<void(QString)>& err) {
json payload = {
{"jsonrpc", "1.0"},
{"id", "someid"},
{"method", "z_sendmany"},
{"params", params}
};
conn->doRPC(payload, cb, [=] (auto reply, auto parsed) {
if (!parsed.is_discarded() && !parsed["error"]["message"].is_null()) {
err(QString::fromStdString(parsed["error"]["message"]));
} else {
err(reply->errorString());
}
});
}
/**
* Method to get all the private keys for both z and t addresses. It will make 2 batch calls,
* combine the result, and call the callback with a single list containing both the t-addr and z-addr
* private keys
*/
void RPC::getAllPrivKeys(const std::function<void(QList<QPair<QString, QString>>)> cb) {
if (conn == nullptr) {
// No connection, just return
return;
}
// A special function that will call the callback when two lists have been added
auto holder = new QPair<int, QList<QPair<QString, QString>>>();
holder->first = 0; // This is the number of times the callback has been called, initialized to 0
auto fnCombineTwoLists = [=] (QList<QPair<QString, QString>> list) {
// Increment the callback counter
holder->first++;
// Add all
std::copy(list.begin(), list.end(), std::back_inserter(holder->second));
// And if the caller has been called twice, do the parent callback with the
// collected list
if (holder->first == 2) {
// Sort so z addresses are on top
std::sort(holder->second.begin(), holder->second.end(),
[=] (auto a, auto b) { return a.first > b.first; });
cb(holder->second);
delete holder;
}
};
// A utility fn to do the batch calling
auto fnDoBatchGetPrivKeys = [=](json getAddressPayload, std::string privKeyDumpMethodName) {
conn->doRPCWithDefaultErrorHandling(getAddressPayload, [=] (json resp) {
QList<QString> addrs;
for (auto addr : resp.get<json::array_t>()) {
addrs.push_back(QString::fromStdString(addr.get<json::string_t>()));
}
// Then, do a batch request to get all the private keys
conn->doBatchRPC<QString>(
addrs,
[=] (auto addr) {
json payload = {
{"jsonrpc", "1.0"},
{"id", "someid"},
{"method", privKeyDumpMethodName},
{"params", { addr.toStdString() }},
};
return payload;
},
[=] (QMap<QString, json>* privkeys) {
QList<QPair<QString, QString>> allTKeys;
for (QString addr: privkeys->keys()) {
allTKeys.push_back(
QPair<QString, QString>(
addr,
QString::fromStdString(privkeys->value(addr).get<json::string_t>())));
}
fnCombineTwoLists(allTKeys);
delete privkeys;
}
);
});
};
// First get all the t and z addresses.
json payloadT = {
{"jsonrpc", "1.0"},
{"id", "someid"},
{"method", "getaddressesbyaccount"},
{"params", {""} }
};
json payloadZ = {
{"jsonrpc", "1.0"},
{"id", "someid"},
{"method", "z_listaddresses"}
};
fnDoBatchGetPrivKeys(payloadT, "dumpprivkey");
fnDoBatchGetPrivKeys(payloadZ, "z_exportkey");
}
// Build the RPC JSON Parameters for this tx
void RPC::fillTxJsonParams(json& params, Tx tx) {
Q_ASSERT(params.is_array());
// Get all the addresses and amounts
json allRecepients = json::array();
// For each addr/amt/memo, construct the JSON and also build the confirm dialog box
for (int i=0; i < tx.toAddrs.size(); i++) {
auto toAddr = tx.toAddrs[i];
// Construct the JSON params
json rec = json::object();
rec["address"] = toAddr.addr.toStdString();
// Force it through string for rounding. Without this, decimal points beyond 8 places
// will appear, causing an "invalid amount" error
rec["amount"] = Settings::getDecimalString(toAddr.amount).toStdString(); //.toDouble();
if (Settings::isZAddress(toAddr.addr) && !toAddr.encodedMemo.trimmed().isEmpty())
rec["memo"] = toAddr.encodedMemo.toStdString();
allRecepients.push_back(rec);
}
// Add sender
params.push_back(tx.fromAddr.toStdString());
params.push_back(allRecepients);
// Add fees if custom fees are allowed.
if (Settings::getInstance()->getAllowCustomFees()) {
params.push_back(1); // minconf
params.push_back(tx.fee);
}
}
void RPC::noConnection() {
QIcon i = QApplication::style()->standardIcon(QStyle::SP_MessageBoxCritical);
main->statusIcon->setPixmap(i.pixmap(16, 16));
main->statusIcon->setToolTip("");
main->statusLabel->setText(QObject::tr("No Connection"));
main->statusLabel->setToolTip("");
main->ui->statusBar->showMessage(QObject::tr("No Connection"), 1000);
// Clear balances table.
QMap<QString, double> emptyBalances;
QList<UnspentOutput> emptyOutputs;
balancesTableModel->setNewData(&emptyBalances, &emptyOutputs);
// Clear Transactions table.
QList<TransactionItem> emptyTxs;
transactionsTableModel->addTData(emptyTxs);
transactionsTableModel->addZRecvData(emptyTxs);
transactionsTableModel->addZSentData(emptyTxs);
// Clear balances
ui->balSheilded->setText("");
ui->balTransparent->setText("");
ui->balTotal->setText("");
ui->balSheilded->setToolTip("");
ui->balTransparent->setToolTip("");
ui->balTotal->setToolTip("");
// Clear send tab from address
ui->inputsCombo->clear();
}
// Refresh received z txs by calling z_listreceivedbyaddress/gettransaction
void RPC::refreshReceivedZTrans(QList<QString> zaddrs) {
if (conn == nullptr)
return noConnection();
// We'll only refresh the received Z txs if settings allows us.
if (!Settings::getInstance()->getSaveZtxs()) {
QList<TransactionItem> emptylist;
transactionsTableModel->addZRecvData(emptylist);
return;
}
// This method is complicated because z_listreceivedbyaddress only returns the txid, and
// we have to make a follow up call to gettransaction to get details of that transaction.
// Additionally, it has to be done in batches, because there are multiple z-Addresses,
// and each z-Addr can have multiple received txs.
// 1. For each z-Addr, get list of received txs
conn->doBatchRPC<QString>(zaddrs,
[=] (QString zaddr) {
json payload = {
{"jsonrpc", "1.0"},
{"id", "z_lrba"},
{"method", "z_listreceivedbyaddress"},
{"params", {zaddr.toStdString(), 0}} // Accept 0 conf as well.
};
return payload;
},
[=] (QMap<QString, json>* zaddrTxids) {
// Process all txids, removing duplicates. This can happen if the same address
// appears multiple times in a single tx's outputs.
QSet<QString> txids;
QMap<QString, QString> memos;
for (auto it = zaddrTxids->constBegin(); it != zaddrTxids->constEnd(); it++) {
auto zaddr = it.key();
for (auto& i : it.value().get<json::array_t>()) {
// Mark the address as used
usedAddresses->insert(zaddr, true);
// Filter out change txs
if (! i["change"].get<json::boolean_t>()) {
auto txid = QString::fromStdString(i["txid"].get<json::string_t>());
txids.insert(txid);
// Check for Memos
QString memoBytes = QString::fromStdString(i["memo"].get<json::string_t>());
if (!memoBytes.startsWith("f600")) {
QString memo(QByteArray::fromHex(
QByteArray::fromStdString(i["memo"].get<json::string_t>())));
if (!memo.trimmed().isEmpty())
memos[zaddr + txid] = memo;
}
}
}
}
// 2. For all txids, go and get the details of that txid.
conn->doBatchRPC<QString>(txids.toList(),
[=] (QString txid) {
json payload = {
{"jsonrpc", "1.0"},
{"id", "gettx"},
{"method", "gettransaction"},
{"params", {txid.toStdString()}}
};
return payload;
},
[=] (QMap<QString, json>* txidDetails) {
QList<TransactionItem> txdata;
// Combine them both together. For every zAddr's txid, get the amount, fee, confirmations and time
for (auto it = zaddrTxids->constBegin(); it != zaddrTxids->constEnd(); it++) {
for (auto& i : it.value().get<json::array_t>()) {
// Filter out change txs
if (i["change"].get<json::boolean_t>())
continue;
auto zaddr = it.key();
auto txid = QString::fromStdString(i["txid"].get<json::string_t>());
// Lookup txid in the map
auto txidInfo = txidDetails->value(txid);
qint64 timestamp;
if (txidInfo.find("time") != txidInfo.end()) {
timestamp = txidInfo["time"].get<json::number_unsigned_t>();
} else {
timestamp = txidInfo["blocktime"].get<json::number_unsigned_t>();
}
auto amount = i["amount"].get<json::number_float_t>();
auto confirmations = static_cast<long>(txidInfo["confirmations"].get<json::number_integer_t>());
TransactionItem tx{ QString("receive"), timestamp, zaddr, txid, amount,
confirmations, "", memos.value(zaddr + txid, "") };
txdata.push_front(tx);
}
}
transactionsTableModel->addZRecvData(txdata);
// Cleanup both responses;
delete zaddrTxids;
delete txidDetails;
}
);
}
);
}
/// This will refresh all the balance data from ycashd
void RPC::refresh(bool force) {
if (conn == nullptr)
return noConnection();
getInfoThenRefresh(force);
}
void RPC::getInfoThenRefresh(bool force) {
if (conn == nullptr)
return noConnection();
json payload = {
{"jsonrpc", "1.0"},
{"id", "someid"},
{"method", "getinfo"}
};
static bool prevCallSucceeded = false;
conn->doRPC(payload, [=] (const json& reply) {
prevCallSucceeded = true;
// Testnet?
if (!reply["testnet"].is_null()) {
Settings::getInstance()->setTestnet(reply["testnet"].get<json::boolean_t>());
};
// Connected, so display checkmark.
QIcon i(":/icons/res/connected.gif");
main->statusIcon->setPixmap(i.pixmap(16, 16));
static int lastBlock = 0;
int curBlock = reply["blocks"].get<json::number_integer_t>();
int version = reply["version"].get<json::number_integer_t>();
Settings::getInstance()->setZcashdVersion(version);
if ( force || (curBlock != lastBlock) ) {
// Something changed, so refresh everything.
lastBlock = curBlock;
// See if the turnstile migration has any steps that need to be done.
turnstile->executeMigrationStep();
refreshBalances();
refreshAddresses(); // This calls refreshZSentTransactions() and refreshReceivedZTrans()
refreshTransactions();
}
int connections = reply["connections"].get<json::number_integer_t>();
Settings::getInstance()->setPeers(connections);
if (connections == 0) {
// If there are no peers connected, then the internet is probably off or something else is wrong.
QIcon i = QApplication::style()->standardIcon(QStyle::SP_MessageBoxWarning);
main->statusIcon->setPixmap(i.pixmap(16, 16));
}
// Get network sol/s
if (ezcashd) {
json payload = {
{"jsonrpc", "1.0"},
{"id", "someid"},
{"method", "getnetworksolps"}
};
conn->doRPCIgnoreError(payload, [=](const json& reply) {
qint64 solrate = reply.get<json::number_unsigned_t>();
ui->numconnections->setText(QString::number(connections));
ui->solrate->setText(QString::number(solrate) % " Sol/s");
});
}
// Call to see if the blockchain is syncing.
json payload = {
{"jsonrpc", "1.0"},
{"id", "someid"},
{"method", "getblockchaininfo"}
};
conn->doRPCIgnoreError(payload, [=](const json& reply) {
auto progress = reply["verificationprogress"].get<double>();
bool isSyncing = progress < 0.9999; // 99.99%
int blockNumber = reply["blocks"].get<json::number_unsigned_t>();
int estimatedheight = 0;
if (reply.find("estimatedheight") != reply.end()) {
estimatedheight = reply["estimatedheight"].get<json::number_unsigned_t>();
}
Settings::getInstance()->setSyncing(isSyncing);
Settings::getInstance()->setBlockNumber(blockNumber);
// Update ycashd tab if it exists
if (ezcashd) {
if (isSyncing) {
QString txt = QString::number(blockNumber);
if (estimatedheight > 0) {
txt = txt % " / ~" % QString::number(estimatedheight);
// If estimated height is available, then use the download blocks
// as the progress instead of verification progress.
progress = (double)blockNumber / (double)estimatedheight;
}
txt = txt % " ( " % QString::number(progress * 100, 'f', 2) % "% )";
ui->blockheight->setText(txt);
ui->heightLabel->setText(QObject::tr("Downloading blocks"));
} else {
// If syncing is finished, we may have to remove the fastsync
// flag from zcash.conf
if (getConnection() != nullptr && getConnection()->config->fastsync) {
getConnection()->config->fastsync = false;
Settings::removeFromZcashConf(Settings::getInstance()->getZcashdConfLocation(),
"fastsync");
}
ui->blockheight->setText(QString::number(blockNumber));
ui->heightLabel->setText(QObject::tr("Block height"));
}
}
// Update the status bar
QString statusText = QString() %
(isSyncing ? QObject::tr("Syncing") : QObject::tr("Connected")) %
" (" %
(Settings::getInstance()->isTestnet() ? QObject::tr("testnet:") : "") %
QString::number(blockNumber) %
(isSyncing ? ("/" % QString::number(progress*100, 'f', 2) % "%") : QString()) %
")";
main->statusLabel->setText(statusText);
// Update the balances view to show a warning if the node is still syncing
ui->lblSyncWarning->setVisible(isSyncing);
ui->lblSyncWarningReceive->setVisible(isSyncing);
auto zecPrice = Settings::getUSDFormat(1);
QString tooltip;
if (connections > 0) {
tooltip = QObject::tr("Connected to ycashd");
}
else {
tooltip = QObject::tr("ycashd has no peer connections");
}
tooltip = tooltip % "(v " % QString::number(Settings::getInstance()->getZcashdVersion()) % ")";
if (!zecPrice.isEmpty()) {
tooltip = "1 " % Settings::getTokenName() % " = " % zecPrice % "\n" % tooltip;
}
main->statusLabel->setToolTip(tooltip);
main->statusIcon->setToolTip(tooltip);
});
}, [=](QNetworkReply* reply, const json&) {
// ycashd has probably disappeared.
this->noConnection();
// Prevent multiple dialog boxes, because these are called async
static bool shown = false;
if (!shown && prevCallSucceeded) { // show error only first time
shown = true;
QMessageBox::critical(main, QObject::tr("Connection Error"), QObject::tr("There was an error connecting to ycashd. The error was") + ": \n\n"
+ reply->errorString(), QMessageBox::StandardButton::Ok);
shown = false;
}
prevCallSucceeded = false;
});
}
void RPC::refreshAddresses() {
if (conn == nullptr)
return noConnection();
auto newzaddresses = new QList<QString>();
getZAddresses([=] (json reply) {
for (auto& it : reply.get<json::array_t>()) {
auto addr = QString::fromStdString(it.get<json::string_t>());
newzaddresses->push_back(addr);
}
delete zaddresses;
zaddresses = newzaddresses;
// Refresh the sent and received txs from all these z-addresses
refreshSentZTrans();
refreshReceivedZTrans(*zaddresses);
});
auto newtaddresses = new QList<QString>();
getTAddresses([=] (json reply) {
for (auto& it : reply.get<json::array_t>()) {
auto addr = QString::fromStdString(it.get<json::string_t>());
if (Settings::isTAddress(addr))
newtaddresses->push_back(addr);
}
delete taddresses;
taddresses = newtaddresses;
});
}
// Function to create the data model and update the views, used below.
void RPC::updateUI(bool anyUnconfirmed) {
ui->unconfirmedWarning->setVisible(anyUnconfirmed);
// Update balances model data, which will update the table too
balancesTableModel->setNewData(allBalances, utxos);
// Update from address
main->updateFromCombo();
};
// Function to process reply of the listunspent and z_listunspent API calls, used below.
bool RPC::processUnspent(const json& reply, QMap<QString, double>* balancesMap, QList<UnspentOutput>* newUtxos) {
bool anyUnconfirmed = false;
for (auto& it : reply.get<json::array_t>()) {
QString qsAddr = QString::fromStdString(it["address"]);
auto confirmations = it["confirmations"].get<json::number_unsigned_t>();
if (confirmations == 0) {
anyUnconfirmed = true;
}
newUtxos->push_back(
UnspentOutput{ qsAddr, QString::fromStdString(it["txid"]),
Settings::getDecimalString(it["amount"].get<json::number_float_t>()),
(int)confirmations, it["spendable"].get<json::boolean_t>() });
(*balancesMap)[qsAddr] = (*balancesMap)[qsAddr] + it["amount"].get<json::number_float_t>();
}
return anyUnconfirmed;
};
void RPC::refreshBalances() {
if (conn == nullptr)
return noConnection();
// 1. Get the Balances
getBalance([=] (json reply) {
auto balT = QString::fromStdString(reply["transparent"]).toDouble();
auto balZ = QString::fromStdString(reply["private"]).toDouble();
auto balTotal = QString::fromStdString(reply["total"]).toDouble();
AppDataModel::getInstance()->setBalances(balT, balZ);
ui->balSheilded ->setText(Settings::getZECDisplayFormat(balZ));
ui->balTransparent->setText(Settings::getZECDisplayFormat(balT));
ui->balTotal ->setText(Settings::getZECDisplayFormat(balTotal));
ui->balSheilded ->setToolTip(Settings::getUSDFormat(balZ));
ui->balTransparent->setToolTip(Settings::getUSDFormat(balT));
ui->balTotal ->setToolTip(Settings::getUSDFormat(balTotal));
});
// 2. Get the UTXOs
// First, create a new UTXO list. It will be replacing the existing list when everything is processed.
auto newUtxos = new QList<UnspentOutput>();
auto newBalances = new QMap<QString, double>();
// Call the Transparent and Z unspent APIs serially and then, once they're done, update the UI
getTransparentUnspent([=] (json reply) {
auto anyTUnconfirmed = processUnspent(reply, newBalances, newUtxos);
getZUnspent([=] (json reply) {
auto anyZUnconfirmed = processUnspent(reply, newBalances, newUtxos);
// Swap out the balances and UTXOs
delete allBalances;
delete utxos;
allBalances = newBalances;
utxos = newUtxos;
updateUI(anyTUnconfirmed || anyZUnconfirmed);
main->balancesReady();
});
});
}
void RPC::refreshTransactions() {
if (conn == nullptr)
return noConnection();
getTransactions([=] (json reply) {
QList<TransactionItem> txdata;
for (auto& it : reply.get<json::array_t>()) {
double fee = 0;
if (!it["fee"].is_null()) {
fee = it["fee"].get<json::number_float_t>();
}
QString address = (it["address"].is_null() ? "" : QString::fromStdString(it["address"]));
TransactionItem tx{
QString::fromStdString(it["category"]),
(qint64)it["time"].get<json::number_unsigned_t>(),
address,
QString::fromStdString(it["txid"]),
it["amount"].get<json::number_float_t>() + fee,
static_cast<long>(it["confirmations"].get<json::number_unsigned_t>()),
"", "" };
txdata.push_back(tx);
if (!address.isEmpty())
usedAddresses->insert(address, true);
}
// Update model data, which updates the table view
transactionsTableModel->addTData(txdata);
});
}
// Read sent Z transactions from the file.
void RPC::refreshSentZTrans() {
if (conn == nullptr)
return noConnection();
auto sentZTxs = SentTxStore::readSentTxFile();
// If there are no sent z txs, then empty the table.
// This happens when you clear history.
if (sentZTxs.isEmpty()) {
transactionsTableModel->addZSentData(sentZTxs);
return;
}
QList<QString> txids;
for (auto sentTx: sentZTxs) {
txids.push_back(sentTx.txid);
}
// Look up all the txids to get the confirmation count for them.
conn->doBatchRPC<QString>(txids,
[=] (QString txid) {
json payload = {
{"jsonrpc", "1.0"},
{"id", "senttxid"},
{"method", "gettransaction"},
{"params", {txid.toStdString()}}
};
return payload;
},
[=] (QMap<QString, json>* txidList) {
auto newSentZTxs = sentZTxs;
// Update the original sent list with the confirmation count
// TODO: This whole thing is kinda inefficient. We should probably just update the file
// with the confirmed block number, so we don't have to keep calling gettransaction for the
// sent items.
for (TransactionItem& sentTx: newSentZTxs) {
auto j = txidList->value(sentTx.txid);
if (j.is_null())
continue;
auto error = j["confirmations"].is_null();
if (!error)
sentTx.confirmations = j["confirmations"].get<json::number_integer_t>();
}
transactionsTableModel->addZSentData(newSentZTxs);
delete txidList;
}
);
}
void RPC::addNewTxToWatch(const QString& newOpid, WatchedTx wtx) {
watchingOps.insert(newOpid, wtx);
watchTxStatus();
}
/**
* Execute a transaction with the standard UI. i.e., standard status bar message and standard error
* handling
*/
void RPC::executeStandardUITransaction(Tx tx) {
executeTransaction(tx,
[=] (QString opid) {
ui->statusBar->showMessage(QObject::tr("Computing Tx: ") % opid);
},
[=] (QString, QString txid) {
ui->statusBar->showMessage(Settings::txidStatusMessage + " " + txid);
},
[=] (QString opid, QString errStr) {
ui->statusBar->showMessage(QObject::tr(" Tx ") % opid % QObject::tr(" failed"), 15 * 1000);
if (!opid.isEmpty())
errStr = QObject::tr("The transaction with id ") % opid % QObject::tr(" failed. The error was") + ":\n\n" + errStr;
QMessageBox::critical(main, QObject::tr("Transaction Error"), errStr, QMessageBox::Ok);
}
);
}
// Execute a transaction!
void RPC::executeTransaction(Tx tx,
const std::function<void(QString opid)> submitted,
const std::function<void(QString opid, QString txid)> computed,
const std::function<void(QString opid, QString errStr)> error) {
// First, create the json params
json params = json::array();
fillTxJsonParams(params, tx);
std::cout << std::setw(2) << params << std::endl;
sendZTransaction(params, [=](const json& reply) {
QString opid = QString::fromStdString(reply.get<json::string_t>());
// And then start monitoring the transaction
addNewTxToWatch( opid, WatchedTx { opid, tx, computed, error} );
submitted(opid);
},
[=](QString errStr) {
error("", errStr);
});
}
void RPC::watchTxStatus() {
if (conn == nullptr)
return noConnection();
// Make an RPC to load pending operation statues
json payload = {
{"jsonrpc", "1.0"},
{"id", "someid"},
{"method", "z_getoperationstatus"},
};
conn->doRPCIgnoreError(payload, [=] (const json& reply) {
// There's an array for each item in the status
for (auto& it : reply.get<json::array_t>()) {
// If we were watching this Tx and its status became "success", then we'll show a status bar alert
QString id = QString::fromStdString(it["id"]);
if (watchingOps.contains(id)) {
// And if it ended up successful
QString status = QString::fromStdString(it["status"]);
main->loadingLabel->setVisible(false);
if (status == "success") {
auto txid = QString::fromStdString(it["result"]["txid"]);
SentTxStore::addToSentTx(watchingOps[id].tx, txid);
auto wtx = watchingOps[id];
watchingOps.remove(id);
wtx.completed(id, txid);
// Refresh balances to show unconfirmed balances
refresh(true);
} else if (status == "failed") {
// If it failed, then we'll actually show a warning.
auto errorMsg = QString::fromStdString(it["error"]["message"]);
auto wtx = watchingOps[id];
watchingOps.remove(id);
wtx.error(id, errorMsg);
}
}
if (watchingOps.isEmpty()) {
txTimer->start(Settings::updateSpeed);
} else {