forked from dashpay/dash
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoverviewpage.cpp
757 lines (639 loc) · 34.7 KB
/
overviewpage.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
// Copyright (c) 2011-2020 The Bitcoin Core developers
// Copyright (c) 2014-2024 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/overviewpage.h>
#include <qt/forms/ui_overviewpage.h>
#include <qt/bitcoinunits.h>
#include <qt/clientmodel.h>
#include <qt/guiutil.h>
#include <qt/optionsmodel.h>
#include <qt/transactionfilterproxy.h>
#include <qt/transactionoverviewwidget.h>
#include <qt/transactiontablemodel.h>
#include <qt/utilitydialog.h>
#include <qt/walletmodel.h>
#include <coinjoin/options.h>
#include <interfaces/coinjoin.h>
#include <algorithm>
#include <map>
#include <cmath>
#include <QAbstractItemDelegate>
#include <QApplication>
#include <QDateTime>
#include <QPainter>
#include <QSettings>
#include <QStatusTipEvent>
#include <QTimer>
#define ITEM_HEIGHT 54
#define NUM_ITEMS_DISABLED 5
#define NUM_ITEMS_ENABLED_NORMAL 6
#define NUM_ITEMS_ENABLED_ADVANCED 8
Q_DECLARE_METATYPE(interfaces::WalletBalances)
class TxViewDelegate : public QAbstractItemDelegate
{
Q_OBJECT
public:
explicit TxViewDelegate(QObject* parent = nullptr) :
QAbstractItemDelegate(), unit(BitcoinUnits::DASH)
{
connect(this, &TxViewDelegate::width_changed, this, &TxViewDelegate::sizeHintChanged);
}
inline void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index ) const override
{
painter->save();
QRect mainRect = option.rect;
int xspace = 8;
int ypad = 8;
int halfheight = (mainRect.height() - 2*ypad)/2;
QRect rectTopHalf(mainRect.left() + xspace, mainRect.top() + ypad, mainRect.width() - xspace, halfheight);
QRect rectBottomHalf(mainRect.left() + xspace, mainRect.top() + ypad + halfheight + 5, mainRect.width() - xspace, halfheight);
QRect rectBounding;
QColor colorForeground;
qreal initialFontSize = painter->font().pointSizeF();
// Grab model indexes for desired data from TransactionTableModel
QModelIndex indexDate = index.sibling(index.row(), TransactionTableModel::Date);
QModelIndex indexAmount = index.sibling(index.row(), TransactionTableModel::Amount);
QModelIndex indexAddress = index.sibling(index.row(), TransactionTableModel::ToAddress);
// Draw first line (with slightly bigger font than the second line will get)
// Content: Date/Time, Optional IS indicator, Amount
painter->setFont(GUIUtil::getFont(GUIUtil::FontWeight::Normal, false, GUIUtil::getScaledFontSize(initialFontSize * 1.17)));
// Date/Time
colorForeground = qvariant_cast<QColor>(indexDate.data(Qt::ForegroundRole));
QString strDate = indexDate.data(Qt::DisplayRole).toString();
painter->setPen(colorForeground);
painter->drawText(rectTopHalf, Qt::AlignLeft | Qt::AlignVCenter, strDate, &rectBounding);
// Optional IS indicator
QIcon iconInstantSend = qvariant_cast<QIcon>(indexAddress.data(TransactionTableModel::RawDecorationRole));
QRect rectInstantSend(rectBounding.right() + 5, rectTopHalf.top(), 16, halfheight);
iconInstantSend.paint(painter, rectInstantSend);
// Amount
colorForeground = qvariant_cast<QColor>(indexAmount.data(Qt::ForegroundRole));
// Note: do NOT use Qt::DisplayRole, have format properly here
qint64 nAmount = index.data(TransactionTableModel::AmountRole).toLongLong();
QString strAmount = BitcoinUnits::floorWithUnit(unit, nAmount, true, BitcoinUnits::SeparatorStyle::ALWAYS);
painter->setPen(colorForeground);
QRect amount_bounding_rect;
painter->drawText(rectTopHalf, Qt::AlignRight | Qt::AlignVCenter, strAmount, &amount_bounding_rect);
// Draw second line (with the initial font)
// Content: Address/label, Optional Watchonly indicator
painter->setFont(GUIUtil::getFont(GUIUtil::FontWeight::Normal, false, GUIUtil::getScaledFontSize(initialFontSize)));
// Address/Label
colorForeground = qvariant_cast<QColor>(indexAddress.data(Qt::ForegroundRole));
QString address = indexAddress.data(Qt::DisplayRole).toString();
painter->setPen(colorForeground);
painter->drawText(rectBottomHalf, Qt::AlignLeft | Qt::AlignVCenter, address, &rectBounding);
int address_rect_min_width = rectBounding.width();
// Optional Watchonly indicator
if (index.data(TransactionTableModel::WatchonlyRole).toBool())
{
QIcon iconWatchonly = qvariant_cast<QIcon>(index.data(TransactionTableModel::WatchonlyDecorationRole));
QRect rectWatchonly(rectBounding.right() + 5, rectBottomHalf.top(), 16, halfheight);
iconWatchonly.paint(painter, rectWatchonly);
}
const int minimum_width = std::max(address_rect_min_width, amount_bounding_rect.width() /*+ date_bounding_rect.width() */);
const auto search = m_minimum_width.find(index.row());
if (search == m_minimum_width.end() || search->second != minimum_width) {
m_minimum_width[index.row()] = minimum_width;
Q_EMIT width_changed(index);
}
painter->restore();
}
inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override
{
const auto search = m_minimum_width.find(index.row());
const int minimum_text_width = search == m_minimum_width.end() ? 0 : search->second;
return {ITEM_HEIGHT + 8 + minimum_text_width, ITEM_HEIGHT};
}
int unit;
Q_SIGNALS:
//! An intermediate signal for emitting from the `paint() const` member function.
void width_changed(const QModelIndex& index) const;
private:
mutable std::map<int, int> m_minimum_width;
};
#include <qt/overviewpage.moc>
OverviewPage::OverviewPage(QWidget* parent) :
QWidget(parent),
timer(nullptr),
ui(new Ui::OverviewPage),
clientModel(nullptr),
walletModel(nullptr),
cachedNumISLocks(-1),
txdelegate(new TxViewDelegate(this))
{
ui->setupUi(this);
GUIUtil::setFont({ui->label_4,
ui->label_5,
ui->labelCoinJoinHeader
}, GUIUtil::FontWeight::Bold, 16);
GUIUtil::setFont({ui->labelTotalText,
ui->labelWatchTotal,
ui->labelTotal
}, GUIUtil::FontWeight::Bold, 14);
GUIUtil::setFont({ui->labelBalanceText,
ui->labelPendingText,
ui->labelImmatureText,
ui->labelWatchonly,
ui->labelSpendable
}, GUIUtil::FontWeight::Bold);
GUIUtil::updateFonts();
m_balances.balance = -1;
// Recent transactions
ui->listTransactions->setItemDelegate(txdelegate);
// Note: minimum height of listTransactions will be set later in updateAdvancedCJUI() to reflect actual settings
ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false);
connect(ui->listTransactions, &TransactionOverviewWidget::clicked, this, &OverviewPage::handleTransactionClicked);
// init "out of sync" warning labels
ui->labelWalletStatus->setText("(" + tr("out of sync") + ")");
ui->labelCoinJoinSyncStatus->setText("(" + tr("out of sync") + ")");
ui->labelTransactionsStatus->setText("(" + tr("out of sync") + ")");
QString strCoinJoinName = QString::fromStdString(gCoinJoinName);
ui->labelCoinJoinHeader->setText(strCoinJoinName);
ui->labelAnonymizedText->setText(tr("%1 Balance").arg(strCoinJoinName));
// hide PS frame (helps to preserve saved size)
// we'll setup and make it visible in coinJoinStatus() later
ui->frameCoinJoin->setVisible(false);
// start with displaying the "out of sync" warnings
showOutOfSyncWarning(true);
timer = new QTimer(this);
connect(timer, &QTimer::timeout, [this]{ coinJoinStatus(); });
}
void OverviewPage::handleTransactionClicked(const QModelIndex &index)
{
if(filter)
Q_EMIT transactionClicked(filter->mapToSource(index));
}
void OverviewPage::handleOutOfSyncWarningClicks()
{
Q_EMIT outOfSyncWarningClicked();
}
void OverviewPage::setPrivacy(bool privacy)
{
m_privacy = privacy;
if (m_balances.balance != -1) {
setBalance(m_balances);
}
ui->listTransactions->setVisible(!m_privacy);
const QString status_tip = m_privacy ? tr("Discreet mode activated for the Overview tab. To unmask the values, uncheck Settings->Discreet mode.") : "";
setStatusTip(status_tip);
QStatusTipEvent event(status_tip);
QApplication::sendEvent(this, &event);
}
OverviewPage::~OverviewPage()
{
delete ui;
}
void OverviewPage::setBalance(const interfaces::WalletBalances& balances)
{
int unit = walletModel->getOptionsModel()->getDisplayUnit();
m_balances = balances;
if (walletModel->wallet().isLegacy()) {
if (walletModel->wallet().privateKeysDisabled()) {
ui->labelBalance->setText(BitcoinUnits::floorHtmlWithPrivacy(unit, balances.watch_only_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));
ui->labelUnconfirmed->setText(BitcoinUnits::floorHtmlWithPrivacy(unit, balances.unconfirmed_watch_only_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));
ui->labelImmature->setText(BitcoinUnits::floorHtmlWithPrivacy(unit, balances.immature_watch_only_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));
ui->labelTotal->setText(BitcoinUnits::floorHtmlWithPrivacy(unit, balances.watch_only_balance + balances.unconfirmed_watch_only_balance + balances.immature_watch_only_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));
} else {
ui->labelBalance->setText(BitcoinUnits::floorHtmlWithPrivacy(unit, balances.balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));
ui->labelUnconfirmed->setText(BitcoinUnits::floorHtmlWithPrivacy(unit, balances.unconfirmed_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));
ui->labelImmature->setText(BitcoinUnits::floorHtmlWithPrivacy(unit, balances.immature_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));
ui->labelAnonymized->setText(BitcoinUnits::floorHtmlWithPrivacy(unit, balances.anonymized_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));
ui->labelTotal->setText(BitcoinUnits::floorHtmlWithPrivacy(unit, balances.balance + balances.unconfirmed_balance + balances.immature_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));
ui->labelWatchAvailable->setText(BitcoinUnits::floorHtmlWithPrivacy(unit, balances.watch_only_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));
ui->labelWatchPending->setText(BitcoinUnits::floorHtmlWithPrivacy(unit, balances.unconfirmed_watch_only_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));
ui->labelWatchImmature->setText(BitcoinUnits::floorHtmlWithPrivacy(unit, balances.immature_watch_only_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));
ui->labelWatchTotal->setText(BitcoinUnits::floorHtmlWithPrivacy(unit, balances.watch_only_balance + balances.unconfirmed_watch_only_balance + balances.immature_watch_only_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));
}
} else {
ui->labelBalance->setText(BitcoinUnits::floorHtmlWithPrivacy(unit, balances.balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));
ui->labelUnconfirmed->setText(BitcoinUnits::floorHtmlWithPrivacy(unit, balances.unconfirmed_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));
ui->labelImmature->setText(BitcoinUnits::floorHtmlWithPrivacy(unit, balances.immature_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));
ui->labelAnonymized->setText(BitcoinUnits::floorHtmlWithPrivacy(unit, balances.anonymized_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));
ui->labelTotal->setText(BitcoinUnits::floorHtmlWithPrivacy(unit, balances.balance + balances.unconfirmed_balance + balances.immature_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));
}
// only show immature (newly mined) balance if it's non-zero, so as not to complicate things
// for the non-mining users
bool fDebugUI = gArgs.GetBoolArg("-debug-ui", false);
bool showImmature = fDebugUI || balances.immature_balance != 0;
bool showWatchOnlyImmature = fDebugUI || balances.immature_watch_only_balance != 0;
// for symmetry reasons also show immature label when the watch-only one is shown
ui->labelImmature->setVisible(showImmature || showWatchOnlyImmature);
ui->labelImmatureText->setVisible(showImmature || showWatchOnlyImmature);
ui->labelWatchImmature->setVisible(!walletModel->wallet().privateKeysDisabled() && showWatchOnlyImmature); // show watch-only immature balance
updateCoinJoinProgress();
int numISLocks = walletModel->getNumISLocks();
if(cachedNumISLocks != numISLocks) {
cachedNumISLocks = numISLocks;
ui->listTransactions->update();
}
}
// show/hide watch-only labels
void OverviewPage::updateWatchOnlyLabels(bool showWatchOnly)
{
ui->labelSpendable->setVisible(showWatchOnly); // show spendable label (only when watch-only is active)
ui->labelWatchonly->setVisible(showWatchOnly); // show watch-only label
ui->lineWatchBalance->setVisible(showWatchOnly); // show watch-only balance separator line
ui->labelWatchAvailable->setVisible(showWatchOnly); // show watch-only available balance
ui->labelWatchPending->setVisible(showWatchOnly); // show watch-only pending balance
ui->labelWatchTotal->setVisible(showWatchOnly); // show watch-only total balance
if (!showWatchOnly){
ui->labelWatchImmature->hide();
}
else{
ui->labelBalance->setIndent(20);
ui->labelUnconfirmed->setIndent(20);
ui->labelImmature->setIndent(20);
ui->labelTotal->setIndent(20);
}
}
void OverviewPage::setClientModel(ClientModel *model)
{
this->clientModel = model;
if (model) {
// Show warning, for example if this is a prerelease version
connect(model, &ClientModel::alertsChanged, this, &OverviewPage::updateAlerts);
updateAlerts(model->getStatusBarWarnings());
}
}
void OverviewPage::setWalletModel(WalletModel *model)
{
this->walletModel = model;
if(model && model->getOptionsModel())
{
// update the display unit, to not use the default ("DASH")
updateDisplayUnit();
// Keep up to date with wallet
interfaces::Wallet& wallet = model->wallet();
interfaces::WalletBalances balances = wallet.getBalances();
setBalance(balances);
connect(model, &WalletModel::balanceChanged, this, &OverviewPage::setBalance);
connect(model->getOptionsModel(), &OptionsModel::displayUnitChanged, this, &OverviewPage::updateDisplayUnit);
updateWatchOnlyLabels((wallet.haveWatchOnly() && !model->wallet().privateKeysDisabled()) || gArgs.GetBoolArg("-debug-ui", false));
connect(model, &WalletModel::notifyWatchonlyChanged, [this](bool showWatchOnly) {
updateWatchOnlyLabels(showWatchOnly && !walletModel->wallet().privateKeysDisabled());
});
// explicitly update PS frame and transaction list to reflect actual settings
updateAdvancedCJUI(model->getOptionsModel()->getShowAdvancedCJUI());
connect(model->getOptionsModel(), &OptionsModel::coinJoinRoundsChanged, this, &OverviewPage::updateCoinJoinProgress);
connect(model->getOptionsModel(), &OptionsModel::coinJoinAmountChanged, this, &OverviewPage::updateCoinJoinProgress);
connect(model->getOptionsModel(), &OptionsModel::AdvancedCJUIChanged, this, &OverviewPage::updateAdvancedCJUI);
connect(model->getOptionsModel(), &OptionsModel::coinJoinEnabledChanged, [=]() {
coinJoinStatus(true);
});
// Disable coinJoinClient builtin support for automatic backups while we are in GUI,
// we'll handle automatic backups and user warnings in coinJoinStatus()
walletModel->coinJoin()->disableAutobackups();
connect(ui->toggleCoinJoin, &QPushButton::clicked, this, &OverviewPage::toggleCoinJoin);
// coinjoin buttons will not react to spacebar must be clicked on
ui->toggleCoinJoin->setFocusPolicy(Qt::NoFocus);
}
}
void OverviewPage::updateDisplayUnit()
{
if(walletModel && walletModel->getOptionsModel())
{
nDisplayUnit = walletModel->getOptionsModel()->getDisplayUnit();
if (m_balances.balance != -1) {
setBalance(m_balances);
}
// Update txdelegate->unit with the current unit
txdelegate->unit = nDisplayUnit;
ui->listTransactions->update();
}
}
void OverviewPage::updateAlerts(const QString &warnings)
{
this->ui->labelAlerts->setVisible(!warnings.isEmpty());
this->ui->labelAlerts->setText(warnings);
}
void OverviewPage::showOutOfSyncWarning(bool fShow)
{
ui->labelWalletStatus->setVisible(fShow);
ui->labelCoinJoinSyncStatus->setVisible(fShow);
ui->labelTransactionsStatus->setVisible(fShow);
}
void OverviewPage::updateCoinJoinProgress()
{
if (!walletModel || !clientModel || clientModel->node().shutdownRequested() || !clientModel->masternodeSync().isBlockchainSynced()) return;
QString strAmountAndRounds;
QString strCoinJoinAmount = BitcoinUnits::formatHtmlWithUnit(nDisplayUnit, clientModel->coinJoinOptions().getAmount() * COIN, false, BitcoinUnits::SeparatorStyle::ALWAYS);
if(m_balances.balance == 0)
{
ui->coinJoinProgress->setValue(0);
ui->coinJoinProgress->setToolTip(tr("No inputs detected"));
// when balance is zero just show info from settings
strCoinJoinAmount = strCoinJoinAmount.remove(strCoinJoinAmount.indexOf("."), BitcoinUnits::decimals(nDisplayUnit) + 1);
strAmountAndRounds = strCoinJoinAmount + " / " + tr("%n Rounds", "", clientModel->coinJoinOptions().getRounds());
ui->labelAmountRounds->setToolTip(tr("No inputs detected"));
ui->labelAmountRounds->setText(strAmountAndRounds);
return;
}
CAmount nAnonymizableBalance = walletModel->wallet().getAnonymizableBalance(false, false);
CAmount nMaxToAnonymize = nAnonymizableBalance + m_balances.anonymized_balance;
// If it's more than the anon threshold, limit to that.
if (nMaxToAnonymize > clientModel->coinJoinOptions().getAmount() * COIN) nMaxToAnonymize = clientModel->coinJoinOptions().getAmount() * COIN;
if(nMaxToAnonymize == 0) return;
if (nMaxToAnonymize >= clientModel->coinJoinOptions().getAmount() * COIN) {
ui->labelAmountRounds->setToolTip(tr("Found enough compatible inputs to mix %1")
.arg(strCoinJoinAmount));
strCoinJoinAmount = strCoinJoinAmount.remove(strCoinJoinAmount.indexOf("."), BitcoinUnits::decimals(nDisplayUnit) + 1);
strAmountAndRounds = strCoinJoinAmount + " / " + tr("%n Rounds", "", clientModel->coinJoinOptions().getRounds());
} else {
QString strMaxToAnonymize = BitcoinUnits::formatHtmlWithUnit(nDisplayUnit, nMaxToAnonymize, false, BitcoinUnits::SeparatorStyle::ALWAYS);
ui->labelAmountRounds->setToolTip(tr("Not enough compatible inputs to mix <span style='%1'>%2</span>,<br>"
"will mix <span style='%1'>%3</span> instead")
.arg(GUIUtil::getThemedStyleQString(GUIUtil::ThemedStyle::TS_ERROR))
.arg(strCoinJoinAmount)
.arg(strMaxToAnonymize));
strMaxToAnonymize = strMaxToAnonymize.remove(strMaxToAnonymize.indexOf("."), BitcoinUnits::decimals(nDisplayUnit) + 1);
strAmountAndRounds = "<span style='" + GUIUtil::getThemedStyleQString(GUIUtil::ThemedStyle::TS_ERROR) + "'>" +
QString(BitcoinUnits::factor(nDisplayUnit) == 1 ? "" : "~") + strMaxToAnonymize +
" / " + tr("%n Rounds", "", clientModel->coinJoinOptions().getRounds()) + "</span>";
}
ui->labelAmountRounds->setText(strAmountAndRounds);
if (!fShowAdvancedCJUI) return;
CAmount nDenominatedConfirmedBalance;
CAmount nDenominatedUnconfirmedBalance;
CAmount nNormalizedAnonymizedBalance;
float nAverageAnonymizedRounds;
nDenominatedConfirmedBalance = walletModel->wallet().getDenominatedBalance(false);
nDenominatedUnconfirmedBalance = walletModel->wallet().getDenominatedBalance(true);
nNormalizedAnonymizedBalance = walletModel->wallet().getNormalizedAnonymizedBalance();
nAverageAnonymizedRounds = walletModel->wallet().getAverageAnonymizedRounds();
// calculate parts of the progress, each of them shouldn't be higher than 1
// progress of denominating
float denomPart = 0;
// mixing progress of denominated balance
float anonNormPart = 0;
// completeness of full amount anonymization
float anonFullPart = 0;
CAmount denominatedBalance = nDenominatedConfirmedBalance + nDenominatedUnconfirmedBalance;
denomPart = (float)denominatedBalance / nMaxToAnonymize;
denomPart = denomPart > 1 ? 1 : denomPart;
denomPart *= 100;
anonNormPart = (float)nNormalizedAnonymizedBalance / nMaxToAnonymize;
anonNormPart = anonNormPart > 1 ? 1 : anonNormPart;
anonNormPart *= 100;
anonFullPart = (float)m_balances.anonymized_balance / nMaxToAnonymize;
anonFullPart = anonFullPart > 1 ? 1 : anonFullPart;
anonFullPart *= 100;
// apply some weights to them ...
float denomWeight = 1;
float anonNormWeight = clientModel->coinJoinOptions().getRounds();
float anonFullWeight = 2;
float fullWeight = denomWeight + anonNormWeight + anonFullWeight;
// ... and calculate the whole progress
float denomPartCalc = ceilf((denomPart * denomWeight / fullWeight) * 100) / 100;
float anonNormPartCalc = ceilf((anonNormPart * anonNormWeight / fullWeight) * 100) / 100;
float anonFullPartCalc = ceilf((anonFullPart * anonFullWeight / fullWeight) * 100) / 100;
float progress = denomPartCalc + anonNormPartCalc + anonFullPartCalc;
if(progress >= 100) progress = 100;
ui->coinJoinProgress->setValue(progress);
QString strToolPip = ("<b>" + tr("Overall progress") + ": %1%</b><br/>" +
tr("Denominated") + ": %2%<br/>" +
tr("Partially mixed") + ": %3%<br/>" +
tr("Mixed") + ": %4%<br/>" +
tr("Denominated inputs have %5 of %n rounds on average", "", clientModel->coinJoinOptions().getRounds()))
.arg(progress).arg(denomPart).arg(anonNormPart).arg(anonFullPart)
.arg(nAverageAnonymizedRounds);
ui->coinJoinProgress->setToolTip(strToolPip);
}
void OverviewPage::updateAdvancedCJUI(bool fShowAdvancedCJUI)
{
if (!walletModel || !clientModel) return;
this->fShowAdvancedCJUI = fShowAdvancedCJUI;
coinJoinStatus(true);
}
void OverviewPage::coinJoinStatus(bool fForce)
{
if (!walletModel || !clientModel) return;
if (!fForce && (clientModel->node().shutdownRequested() || !clientModel->masternodeSync().isBlockchainSynced())) return;
// Disable any PS UI for masternode or when autobackup is disabled or failed for whatever reason
if (clientModel->node().isMasternode() || nWalletBackups <= 0) {
DisableCoinJoinCompletely();
if (nWalletBackups <= 0) {
ui->labelCoinJoinEnabled->setToolTip(tr("Automatic backups are disabled, no mixing available!"));
}
return;
}
bool fIsEnabled = clientModel->coinJoinOptions().isEnabled();
ui->frameCoinJoin->setVisible(fIsEnabled);
if (!fIsEnabled) {
SetupTransactionList(NUM_ITEMS_DISABLED);
if (timer != nullptr) {
timer->stop();
}
return;
}
if (timer != nullptr && !timer->isActive()) {
timer->start(1000);
}
// Wrap all coinjoin related widgets we want to show/hide state based.
// Value of the map contains a flag if this widget belongs to the advanced
// CoinJoin UI option or not. True if it does, false if not.
std::map<QWidget*, bool> coinJoinWidgets = {
{ui->labelCompletitionText, true},
{ui->coinJoinProgress, true},
{ui->labelSubmittedDenomText, true},
{ui->labelSubmittedDenom, true},
{ui->labelAmountAndRoundsText, false},
{ui->labelAmountRounds, false}
};
auto setWidgetsVisible = [&](bool fVisible) {
static bool fInitial{true};
static bool fLastVisible{false};
static bool fLastShowAdvanced{false};
// Only update the widget's visibility if something changed since the last call of setWidgetsVisible
if (fLastShowAdvanced == fShowAdvancedCJUI && fLastVisible == fVisible) {
if (fInitial) {
fInitial = false;
} else {
return;
}
}
// Set visible if: fVisible and not advanced UI element or advanced ui element and advanced ui active
for (const auto& it : coinJoinWidgets) {
it.first->setVisible(fVisible && (!it.second || it.second == fShowAdvancedCJUI));
}
fLastVisible = fVisible;
fLastShowAdvanced = fShowAdvancedCJUI;
};
static int64_t nLastDSProgressBlockTime = 0;
int nBestHeight = clientModel->node().getNumBlocks();
// We are processing more than 1 block per second, we'll just leave
if (nBestHeight > walletModel->coinJoin()->getCachedBlocks() && GetTime() - nLastDSProgressBlockTime <= 1) return;
nLastDSProgressBlockTime = GetTime();
QString strKeysLeftText(tr("keys left: %1").arg(walletModel->getKeysLeftSinceAutoBackup()));
if(walletModel->getKeysLeftSinceAutoBackup() < COINJOIN_KEYS_THRESHOLD_WARNING) {
strKeysLeftText = "<span style='" + GUIUtil::getThemedStyleQString(GUIUtil::ThemedStyle::TS_ERROR) + "'>" + strKeysLeftText + "</span>";
}
if (!walletModel->wallet().isLegacy()) {
// we don't need in auto-back for case of Descriptor wallets
strKeysLeftText = "";
}
ui->labelCoinJoinEnabled->setToolTip(strKeysLeftText);
QString strCoinJoinName = QString::fromStdString(gCoinJoinName);
if (!walletModel->coinJoin()->isMixing()) {
if (nBestHeight != walletModel->coinJoin()->getCachedBlocks()) {
walletModel->coinJoin()->setCachedBlocks(nBestHeight);
updateCoinJoinProgress();
}
setWidgetsVisible(false);
ui->toggleCoinJoin->setText(tr("Start %1").arg(strCoinJoinName));
QString strEnabled = tr("Disabled");
// Show how many keys left in advanced PS UI mode only
if (fShowAdvancedCJUI && !strKeysLeftText.isEmpty()) strEnabled += ", " + strKeysLeftText;
ui->labelCoinJoinEnabled->setText(strEnabled);
// If mixing isn't active always show the lower number of txes because there are
// anyway the most PS widgets hidden.
SetupTransactionList(NUM_ITEMS_ENABLED_NORMAL);
return;
} else {
SetupTransactionList(fShowAdvancedCJUI ? NUM_ITEMS_ENABLED_ADVANCED : NUM_ITEMS_ENABLED_NORMAL);
}
// Warn user that wallet is running out of keys
// NOTE: we do NOT warn user and do NOT create autobackups if mixing is not running
if (walletModel->wallet().isLegacy() && nWalletBackups > 0 && walletModel->getKeysLeftSinceAutoBackup() < COINJOIN_KEYS_THRESHOLD_WARNING) {
QSettings settings;
if(settings.value("fLowKeysWarning").toBool()) {
QString strWarn = tr("Very low number of keys left since last automatic backup!") + "<br><br>" +
tr("We are about to create a new automatic backup for you, however "
"<span style='%1'> you should always make sure you have backups "
"saved in some safe place</span>!").arg(GUIUtil::getThemedStyleQString(GUIUtil::ThemedStyle::TS_COMMAND)) + "<br><br>" +
tr("Note: You can turn this message off in options.");
ui->labelCoinJoinEnabled->setToolTip(strWarn);
LogPrint(BCLog::COINJOIN, "OverviewPage::coinJoinStatus -- Very low number of keys left since last automatic backup, warning user and trying to create new backup...\n");
QMessageBox::warning(this, strCoinJoinName, strWarn, QMessageBox::Ok, QMessageBox::Ok);
} else {
LogPrint(BCLog::COINJOIN, "OverviewPage::coinJoinStatus -- Very low number of keys left since last automatic backup, skipping warning and trying to create new backup...\n");
}
QString strBackupWarning;
QString strBackupError;
if(!walletModel->autoBackupWallet(strBackupWarning, strBackupError)) {
if (!strBackupWarning.isEmpty()) {
// It's still more or less safe to continue but warn user anyway
LogPrint(BCLog::COINJOIN, "OverviewPage::coinJoinStatus -- WARNING! Something went wrong on automatic backup: %s\n", strBackupWarning.toStdString());
QMessageBox::warning(this, strCoinJoinName,
tr("WARNING! Something went wrong on automatic backup") + ":<br><br>" + strBackupWarning,
QMessageBox::Ok, QMessageBox::Ok);
}
if (!strBackupError.isEmpty()) {
// Things are really broken, warn user and stop mixing immediately
LogPrint(BCLog::COINJOIN, "OverviewPage::coinJoinStatus -- ERROR! Failed to create automatic backup: %s\n", strBackupError.toStdString());
QMessageBox::warning(this, strCoinJoinName,
tr("ERROR! Failed to create automatic backup") + ":<br><br>" + strBackupError + "<br>" +
tr("Mixing is disabled, please close your wallet and fix the issue!"),
QMessageBox::Ok, QMessageBox::Ok);
}
}
}
QString strEnabled = walletModel->coinJoin()->isMixing() ? tr("Enabled") : tr("Disabled");
// Show how many keys left in advanced PS UI mode only
if(fShowAdvancedCJUI && !strKeysLeftText.isEmpty()) strEnabled += ", " + strKeysLeftText;
ui->labelCoinJoinEnabled->setText(strEnabled);
if (walletModel->wallet().isLegacy()) {
if(nWalletBackups == -1) {
// Automatic backup failed, nothing else we can do until user fixes the issue manually
DisableCoinJoinCompletely();
QString strError = tr("ERROR! Failed to create automatic backup") + ", " +
tr("see debug.log for details.") + "<br><br>" +
tr("Mixing is disabled, please close your wallet and fix the issue!");
ui->labelCoinJoinEnabled->setToolTip(strError);
return;
} else if(nWalletBackups == -2) {
// We were able to create automatic backup but keypool was not replenished because wallet is locked.
QString strWarning = tr("WARNING! Failed to replenish keypool, please unlock your wallet to do so.");
ui->labelCoinJoinEnabled->setToolTip(strWarning);
}
}
// check coinjoin status and unlock if needed
if(nBestHeight != walletModel->coinJoin()->getCachedBlocks()) {
// Balance and number of transactions might have changed
walletModel->coinJoin()->setCachedBlocks(nBestHeight);
updateCoinJoinProgress();
}
setWidgetsVisible(true);
ui->labelSubmittedDenom->setText(QString(walletModel->coinJoin()->getSessionDenoms().c_str()));
}
void OverviewPage::toggleCoinJoin(){
QSettings settings;
// Popup some information on first mixing
QString hasMixed = settings.value("hasMixed").toString();
QString strCoinJoinName = QString::fromStdString(gCoinJoinName);
if(hasMixed.isEmpty()){
QMessageBox::information(this, strCoinJoinName,
tr("If you don't want to see internal %1 fees/transactions select \"Most Common\" as Type on the \"Transactions\" tab.").arg(strCoinJoinName),
QMessageBox::Ok, QMessageBox::Ok);
settings.setValue("hasMixed", "hasMixed");
}
if (!walletModel->coinJoin()->isMixing()) {
auto& options = walletModel->node().coinJoinOptions();
const CAmount nMinAmount = options.getSmallestDenomination() + options.getMaxCollateralAmount();
if(m_balances.balance < nMinAmount) {
QString strMinAmount(BitcoinUnits::formatWithUnit(nDisplayUnit, nMinAmount));
QMessageBox::warning(this, strCoinJoinName,
tr("%1 requires at least %2 to use.").arg(strCoinJoinName).arg(strMinAmount),
QMessageBox::Ok, QMessageBox::Ok);
return;
}
// if wallet is locked, ask for a passphrase
if (walletModel->getEncryptionStatus() == WalletModel::Locked)
{
WalletModel::UnlockContext ctx(walletModel->requestUnlock(true));
if(!ctx.isValid())
{
//unlock was cancelled
walletModel->coinJoin()->resetCachedBlocks();
QMessageBox::warning(this, strCoinJoinName,
tr("Wallet is locked and user declined to unlock. Disabling %1.").arg(strCoinJoinName),
QMessageBox::Ok, QMessageBox::Ok);
LogPrint(BCLog::COINJOIN, "OverviewPage::toggleCoinJoin -- Wallet is locked and user declined to unlock. Disabling CoinJoin.\n");
return;
}
}
}
walletModel->coinJoin()->resetCachedBlocks();
if (walletModel->coinJoin()->isMixing()) {
ui->toggleCoinJoin->setText(tr("Start %1").arg(strCoinJoinName));
walletModel->coinJoin()->resetPool();
walletModel->coinJoin()->stopMixing();
} else {
ui->toggleCoinJoin->setText(tr("Stop %1").arg(strCoinJoinName));
walletModel->coinJoin()->startMixing();
}
}
void OverviewPage::SetupTransactionList(int nNumItems)
{
if (walletModel == nullptr || walletModel->getTransactionTableModel() == nullptr) {
return;
}
// Set up transaction list
if (filter == nullptr) {
filter.reset(new TransactionFilterProxy());
filter->setSourceModel(walletModel->getTransactionTableModel());
filter->setDynamicSortFilter(true);
filter->setSortRole(Qt::EditRole);
filter->setShowInactive(false);
filter->sort(TransactionTableModel::Date, Qt::DescendingOrder);
ui->listTransactions->setModel(filter.get());
}
if (filter->rowCount() == nNumItems) {
return;
}
filter->setLimit(nNumItems);
ui->listTransactions->setMinimumHeight(nNumItems * ITEM_HEIGHT);
}
void OverviewPage::DisableCoinJoinCompletely()
{
if (walletModel == nullptr) {
return;
}
ui->toggleCoinJoin->setText("(" + tr("Disabled") + ")");
ui->frameCoinJoin->setEnabled(false);
if (nWalletBackups <= 0) {
ui->labelCoinJoinEnabled->setText("<span style='" + GUIUtil::getThemedStyleQString(GUIUtil::ThemedStyle::TS_ERROR) + "'>(" + tr("Disabled") + ")</span>");
}
walletModel->coinJoin()->stopMixing();
}