forked from dashpay/dash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgovernancelist.cpp
More file actions
597 lines (506 loc) · 19.6 KB
/
governancelist.cpp
File metadata and controls
597 lines (506 loc) · 19.6 KB
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
// Copyright (c) 2021-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/forms/ui_governancelist.h>
#include <qt/governancelist.h>
#include <chainparams.h>
#include <chainparamsbase.h>
#include <evo/deterministicmns.h>
#include <governance/governance.h>
#include <governance/vote.h>
#include <interfaces/node.h>
#include <interfaces/wallet.h>
#include <key_io.h>
#include <qt/clientmodel.h>
#include <qt/guiutil.h>
#include <qt/optionsmodel.h>
#include <qt/walletmodel.h>
#include <script/standard.h>
#include <util/message.h>
#include <util/strencodings.h>
#include <wallet/wallet.h>
#include <univalue.h>
#include <QAbstractItemView>
#include <QDesktopServices>
#include <QMessageBox>
#include <QTableWidgetItem>
#include <QUrl>
#include <QtGui/QClipboard>
///
/// Proposal wrapper
///
Proposal::Proposal(ClientModel* _clientModel, const CGovernanceObject& _govObj, QObject* parent) :
QObject(parent),
clientModel(_clientModel),
govObj(_govObj)
{
UniValue prop_data;
if (prop_data.read(govObj.GetDataAsPlainString())) {
if (UniValue titleValue = prop_data.find_value("name"); titleValue.isStr()) {
m_title = QString::fromStdString(titleValue.get_str());
}
if (UniValue paymentStartValue = prop_data.find_value("start_epoch"); paymentStartValue.isNum()) {
m_startDate = QDateTime::fromSecsSinceEpoch(paymentStartValue.getInt<int64_t>());
}
if (UniValue paymentEndValue = prop_data.find_value("end_epoch"); paymentEndValue.isNum()) {
m_endDate = QDateTime::fromSecsSinceEpoch(paymentEndValue.getInt<int64_t>());
}
if (UniValue amountValue = prop_data.find_value("payment_amount"); amountValue.isNum()) {
m_paymentAmount = amountValue.get_real();
}
if (UniValue urlValue = prop_data.find_value("url"); urlValue.isStr()) {
m_url = QString::fromStdString(urlValue.get_str());
}
}
}
QString Proposal::title() const { return m_title; }
QString Proposal::hash() const { return QString::fromStdString(govObj.GetHash().ToString()); }
QDateTime Proposal::startDate() const { return m_startDate; }
QDateTime Proposal::endDate() const { return m_endDate; }
double Proposal::paymentAmount() const { return m_paymentAmount; }
QString Proposal::url() const { return m_url; }
bool Proposal::isActive() const
{
std::string strError;
return clientModel->node().gov().getObjLocalValidity(govObj, strError, false);
}
QString Proposal::votingStatus(const int nAbsVoteReq) const
{
// Voting status...
// TODO: determine if voting is in progress vs. funded or not funded for past proposals.
// see CSuperblock::GetNearestSuperblocksHeights(nBlockHeight, nLastSuperblock, nNextSuperblock);
const int absYesCount = clientModel->node().gov().getObjAbsYesCount(govObj, VOTE_SIGNAL_FUNDING);
QString qStatusString;
if (absYesCount >= nAbsVoteReq) {
// Could use govObj.IsSetCachedFunding here, but need nAbsVoteReq to display numbers anyway.
return tr("Passing +%1").arg(absYesCount - nAbsVoteReq);
} else {
return tr("Needs additional %1 votes").arg(nAbsVoteReq - absYesCount);
}
}
int Proposal::GetAbsoluteYesCount() const
{
return clientModel->node().gov().getObjAbsYesCount(govObj, VOTE_SIGNAL_FUNDING);
}
void Proposal::openUrl() const
{
QDesktopServices::openUrl(QUrl(m_url));
}
QString Proposal::toJson() const
{
const auto json = govObj.ToJson();
return QString::fromStdString(json.write(2));
}
///
/// Proposal Model
///
int ProposalModel::rowCount(const QModelIndex& index) const
{
return m_data.count();
}
int ProposalModel::columnCount(const QModelIndex& index) const
{
return Column::_COUNT;
}
QVariant ProposalModel::data(const QModelIndex& index, int role) const
{
if (role != Qt::DisplayRole && role != Qt::EditRole) return {};
const auto proposal = m_data[index.row()];
switch(role) {
case Qt::DisplayRole:
{
switch (index.column()) {
case Column::HASH:
return proposal->hash();
case Column::TITLE:
return proposal->title();
case Column::START_DATE:
return proposal->startDate().date();
case Column::END_DATE:
return proposal->endDate().date();
case Column::PAYMENT_AMOUNT: {
return BitcoinUnits::floorWithUnit(m_display_unit, proposal->paymentAmount() * COIN, false,
BitcoinUnits::SeparatorStyle::ALWAYS);
}
case Column::IS_ACTIVE:
return proposal->isActive() ? tr("Yes") : tr("No");
case Column::VOTING_STATUS:
return proposal->votingStatus(nAbsVoteReq);
default:
return {};
};
break;
}
case Qt::EditRole:
{
// Edit role is used for sorting, so return the raw values where possible
switch (index.column()) {
case Column::HASH:
return proposal->hash();
case Column::TITLE:
return proposal->title();
case Column::START_DATE:
return proposal->startDate();
case Column::END_DATE:
return proposal->endDate();
case Column::PAYMENT_AMOUNT:
return proposal->paymentAmount();
case Column::IS_ACTIVE:
return proposal->isActive();
case Column::VOTING_STATUS:
return proposal->GetAbsoluteYesCount();
default:
return {};
};
break;
}
};
return {};
}
QVariant ProposalModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation != Qt::Horizontal || role != Qt::DisplayRole) return {};
switch (section) {
case Column::HASH:
return tr("Hash");
case Column::TITLE:
return tr("Title");
case Column::START_DATE:
return tr("Start");
case Column::END_DATE:
return tr("End");
case Column::PAYMENT_AMOUNT:
return tr("Amount");
case Column::IS_ACTIVE:
return tr("Active");
case Column::VOTING_STATUS:
return tr("Status");
default:
return {};
}
}
int ProposalModel::columnWidth(int section)
{
switch (section) {
case Column::HASH:
return 80;
case Column::TITLE:
return 220;
case Column::START_DATE:
case Column::END_DATE:
case Column::PAYMENT_AMOUNT:
return 110;
case Column::IS_ACTIVE:
return 80;
case Column::VOTING_STATUS:
return 220;
default:
return 80;
}
}
void ProposalModel::append(const Proposal* proposal)
{
beginInsertRows({}, m_data.count(), m_data.count());
m_data.append(proposal);
endInsertRows();
}
void ProposalModel::remove(int row)
{
beginRemoveRows({}, row, row);
delete m_data.at(row);
m_data.removeAt(row);
endRemoveRows();
}
void ProposalModel::reconcile(Span<const Proposal*> proposals)
{
// Vector of m_data.count() false values. Going through new proposals,
// set keep_index true for each old proposal found in the new proposals.
// After going through new proposals, remove any existing proposals that
// weren't found (and are still false).
std::vector<bool> keep_index(m_data.count(), false);
for (const auto proposal : proposals) {
bool found = false;
for (int i = 0; i < m_data.count(); ++i) {
if (m_data.at(i)->hash() == proposal->hash()) {
found = true;
keep_index.at(i) = true;
if (m_data.at(i)->GetAbsoluteYesCount() != proposal->GetAbsoluteYesCount()) {
// replace proposal to update vote count
delete m_data.at(i);
m_data.replace(i, proposal);
Q_EMIT dataChanged(createIndex(i, Column::VOTING_STATUS), createIndex(i, Column::VOTING_STATUS));
} else {
// no changes
delete proposal;
}
break;
}
}
if (!found) {
append(proposal);
}
}
for (unsigned int i = keep_index.size(); i > 0; --i) {
if (!keep_index.at(i - 1)) {
remove(i - 1);
}
}
}
void ProposalModel::setVotingParams(int newAbsVoteReq)
{
if (this->nAbsVoteReq != newAbsVoteReq) {
this->nAbsVoteReq = newAbsVoteReq;
// Changing either of the voting params may change the voting status
// column. Emit signal to force recalculation.
Q_EMIT dataChanged(createIndex(0, Column::VOTING_STATUS), createIndex(rowCount(), Column::VOTING_STATUS));
}
}
const Proposal* ProposalModel::getProposalAt(const QModelIndex& index) const
{
return m_data[index.row()];
}
void ProposalModel::setDisplayUnit(BitcoinUnit display_unit) { this->m_display_unit = display_unit; }
//
// Governance Tab main widget.
//
GovernanceList::GovernanceList(QWidget* parent) :
QWidget(parent),
ui(std::make_unique<Ui::GovernanceList>()),
proposalModel(new ProposalModel(this)),
proposalModelProxy(new QSortFilterProxyModel(this)),
proposalContextMenu(new QMenu(this)),
timer(new QTimer(this))
{
ui->setupUi(this);
GUIUtil::setFont({ui->label_count_2, ui->countLabel, ui->label_mn_count, ui->mnCountLabel},
GUIUtil::FontWeight::Bold, 14);
GUIUtil::setFont({ui->label_filter_2}, GUIUtil::FontWeight::Normal, 15);
proposalModelProxy->setSourceModel(proposalModel);
ui->govTableView->setModel(proposalModelProxy);
ui->govTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->govTableView->horizontalHeader()->setStretchLastSection(true);
ui->govTableView->verticalHeader()->setVisible(false);
for (int i = 0; i < proposalModel->columnCount(); ++i) {
ui->govTableView->setColumnWidth(i, proposalModel->columnWidth(i));
}
// Set up sorting.
proposalModelProxy->setSortRole(Qt::EditRole);
ui->govTableView->setSortingEnabled(true);
ui->govTableView->sortByColumn(ProposalModel::Column::START_DATE, Qt::DescendingOrder);
// Set up filtering.
proposalModelProxy->setFilterKeyColumn(ProposalModel::Column::TITLE); // filter by title column...
connect(ui->filterLineEdit, &QLineEdit::textChanged, proposalModelProxy, &QSortFilterProxyModel::setFilterFixedString);
// Changes to number of rows should update proposal count display.
connect(proposalModelProxy, &QSortFilterProxyModel::rowsInserted, this, &GovernanceList::updateProposalCount);
connect(proposalModelProxy, &QSortFilterProxyModel::rowsRemoved, this, &GovernanceList::updateProposalCount);
connect(proposalModelProxy, &QSortFilterProxyModel::layoutChanged, this, &GovernanceList::updateProposalCount);
// Enable CustomContextMenu on the table to make the view emit customContextMenuRequested signal.
ui->govTableView->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->govTableView, &QTableView::customContextMenuRequested, this, &GovernanceList::showProposalContextMenu);
connect(ui->govTableView, &QTableView::doubleClicked, this, &GovernanceList::showAdditionalInfo);
connect(timer, &QTimer::timeout, this, &GovernanceList::updateProposalList);
// Initialize masternode count to 0
ui->mnCountLabel->setText("0");
GUIUtil::updateFonts();
}
GovernanceList::~GovernanceList() = default;
void GovernanceList::setClientModel(ClientModel* model)
{
this->clientModel = model;
updateProposalList();
if (model != nullptr) {
connect(model->getOptionsModel(), &OptionsModel::displayUnitChanged, this, &GovernanceList::updateDisplayUnit);
// Update voting capability if we now have both client and wallet models
if (walletModel) {
updateVotingCapability();
// Update voting capability when masternode list changes
connect(clientModel, &ClientModel::masternodeListChanged, this, &GovernanceList::updateVotingCapability);
}
}
}
void GovernanceList::setWalletModel(WalletModel* model)
{
this->walletModel = model;
if (model && clientModel) {
updateVotingCapability();
}
}
void GovernanceList::updateDisplayUnit()
{
if (this->clientModel) {
proposalModel->setDisplayUnit(this->clientModel->getOptionsModel()->getDisplayUnit());
ui->govTableView->update();
}
}
void GovernanceList::updateProposalList()
{
if (this->clientModel) {
// A proposal is considered passing if (YES votes - NO votes) >= (Total Weight of Masternodes / 10),
// count total valid (ENABLED) masternodes to determine passing threshold.
// Need to query number of masternodes here with access to clientModel.
const int nWeightedMnCount = clientModel->getMasternodeList().first.GetValidWeightedMNsCount();
const int nAbsVoteReq = std::max(Params().GetConsensus().nGovernanceMinQuorum, nWeightedMnCount / 10);
proposalModel->setVotingParams(nAbsVoteReq);
std::vector<CGovernanceObject> govObjList;
clientModel->getAllGovernanceObjects(govObjList);
std::vector<const Proposal*> newProposals;
for (const auto& govObj : govObjList) {
if (govObj.GetObjectType() != GovernanceObject::PROPOSAL) {
continue; // Skip triggers.
}
newProposals.emplace_back(new Proposal(this->clientModel, govObj, proposalModel));
}
proposalModel->reconcile(newProposals);
}
// Schedule next update.
timer->start(GOVERNANCELIST_UPDATE_SECONDS * 1000);
}
void GovernanceList::updateProposalCount() const
{
ui->countLabel->setText(QString::number(proposalModelProxy->rowCount()));
}
void GovernanceList::showProposalContextMenu(const QPoint& pos)
{
const auto index = ui->govTableView->indexAt(pos);
if (!index.isValid()) {
return;
}
const auto proposal = proposalModel->getProposalAt(proposalModelProxy->mapToSource(index));
if (proposal == nullptr) {
return;
}
// right click menu with option to open proposal url
QString proposal_url = proposal->url();
proposal_url.replace(QChar('&'), QString("&&"));
proposalContextMenu->clear();
proposalContextMenu->addAction(proposal_url, proposal, &Proposal::openUrl);
// Add voting options if wallet is available and has voting capability
if (walletModel && canVote()) {
proposalContextMenu->addSeparator();
proposalContextMenu->addAction(tr("Vote Yes"), this, &GovernanceList::voteYes);
proposalContextMenu->addAction(tr("Vote No"), this, &GovernanceList::voteNo);
proposalContextMenu->addAction(tr("Vote Abstain"), this, &GovernanceList::voteAbstain);
}
proposalContextMenu->exec(QCursor::pos());
}
void GovernanceList::showAdditionalInfo(const QModelIndex& index)
{
if (!index.isValid()) {
return;
}
const auto proposal = proposalModel->getProposalAt(proposalModelProxy->mapToSource(index));
if (proposal == nullptr) {
return;
}
const auto windowTitle = tr("Proposal Info: %1").arg(proposal->title());
const auto json = proposal->toJson();
QMessageBox::information(this, windowTitle, json);
}
void GovernanceList::updateVotingCapability()
{
if (!walletModel || !clientModel) return;
votableMasternodes.clear();
auto [mnList, pindex] = clientModel->getMasternodeList();
if (!pindex) return;
mnList.ForEachMN(true, [&](const auto& dmn) {
// Check if wallet owns the voting key using the same logic as RPC
const CScript script = GetScriptForDestination(PKHash(dmn.pdmnState->keyIDVoting));
if (walletModel->wallet().isSpendable(script)) {
votableMasternodes[dmn.proTxHash] = dmn.pdmnState->keyIDVoting;
}
});
// Update masternode count display
updateMasternodeCount();
}
void GovernanceList::updateMasternodeCount() const
{
if (ui && ui->mnCountLabel) {
ui->mnCountLabel->setText(QString::number(votableMasternodes.size()));
}
}
void GovernanceList::voteYes() { voteForProposal(VOTE_OUTCOME_YES); }
void GovernanceList::voteNo() { voteForProposal(VOTE_OUTCOME_NO); }
void GovernanceList::voteAbstain() { voteForProposal(VOTE_OUTCOME_ABSTAIN); }
void GovernanceList::voteForProposal(vote_outcome_enum_t outcome)
{
if (!walletModel) {
QMessageBox::warning(this, tr("Voting Failed"), tr("No wallet available."));
return;
}
if (votableMasternodes.empty()) {
QMessageBox::warning(this, tr("Voting Failed"), tr("No masternode voting keys found in wallet."));
return;
}
// Get the selected proposal
const auto selection = ui->govTableView->selectionModel()->selectedRows();
if (selection.isEmpty()) {
QMessageBox::warning(this, tr("Voting Failed"), tr("Please select a proposal to vote on."));
return;
}
const auto index = selection.first();
const auto proposal = proposalModel->getProposalAt(proposalModelProxy->mapToSource(index));
if (proposal == nullptr) return;
const uint256 proposalHash(uint256S(proposal->hash().toStdString()));
// Request unlock if needed and keep context alive for the voting operation
WalletModel::UnlockContext ctx(walletModel->requestUnlock());
if (!ctx.isValid()) {
// Unlock cancelled or failed
QMessageBox::warning(this, tr("Voting Failed"), tr("Unable to unlock wallet."));
return;
}
int nSuccessful = 0;
int nFailed = 0;
QStringList failedMessages;
// Get masternode list once before the loop
auto [mnList, pindex] = clientModel->getMasternodeList();
if (!pindex) {
QMessageBox::warning(this, tr("Voting Failed"), tr("Unable to get masternode list. Please try again later."));
return;
}
// Vote with each masternode
for (const auto& [proTxHash, votingKeyID] : votableMasternodes) {
// Find the masternode
auto dmn = mnList.GetValidMN(proTxHash);
if (!dmn) {
nFailed++;
failedMessages.append(tr("Masternode %1 not found").arg(QString::fromStdString(proTxHash.ToString())));
continue;
}
// Create vote
CGovernanceVote vote(dmn->collateralOutpoint, proposalHash, VOTE_SIGNAL_FUNDING, outcome);
// Sign vote using CWallet member function
if (!walletModel->wallet().wallet()->SignGovernanceVote(votingKeyID, vote)) {
nFailed++;
failedMessages.append(
tr("Failed to sign vote for masternode %1").arg(QString::fromStdString(proTxHash.ToString())));
continue;
}
// Submit vote
std::string strError;
if (clientModel->node().gov().processVoteAndRelay(vote, strError)) {
nSuccessful++;
} else {
nFailed++;
failedMessages.append(
tr("Masternode %1: %2").arg(QString::fromStdString(proTxHash.ToString()), QString::fromStdString(strError)));
}
}
// Show results
QString message;
if (nSuccessful > 0 && nFailed == 0) {
message = tr("Voted successfully %1 time(s).").arg(nSuccessful);
} else if (nSuccessful > 0 && nFailed > 0) {
message = tr("Voted successfully %1 time(s) and failed %2 time(s).").arg(nSuccessful).arg(nFailed);
if (!failedMessages.isEmpty()) {
message += tr("\n\nFailed votes:\n%1").arg(failedMessages.join("\n"));
}
} else {
message = tr("Failed to vote %1 time(s).").arg(nFailed);
if (!failedMessages.isEmpty()) {
message += tr("\n\nErrors:\n%1").arg(failedMessages.join("\n"));
}
}
QMessageBox::information(this, tr("Voting Results"), message);
// Update proposal list to show new vote counts
updateProposalList();
}