forked from PIVX-Project/PIVX
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbudgetmanager.cpp
1666 lines (1441 loc) · 64.8 KB
/
budgetmanager.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
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2022 The PIVX Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "budget/budgetmanager.h"
#include "consensus/validation.h"
#include "evo/deterministicmns.h"
#include "masternodeman.h"
#include "netmessagemaker.h"
#include "tiertwo/tiertwo_sync_state.h"
#include "tiertwo/netfulfilledman.h"
#include "util/validation.h"
#include "validation.h" // GetTransaction, cs_main
#ifdef ENABLE_WALLET
#include "wallet/wallet.h" // future: use interface instead.
#endif
#define BUDGET_ORPHAN_VOTES_CLEANUP_SECONDS (60 * 60) // One hour.
// Request type used in the net requests manager to block peers asking budget sync too often
static const std::string BUDGET_SYNC_REQUEST_RECV = "budget-sync-recv";
CBudgetManager g_budgetman;
// Used to check both proposals and finalized-budgets collateral txes
bool CheckCollateral(const uint256& nTxCollateralHash, const uint256& nExpectedHash, std::string& strError, int64_t& nTime, int nCurrentHeight, bool fBudgetFinalization);
void CBudgetManager::ReloadMapSeen()
{
const auto reloadSeenMap = [](auto& mutex1, auto& mutex2, const auto& mapBudgets, auto& mapSeen, auto& mapOrphans) {
LOCK2(mutex1, mutex2);
mapSeen.clear();
mapOrphans.clear();
for (const auto& b : mapBudgets) {
for (const auto& it : b.second.mapVotes) {
const auto& vote = it.second;
if (vote.IsValid()) {
mapSeen.emplace(vote.GetHash(), vote);
}
}
}
};
reloadSeenMap(cs_proposals, cs_votes, mapProposals, mapSeenProposalVotes, mapOrphanProposalVotes);
reloadSeenMap(cs_budgets, cs_finalizedvotes, mapFinalizedBudgets, mapSeenFinalizedBudgetVotes, mapOrphanFinalizedBudgetVotes);
}
void CBudgetManager::CheckOrphanVotes()
{
{
LOCK2(cs_proposals, cs_votes);
for (auto itOrphanVotes = mapOrphanProposalVotes.begin(); itOrphanVotes != mapOrphanProposalVotes.end();) {
auto itProposal = mapProposals.find(itOrphanVotes->first);
if (itProposal != mapProposals.end()) {
// Proposal found.
CBudgetProposal* bp = &(itProposal->second);
// Try to add orphan votes
for (const CBudgetVote& vote : itOrphanVotes->second.first) {
std::string strError;
if (!bp->AddOrUpdateVote(vote, strError)) {
LogPrint(BCLog::MNBUDGET, "Unable to add orphan vote for proposal: %s\n", strError);
}
}
// Remove entry from the map
itOrphanVotes = mapOrphanProposalVotes.erase(itOrphanVotes);
} else {
++itOrphanVotes;
}
}
}
{
LOCK2(cs_budgets, cs_finalizedvotes);
for (auto itOrphanVotes = mapOrphanFinalizedBudgetVotes.begin(); itOrphanVotes != mapOrphanFinalizedBudgetVotes.end();) {
auto itFinalBudget = mapFinalizedBudgets.find(itOrphanVotes->first);
if (itFinalBudget != mapFinalizedBudgets.end()) {
// Finalized budget found.
CFinalizedBudget* fb = &(itFinalBudget->second);
// Try to add orphan votes
for (const CFinalizedBudgetVote& vote : itOrphanVotes->second.first) {
std::string strError;
if (!fb->AddOrUpdateVote(vote, strError)) {
LogPrint(BCLog::MNBUDGET, "Unable to add orphan vote for final budget: %s\n", strError);
}
}
// Remove entry from the map
itOrphanVotes = mapOrphanFinalizedBudgetVotes.erase(itOrphanVotes);
} else {
++itOrphanVotes;
}
}
}
LogPrint(BCLog::MNBUDGET,"%s: Done\n", __func__);
}
uint256 CBudgetManager::SubmitFinalBudget()
{
static int nSubmittedHeight = 0; // height at which final budget was submitted last time
int nCurrentHeight = GetBestHeight();
const int nBlocksPerCycle = Params().GetConsensus().nBudgetCycleBlocks;
int nBlockStart = nCurrentHeight - nCurrentHeight % nBlocksPerCycle + nBlocksPerCycle;
if (nSubmittedHeight >= nBlockStart){
LogPrint(BCLog::MNBUDGET,"%s: nSubmittedHeight(=%ld) < nBlockStart(=%ld) condition not fulfilled.\n",
__func__, nSubmittedHeight, nBlockStart);
return UINT256_ZERO;
}
// Submit final budget during the last 2 days (2880 blocks) before payment for Mainnet, about 9 minutes (9 blocks) for Testnet
int finalizationWindow = ((nBlocksPerCycle / 30) * 2);
if (Params().IsTestnet()) {
// NOTE: 9 blocks for testnet is way to short to have any masternode submit an automatic vote on the finalized(!) budget,
// because those votes are only submitted/relayed once every 56 blocks in CFinalizedBudget::AutoCheck()
finalizationWindow = 64; // 56 + 4 finalization confirmations + 4 minutes buffer for propagation
}
int nFinalizationStart = nBlockStart - finalizationWindow;
int nOffsetToStart = nFinalizationStart - nCurrentHeight;
if (nBlockStart - nCurrentHeight > finalizationWindow) {
LogPrint(BCLog::MNBUDGET,"%s: Too early for finalization. Current block is %ld, next Superblock is %ld.\n", __func__, nCurrentHeight, nBlockStart);
LogPrint(BCLog::MNBUDGET,"%s: First possible block for finalization: %ld. Last possible block for finalization: %ld. "
"You have to wait for %ld block(s) until Budget finalization will be possible\n", __func__, nFinalizationStart, nBlockStart, nOffsetToStart);
return UINT256_ZERO;
}
std::vector<CBudgetProposal> vBudgetProposals = GetBudget();
std::string strBudgetName = "main";
std::vector<CTxBudgetPayment> vecTxBudgetPayments;
for (const auto& p : vBudgetProposals) {
CTxBudgetPayment txBudgetPayment;
txBudgetPayment.nProposalHash = p.GetHash();
txBudgetPayment.payee = p.GetPayee();
txBudgetPayment.nAmount = p.GetAllotted();
vecTxBudgetPayments.push_back(txBudgetPayment);
}
if (vecTxBudgetPayments.size() < 1) {
LogPrint(BCLog::MNBUDGET,"%s: Found No Proposals For Period\n", __func__);
return UINT256_ZERO;
}
CFinalizedBudget tempBudget(strBudgetName, nBlockStart, vecTxBudgetPayments, UINT256_ZERO);
const uint256& budgetHash = tempBudget.GetHash();
if (HaveFinalizedBudget(budgetHash)) {
LogPrint(BCLog::MNBUDGET,"%s: Budget already exists - %s\n", __func__, budgetHash.ToString());
nSubmittedHeight = nCurrentHeight;
return UINT256_ZERO;
}
// See if collateral tx exists
if (!mapUnconfirmedFeeTx.count(budgetHash)) {
// create the collateral tx, send it to the network and return
CTransactionRef wtx;
// Get our change address
if (vpwallets.empty() || !vpwallets[0]) {
LogPrint(BCLog::MNBUDGET,"%s: Wallet not found\n", __func__);
return UINT256_ZERO;
}
CReserveKey keyChange(vpwallets[0]);
if (!vpwallets[0]->CreateBudgetFeeTX(wtx, budgetHash, keyChange, BUDGET_FEE_TX)) {
LogPrint(BCLog::MNBUDGET,"%s: Can't make collateral transaction\n", __func__);
return UINT256_ZERO;
}
// Send the tx to the network
const CWallet::CommitResult& res = vpwallets[0]->CommitTransaction(wtx, keyChange, g_connman.get());
if (res.status == CWallet::CommitStatus::OK) {
const uint256& collateraltxid = wtx->GetHash();
mapUnconfirmedFeeTx.emplace(budgetHash, collateraltxid);
LogPrint(BCLog::MNBUDGET,"%s: Collateral sent. txid: %s\n", __func__, collateraltxid.ToString());
return budgetHash;
}
return UINT256_ZERO;
}
// Collateral tx already exists, see if it's mature enough.
CFinalizedBudget fb(strBudgetName, nBlockStart, vecTxBudgetPayments, mapUnconfirmedFeeTx.at(budgetHash));
if (!AddFinalizedBudget(fb)) {
return UINT256_ZERO;
}
fb.Relay();
nSubmittedHeight = nCurrentHeight;
LogPrint(BCLog::MNBUDGET,"%s: Done! %s\n", __func__, budgetHash.ToString());
return budgetHash;
}
void CBudgetManager::SetBudgetProposalsStr(CFinalizedBudget& finalizedBudget) const
{
const std::vector<uint256>& vHashes = finalizedBudget.GetProposalsHashes();
std::string strProposals = "";
{
LOCK(cs_proposals);
for (const uint256& hash: vHashes) {
const std::string token = (mapProposals.count(hash) ? mapProposals.at(hash).GetName() : hash.ToString());
strProposals += (strProposals == "" ? "" : ", ") + token;
}
}
finalizedBudget.SetProposalsStr(strProposals);
}
std::string CBudgetManager::GetFinalizedBudgetStatus(const uint256& nHash) const
{
CFinalizedBudget fb;
if (!GetFinalizedBudget(nHash, fb))
return strprintf("ERROR: cannot find finalized budget %s\n", nHash.ToString());
std::string retBadHashes = "";
std::string retBadPayeeOrAmount = "";
int nBlockStart = fb.GetBlockStart();
int nBlockEnd = fb.GetBlockEnd();
for (int nBlockHeight = nBlockStart; nBlockHeight <= nBlockEnd; nBlockHeight++) {
CTxBudgetPayment budgetPayment;
if (!fb.GetBudgetPaymentByBlock(nBlockHeight, budgetPayment)) {
LogPrint(BCLog::MNBUDGET,"%s: Couldn't find budget payment for block %lld\n", __func__, nBlockHeight);
continue;
}
CBudgetProposal bp;
if (!GetProposal(budgetPayment.nProposalHash, bp)) {
retBadHashes += (retBadHashes == "" ? "" : ", ") + budgetPayment.nProposalHash.ToString();
continue;
}
if (bp.GetPayee() != budgetPayment.payee || bp.GetAmount() != budgetPayment.nAmount) {
retBadPayeeOrAmount += (retBadPayeeOrAmount == "" ? "" : ", ") + budgetPayment.nProposalHash.ToString();
}
}
if (retBadHashes == "" && retBadPayeeOrAmount == "") return "OK";
if (retBadHashes != "") retBadHashes = "Unknown proposal(s) hash! Check this proposal(s) before voting: " + retBadHashes;
if (retBadPayeeOrAmount != "") retBadPayeeOrAmount = "Budget payee/nAmount doesn't match our proposal(s)! "+ retBadPayeeOrAmount;
return retBadHashes + " -- " + retBadPayeeOrAmount;
}
bool CBudgetManager::AddFinalizedBudget(CFinalizedBudget& finalizedBudget, CNode* pfrom)
{
AssertLockNotHeld(cs_budgets); // need to lock cs_main here (CheckCollateral)
const uint256& nHash = finalizedBudget.GetHash();
if (WITH_LOCK(cs_budgets, return mapFinalizedBudgets.count(nHash))) {
LogPrint(BCLog::MNBUDGET,"%s: finalized budget %s already added\n", __func__, nHash.ToString());
return false;
}
if (!finalizedBudget.IsWellFormed(GetTotalBudget(finalizedBudget.GetBlockStart()))) {
LogPrint(BCLog::MNBUDGET,"%s: invalid finalized budget: %s %s\n", __func__, nHash.ToString(), finalizedBudget.IsInvalidLogStr());
return false;
}
std::string strError;
int nCurrentHeight = GetBestHeight();
const uint256& feeTxId = finalizedBudget.GetFeeTXHash();
if (!CheckCollateral(feeTxId, nHash, strError, finalizedBudget.nTime, nCurrentHeight, true)) {
LogPrint(BCLog::MNBUDGET,"%s: invalid finalized budget (%s) collateral id=%s - %s\n",
__func__, nHash.ToString(), feeTxId.ToString(), strError);
finalizedBudget.SetStrInvalid(strError);
return false;
}
// update expiration
if (!finalizedBudget.UpdateValid(nCurrentHeight)) {
LogPrint(BCLog::MNBUDGET,"%s: invalid finalized budget: %s %s\n", __func__, nHash.ToString(), finalizedBudget.IsInvalidLogStr());
return false;
}
// Compare budget payments with existent proposals, don't care on the order, just verify proposals existence.
std::vector<CBudgetProposal> vBudget = GetBudget();
std::map<uint256, CBudgetProposal> mapWinningProposals;
for (const CBudgetProposal& p: vBudget) { mapWinningProposals.emplace(p.GetHash(), p); }
if (!finalizedBudget.CheckProposals(mapWinningProposals)) {
finalizedBudget.SetStrInvalid("Invalid proposals");
LogPrint(BCLog::MNBUDGET,"%s: Budget finalization does not match with winning proposals\n", __func__);
// just for now (until v6), request proposals and budget sync in case we are missing them
if (pfrom) {
CNetMsgMaker maker(pfrom->GetSendVersion());
// First, request single proposals that we don't have.
for (const auto& propId : finalizedBudget.GetProposalsHashes()) {
if (!g_budgetman.HaveProposal(propId)) {
g_connman->PushMessage(pfrom, maker.Make(NetMsgType::BUDGETVOTESYNC, propId));
}
}
// Second a full budget sync for missing votes and the budget finalization that we are rejecting here.
// Note: this will not make any effect on peers with version <= 70923 as they, invalidly, are blocking
// follow-up budget sync request for the entire node life cycle.
uint256 n;
g_connman->PushMessage(pfrom, maker.Make(NetMsgType::BUDGETVOTESYNC, n));
}
return false;
}
// Add budget finalization.
SetBudgetProposalsStr(finalizedBudget);
ForceAddFinalizedBudget(nHash, feeTxId, finalizedBudget);
LogPrint(BCLog::MNBUDGET,"%s: finalized budget %s [%s (%s)] added\n",
__func__, nHash.ToString(), finalizedBudget.GetName(), finalizedBudget.GetProposalsStr());
return true;
}
void CBudgetManager::ForceAddFinalizedBudget(const uint256& nHash, const uint256& feeTxId, const CFinalizedBudget& finalizedBudget)
{
LOCK(cs_budgets);
mapFinalizedBudgets.emplace(nHash, finalizedBudget);
// Add to feeTx index
mapFeeTxToBudget.emplace(feeTxId, nHash);
// Remove the budget from the unconfirmed map, if it was there
if (mapUnconfirmedFeeTx.count(nHash))
mapUnconfirmedFeeTx.erase(nHash);
}
bool CBudgetManager::AddProposal(CBudgetProposal& budgetProposal)
{
AssertLockNotHeld(cs_proposals); // need to lock cs_main here (CheckCollateral)
const uint256& nHash = budgetProposal.GetHash();
if (WITH_LOCK(cs_proposals, return mapProposals.count(nHash))) {
LogPrint(BCLog::MNBUDGET,"%s: proposal %s already added\n", __func__, nHash.ToString());
return false;
}
if (!budgetProposal.IsWellFormed(GetTotalBudget(budgetProposal.GetBlockStart()))) {
LogPrint(BCLog::MNBUDGET,"%s: Invalid budget proposal %s %s\n", __func__, nHash.ToString(), budgetProposal.IsInvalidLogStr());
return false;
}
std::string strError;
int nCurrentHeight = GetBestHeight();
const uint256& feeTxId = budgetProposal.GetFeeTXHash();
if (!CheckCollateral(feeTxId, nHash, strError, budgetProposal.nTime, nCurrentHeight, false)) {
LogPrint(BCLog::MNBUDGET,"%s: invalid budget proposal (%s) collateral id=%s - %s\n",
__func__, nHash.ToString(), feeTxId.ToString(), strError);
budgetProposal.SetStrInvalid(strError);
return false;
}
// update expiration / heavily-downvoted
int mnCount = mnodeman.CountEnabled();
if (!budgetProposal.UpdateValid(nCurrentHeight, mnCount)) {
LogPrint(BCLog::MNBUDGET,"%s: Invalid budget proposal %s %s\n", __func__, nHash.ToString(), budgetProposal.IsInvalidLogStr());
return false;
}
{
LOCK(cs_proposals);
mapProposals.emplace(nHash, budgetProposal);
// Add to feeTx index
mapFeeTxToProposal.emplace(feeTxId, nHash);
}
LogPrint(BCLog::MNBUDGET,"%s: budget proposal %s [%s] added\n", __func__, nHash.ToString(), budgetProposal.GetName());
return true;
}
void CBudgetManager::CheckAndRemove()
{
int nCurrentHeight = GetBestHeight();
std::map<uint256, CFinalizedBudget> tmpMapFinalizedBudgets;
std::map<uint256, CBudgetProposal> tmpMapProposals;
// Get MN count, used for the heavily down-voted check
int mnCount = mnodeman.CountEnabled();
// Check Proposals first
{
LOCK(cs_proposals);
LogPrint(BCLog::MNBUDGET, "%s: mapProposals cleanup - size before: %d\n", __func__, mapProposals.size());
for (auto& it: mapProposals) {
CBudgetProposal* pbudgetProposal = &(it.second);
if (!pbudgetProposal->UpdateValid(nCurrentHeight, mnCount)) {
LogPrint(BCLog::MNBUDGET,"%s: Invalid budget proposal %s %s\n", __func__, (it.first).ToString(), pbudgetProposal->IsInvalidLogStr());
mapFeeTxToProposal.erase(pbudgetProposal->GetFeeTXHash());
} else {
LogPrint(BCLog::MNBUDGET,"%s: Found valid budget proposal: %s %s\n", __func__,
pbudgetProposal->GetName(), pbudgetProposal->GetFeeTXHash().ToString());
tmpMapProposals.emplace(pbudgetProposal->GetHash(), *pbudgetProposal);
}
}
// Remove invalid entries by overwriting complete map
mapProposals.swap(tmpMapProposals);
LogPrint(BCLog::MNBUDGET, "%s: mapProposals cleanup - size after: %d\n", __func__, mapProposals.size());
}
// Then check finalized budgets
{
LOCK(cs_budgets);
LogPrint(BCLog::MNBUDGET, "%s: mapFinalizedBudgets cleanup - size before: %d\n", __func__, mapFinalizedBudgets.size());
for (auto& it: mapFinalizedBudgets) {
CFinalizedBudget* pfinalizedBudget = &(it.second);
if (!pfinalizedBudget->UpdateValid(nCurrentHeight)) {
LogPrint(BCLog::MNBUDGET,"%s: Invalid finalized budget %s %s\n", __func__, (it.first).ToString(), pfinalizedBudget->IsInvalidLogStr());
mapFeeTxToBudget.erase(pfinalizedBudget->GetFeeTXHash());
} else {
LogPrint(BCLog::MNBUDGET,"%s: Found valid finalized budget: %s %s\n", __func__,
pfinalizedBudget->GetName(), pfinalizedBudget->GetFeeTXHash().ToString());
tmpMapFinalizedBudgets.emplace(pfinalizedBudget->GetHash(), *pfinalizedBudget);
}
}
// Remove invalid entries by overwriting complete map
mapFinalizedBudgets = tmpMapFinalizedBudgets;
LogPrint(BCLog::MNBUDGET, "%s: mapFinalizedBudgets cleanup - size after: %d\n", __func__, mapFinalizedBudgets.size());
}
// Masternodes vote on valid ones
VoteOnFinalizedBudgets();
}
void CBudgetManager::RemoveByFeeTxId(const uint256& feeTxId)
{
{
LOCK(cs_proposals);
// Is this collateral related to a proposal?
const auto& it = mapFeeTxToProposal.find(feeTxId);
if (it != mapFeeTxToProposal.end()) {
// Remove proposal
CBudgetProposal* p = FindProposal(it->second);
if (p) {
LogPrintf("%s: Removing proposal %s (collateral disconnected, id=%s)\n", __func__, p->GetName(), feeTxId.ToString());
{
// Erase seen/orhpan votes
LOCK(cs_votes);
for (const auto& vote: p->GetVotes()) {
const uint256& hash{vote.second.GetHash()};
mapSeenProposalVotes.erase(hash);
mapOrphanProposalVotes.erase(hash);
}
}
// Erase proposal object
mapProposals.erase(it->second);
}
// Remove from collateral index
mapFeeTxToProposal.erase(it);
return;
}
}
{
LOCK(cs_budgets);
// Is this collateral related to a finalized budget?
const auto& it = mapFeeTxToBudget.find(feeTxId);
if (it != mapFeeTxToBudget.end()) {
// Remove finalized budget
CFinalizedBudget* b = FindFinalizedBudget(it->second);
if (b) {
LogPrintf("%s: Removing finalized budget %s (collateral disconnected, id=%s)\n", __func__, b->GetName(), feeTxId.ToString());
{
// Erase seen/orhpan votes
LOCK(cs_finalizedvotes);
for (const uint256& hash: b->GetVotesHashes()) {
mapSeenFinalizedBudgetVotes.erase(hash);
mapOrphanFinalizedBudgetVotes.erase(hash);
}
}
// Erase finalized budget object
mapFinalizedBudgets.erase(it->second);
}
// Remove from collateral index
mapFeeTxToBudget.erase(it);
}
}
}
CBudgetManager::HighestFinBudget CBudgetManager::GetBudgetWithHighestVoteCount(int chainHeight) const
{
LOCK(cs_budgets);
int highestVoteCount = 0;
const CFinalizedBudget* pHighestBudget = nullptr;
for (const auto& it: mapFinalizedBudgets) {
const CFinalizedBudget* pfinalizedBudget = &(it.second);
int voteCount = pfinalizedBudget->GetVoteCount();
if (voteCount > highestVoteCount &&
chainHeight >= pfinalizedBudget->GetBlockStart() &&
chainHeight <= pfinalizedBudget->GetBlockEnd()) {
pHighestBudget = pfinalizedBudget;
highestVoteCount = voteCount;
}
}
return {pHighestBudget, highestVoteCount};
}
int CBudgetManager::GetHighestVoteCount(int chainHeight) const
{
const auto& highestBudFin = GetBudgetWithHighestVoteCount(chainHeight);
return (highestBudFin.m_budget_fin ? highestBudFin.m_vote_count : -1);
}
bool CBudgetManager::GetPayeeAndAmount(int chainHeight, CScript& payeeRet, CAmount& nAmountRet) const
{
int nCountThreshold;
if (!IsBudgetPaymentBlock(chainHeight, nCountThreshold))
return false;
const auto& highestBudFin = GetBudgetWithHighestVoteCount(chainHeight);
const CFinalizedBudget* pfb = highestBudFin.m_budget_fin;
return pfb && pfb->GetPayeeAndAmount(chainHeight, payeeRet, nAmountRet) && highestBudFin.m_vote_count > nCountThreshold;
}
bool CBudgetManager::GetExpectedPayeeAmount(int chainHeight, CAmount& nAmountRet) const
{
CScript payeeRet;
return GetPayeeAndAmount(chainHeight, payeeRet, nAmountRet);
}
bool CBudgetManager::FillBlockPayee(CMutableTransaction& txCoinbase, CMutableTransaction& txCoinstake, const int nHeight, bool fProofOfStake) const
{
if (nHeight <= 0) return false;
CScript payee;
CAmount nAmount = 0;
if (!GetPayeeAndAmount(nHeight, payee, nAmount))
return false;
CAmount blockValue = GetBlockValue(nHeight);
// Starting from PIVX v6.0 masternode and budgets are paid in the coinbase tx of PoS blocks
const bool fPayCoinstake = fProofOfStake &&
!Params().GetConsensus().NetworkUpgradeActive(nHeight, Consensus::UPGRADE_V6_0);
if (fProofOfStake) {
if (fPayCoinstake) {
unsigned int i = txCoinstake.vout.size();
txCoinstake.vout.resize(i + 1);
txCoinstake.vout[i].scriptPubKey = payee;
txCoinstake.vout[i].nValue = nAmount;
} else {
txCoinbase.vout.resize(1);
txCoinbase.vout[0].scriptPubKey = payee;
txCoinbase.vout[0].nValue = nAmount;
}
} else {
//miners get the full amount on these blocks
txCoinbase.vout[0].nValue = blockValue;
txCoinbase.vout.resize(2);
//these are super blocks, so their value can be much larger than normal
txCoinbase.vout[1].scriptPubKey = payee;
txCoinbase.vout[1].nValue = nAmount;
}
CTxDestination address;
ExtractDestination(payee, address);
LogPrint(BCLog::MNBUDGET,"%s: Budget payment to %s for %lld\n", __func__, EncodeDestination(address), nAmount);
return true;
}
void CBudgetManager::VoteOnFinalizedBudgets()
{
// function called only from initialized masternodes
if (!fMasterNode) {
LogPrint(BCLog::MNBUDGET,"%s: Not a masternode\n", __func__);
return;
}
// Do this 1 in 4 blocks -- spread out the voting activity
// -- this function is only called every fourteenth block, so this is really 1 in 56 blocks
if (GetRandInt(4) != 0) {
LogPrint(BCLog::MNBUDGET,"%s: waiting\n", __func__);
return;
}
// Get the active masternode (operator) key
CTxIn mnVin;
Optional<CKey> mnKey{nullopt};
CBLSSecretKey blsKey;
if (!GetActiveMasternodeKeys(mnVin, mnKey, blsKey)) {
return;
}
std::vector<CBudgetProposal> vBudget = GetBudget();
if (vBudget.empty()) {
LogPrint(BCLog::MNBUDGET,"%s: No proposal can be finalized\n", __func__);
return;
}
std::map<uint256, CBudgetProposal> mapWinningProposals;
for (const CBudgetProposal& p: vBudget) {
mapWinningProposals.emplace(p.GetHash(), p);
}
// Vector containing the hash of finalized budgets to sign
std::vector<uint256> vBudgetHashes;
{
LOCK(cs_budgets);
for (auto& it: mapFinalizedBudgets) {
CFinalizedBudget* pfb = &(it.second);
// we only need to check this once
if (pfb->IsAutoChecked()) continue;
pfb->SetAutoChecked(true);
//only vote for exact matches
if (strBudgetMode == "auto") {
// compare budget payments with winning proposals
if (!pfb->CheckProposals(mapWinningProposals)) {
continue;
}
}
// exact match found. add budget hash to sign it later.
vBudgetHashes.emplace_back(pfb->GetHash());
}
}
// Sign finalized budgets
for (const uint256& budgetHash: vBudgetHashes) {
CFinalizedBudgetVote vote(mnVin, budgetHash);
if (mnKey != nullopt) {
// Legacy MN
if (!vote.Sign(*mnKey, mnKey->GetPubKey().GetID())) {
LogPrintf("%s: Failure to sign budget %s\n", __func__, budgetHash.ToString());
continue;
}
} else {
// DMN
if (!vote.Sign(blsKey)) {
LogPrintf("%s: Failure to sign budget %s with DMN\n", __func__, budgetHash.ToString());
continue;
}
}
std::string strError = "";
if (!UpdateFinalizedBudget(vote, nullptr, strError)) {
LogPrintf("%s: Error submitting vote - %s\n", __func__, strError);
continue;
}
LogPrint(BCLog::MNBUDGET, "%s: new finalized budget vote signed: %s\n", __func__, vote.GetHash().ToString());
AddSeenFinalizedBudgetVote(vote);
vote.Relay();
}
}
CFinalizedBudget* CBudgetManager::FindFinalizedBudget(const uint256& nHash)
{
AssertLockHeld(cs_budgets);
auto it = mapFinalizedBudgets.find(nHash);
return it != mapFinalizedBudgets.end() ? &(it->second) : nullptr;
}
const CBudgetProposal* CBudgetManager::FindProposalByName(const std::string& strProposalName) const
{
LOCK(cs_proposals);
int64_t nYesCountMax = std::numeric_limits<int64_t>::min();
const CBudgetProposal* pbudgetProposal = nullptr;
for (const auto& it: mapProposals) {
const CBudgetProposal& proposal = it.second;
int64_t nYesCount = proposal.GetYeas() - proposal.GetNays();
if (proposal.GetName() == strProposalName && nYesCount > nYesCountMax) {
pbudgetProposal = &proposal;
nYesCountMax = nYesCount;
}
}
return pbudgetProposal;
}
CBudgetProposal* CBudgetManager::FindProposal(const uint256& nHash)
{
AssertLockHeld(cs_proposals);
auto it = mapProposals.find(nHash);
return it != mapProposals.end() ? &(it->second) : nullptr;
}
bool CBudgetManager::GetProposal(const uint256& nHash, CBudgetProposal& bp) const
{
LOCK(cs_proposals);
auto it = mapProposals.find(nHash);
if (it == mapProposals.end()) return false;
bp = it->second;
return true;
}
bool CBudgetManager::GetFinalizedBudget(const uint256& nHash, CFinalizedBudget& fb) const
{
LOCK(cs_budgets);
auto it = mapFinalizedBudgets.find(nHash);
if (it == mapFinalizedBudgets.end()) return false;
fb = it->second;
return true;
}
bool CBudgetManager::IsBudgetPaymentBlock(int nBlockHeight, int& nCountThreshold) const
{
int nHighestCount = GetHighestVoteCount(nBlockHeight);
int nCountEnabled = mnodeman.CountEnabled();
int nFivePercent = nCountEnabled / 20;
// threshold for highest finalized budgets (highest vote count - 10% of active masternodes)
nCountThreshold = nHighestCount - (nCountEnabled / 10);
// reduce the threshold if there are less than 10 enabled masternodes
if (nCountThreshold == nHighestCount) nCountThreshold--;
LogPrint(BCLog::MNBUDGET,"%s: nHighestCount: %lli, 5%% of Masternodes: %lli.\n",
__func__, nHighestCount, nFivePercent);
// If budget doesn't have 5% of the network votes, then we should pay a masternode instead
return (nHighestCount > nFivePercent);
}
bool CBudgetManager::IsBudgetPaymentBlock(int nBlockHeight) const
{
int nCountThreshold;
return IsBudgetPaymentBlock(nBlockHeight, nCountThreshold);
}
TrxValidationStatus CBudgetManager::IsTransactionValid(const CTransaction& txNew, const uint256& nBlockHash, int nBlockHeight) const
{
int nCountThreshold = 0;
if (!IsBudgetPaymentBlock(nBlockHeight, nCountThreshold)) {
// If budget doesn't have 5% of the network votes, then we should pay a masternode instead
return TrxValidationStatus::InValid;
}
// check the highest finalized budgets (- 10% to assist in consensus)
bool fThreshold = false;
{
LOCK(cs_budgets);
// Get the finalized budget with the highest amount of votes..
const auto& highestBudFin = GetBudgetWithHighestVoteCount(nBlockHeight);
const CFinalizedBudget* highestVotesBudget = highestBudFin.m_budget_fin;
if (highestVotesBudget) {
// Need to surpass the threshold
if (highestBudFin.m_vote_count > nCountThreshold) {
fThreshold = true;
if (highestVotesBudget->IsTransactionValid(txNew, nBlockHash, nBlockHeight) ==
TrxValidationStatus::Valid) {
return TrxValidationStatus::Valid;
}
}
// tx not valid
LogPrint(BCLog::MNBUDGET, "%s: ignoring budget. Out of range or tx not valid.\n", __func__);
}
}
// If not enough masternodes autovoted for any of the finalized budgets or if none of the txs
// are valid, we should pay a masternode instead
return fThreshold ? TrxValidationStatus::InValid : TrxValidationStatus::VoteThreshold;
}
std::vector<CBudgetProposal*> CBudgetManager::GetAllProposalsOrdered()
{
LOCK(cs_proposals);
std::vector<CBudgetProposal*> vBudgetProposalRet;
for (auto& it: mapProposals) {
CBudgetProposal* pbudgetProposal = &(it.second);
RemoveStaleVotesOnProposal(pbudgetProposal);
vBudgetProposalRet.push_back(pbudgetProposal);
}
std::sort(vBudgetProposalRet.begin(), vBudgetProposalRet.end(), CBudgetProposal::PtrHigherYes);
return vBudgetProposalRet;
}
std::vector<CBudgetProposal> CBudgetManager::GetBudget()
{
LOCK(cs_proposals);
int nHeight = GetBestHeight();
if (nHeight <= 0)
return {};
// ------- Get proposals ordered by votes (highest to lowest)
std::vector<CBudgetProposal*> vProposalsOrdered = GetAllProposalsOrdered();
// ------- Grab The Budgets In Order
std::vector<CBudgetProposal> vBudgetProposalsRet;
CAmount nBudgetAllocated = 0;
const int nBlocksPerCycle = Params().GetConsensus().nBudgetCycleBlocks;
int nBlockStart = nHeight - nHeight % nBlocksPerCycle + nBlocksPerCycle;
int nBlockEnd = nBlockStart + nBlocksPerCycle - 1;
int mnCount = mnodeman.CountEnabled();
CAmount nTotalBudget = GetTotalBudget(nBlockStart);
for (CBudgetProposal* pbudgetProposal: vProposalsOrdered) {
LogPrint(BCLog::MNBUDGET,"%s: Processing Budget %s\n", __func__, pbudgetProposal->GetName());
//prop start/end should be inside this period
if (pbudgetProposal->IsPassing(nBlockStart, nBlockEnd, mnCount)) {
LogPrint(BCLog::MNBUDGET,"%s: - Check 1 passed: valid=%d | %ld <= %ld | %ld >= %ld | Yeas=%d Nays=%d Count=%d | established=%d\n",
__func__, pbudgetProposal->IsValid(), pbudgetProposal->GetBlockStart(), nBlockStart, pbudgetProposal->GetBlockEnd(),
nBlockEnd, pbudgetProposal->GetYeas(), pbudgetProposal->GetNays(), mnCount / 10, pbudgetProposal->IsEstablished());
if (pbudgetProposal->GetAmount() + nBudgetAllocated <= nTotalBudget) {
pbudgetProposal->SetAllotted(pbudgetProposal->GetAmount());
nBudgetAllocated += pbudgetProposal->GetAmount();
vBudgetProposalsRet.emplace_back(*pbudgetProposal);
LogPrint(BCLog::MNBUDGET,"%s: - Check 2 passed: Budget added\n", __func__);
} else {
pbudgetProposal->SetAllotted(0);
LogPrint(BCLog::MNBUDGET,"%s: - Check 2 failed: no amount allotted\n", __func__);
}
} else {
LogPrint(BCLog::MNBUDGET,"%s: - Check 1 failed: valid=%d | %ld <= %ld | %ld >= %ld | Yeas=%d Nays=%d Count=%d | established=%d\n",
__func__, pbudgetProposal->IsValid(), pbudgetProposal->GetBlockStart(), nBlockStart, pbudgetProposal->GetBlockEnd(),
nBlockEnd, pbudgetProposal->GetYeas(), pbudgetProposal->GetNays(), mnodeman.CountEnabled() / 10,
pbudgetProposal->IsEstablished());
}
}
return vBudgetProposalsRet;
}
std::vector<CFinalizedBudget*> CBudgetManager::GetFinalizedBudgets()
{
LOCK(cs_budgets);
std::vector<CFinalizedBudget*> vFinalizedBudgetsRet;
// ------- Grab The Budgets In Order
for (auto& it: mapFinalizedBudgets) {
vFinalizedBudgetsRet.push_back(&(it.second));
}
std::sort(vFinalizedBudgetsRet.begin(), vFinalizedBudgetsRet.end(), CFinalizedBudget::PtrGreater);
return vFinalizedBudgetsRet;
}
std::string CBudgetManager::GetRequiredPaymentsString(int nBlockHeight)
{
LOCK(cs_budgets);
std::string ret = "unknown-budget";
std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin();
while (it != mapFinalizedBudgets.end()) {
CFinalizedBudget* pfinalizedBudget = &((*it).second);
if (nBlockHeight >= pfinalizedBudget->GetBlockStart() && nBlockHeight <= pfinalizedBudget->GetBlockEnd()) {
CTxBudgetPayment payment;
if (pfinalizedBudget->GetBudgetPaymentByBlock(nBlockHeight, payment)) {
if (ret == "unknown-budget") {
ret = payment.nProposalHash.ToString();
} else {
ret += ",";
ret += payment.nProposalHash.ToString();
}
} else {
LogPrint(BCLog::MNBUDGET,"%s: Couldn't find budget payment for block %d\n", __func__, nBlockHeight);
}
}
++it;
}
return ret;
}
CAmount CBudgetManager::GetTotalBudget(int nHeight)
{
// 100% of block reward after V5.5 upgrade
CAmount nSubsidy = GetBlockValue(nHeight);
// 20% of block reward prior to V5.5 upgrade
if (nHeight <= Params().GetConsensus().vUpgrades[Consensus::UPGRADE_V5_5].nActivationHeight) {
nSubsidy /= 5;
}
// multiplied by the number of blocks in a cycle (144 on testnet, 30*1440 on mainnet)
return nSubsidy * Params().GetConsensus().nBudgetCycleBlocks;
}
void CBudgetManager::AddSeenProposalVote(const CBudgetVote& vote)
{
LOCK(cs_votes);
mapSeenProposalVotes.emplace(vote.GetHash(), vote);
}
void CBudgetManager::AddSeenFinalizedBudgetVote(const CFinalizedBudgetVote& vote)
{
LOCK(cs_finalizedvotes);
mapSeenFinalizedBudgetVotes.emplace(vote.GetHash(), vote);
}
void CBudgetManager::RemoveStaleVotesOnProposal(CBudgetProposal* prop)
{
AssertLockHeld(cs_proposals);
LogPrint(BCLog::MNBUDGET, "Cleaning proposal votes for %s. Before: YES=%d, NO=%d\n",
prop->GetName(), prop->GetYeas(), prop->GetNays());
auto it = prop->mapVotes.begin();
while (it != prop->mapVotes.end()) {
auto mnList = deterministicMNManager->GetListAtChainTip();
auto dmn = mnList.GetMNByCollateral(it->first);
if (dmn) {
(*it).second.SetValid(!dmn->IsPoSeBanned());
} else {
// -- Legacy System (!TODO: remove after enforcement) --
CMasternode* pmn = mnodeman.Find(it->first);
(*it).second.SetValid(pmn && pmn->IsEnabled());
}
++it;
}
LogPrint(BCLog::MNBUDGET, "Cleaned proposal votes for %s. After: YES=%d, NO=%d\n",
prop->GetName(), prop->GetYeas(), prop->GetNays());
}
void CBudgetManager::RemoveStaleVotesOnFinalBudget(CFinalizedBudget* fbud)
{
AssertLockHeld(cs_budgets);
LogPrint(BCLog::MNBUDGET, "Cleaning finalized budget votes for [%s (%s)]. Before: %d\n",
fbud->GetName(), fbud->GetProposalsStr(), fbud->GetVoteCount());
auto it = fbud->mapVotes.begin();
while (it != fbud->mapVotes.end()) {
auto mnList = deterministicMNManager->GetListAtChainTip();
auto dmn = mnList.GetMNByCollateral(it->first);
if (dmn) {
(*it).second.SetValid(!dmn->IsPoSeBanned());
} else {
// -- Legacy System (!TODO: remove after enforcement) --
CMasternode* pmn = mnodeman.Find(it->first);
(*it).second.SetValid(pmn && pmn->IsEnabled());
}
++it;
}
LogPrint(BCLog::MNBUDGET, "Cleaned finalized budget votes for [%s (%s)]. After: %d\n",
fbud->GetName(), fbud->GetProposalsStr(), fbud->GetVoteCount());
}
CDataStream CBudgetManager::GetProposalVoteSerialized(const uint256& voteHash) const
{
LOCK(cs_votes);
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << mapSeenProposalVotes.at(voteHash);
return ss;
}
CDataStream CBudgetManager::GetProposalSerialized(const uint256& propHash) const
{
LOCK(cs_proposals);
return mapProposals.at(propHash).GetBroadcast();
}
CDataStream CBudgetManager::GetFinalizedBudgetVoteSerialized(const uint256& voteHash) const
{
LOCK(cs_finalizedvotes);
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << mapSeenFinalizedBudgetVotes.at(voteHash);
return ss;
}
CDataStream CBudgetManager::GetFinalizedBudgetSerialized(const uint256& budgetHash) const
{
LOCK(cs_budgets);
return mapFinalizedBudgets.at(budgetHash).GetBroadcast();
}
bool CBudgetManager::AddAndRelayProposalVote(const CBudgetVote& vote, std::string& strError)
{
if (UpdateProposal(vote, nullptr, strError)) {
AddSeenProposalVote(vote);
vote.Relay();
return true;
}
return false;
}
void CBudgetManager::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload)
{
if (g_tiertwo_sync_state.GetSyncPhase() <= MASTERNODE_SYNC_BUDGET) return;
if (strBudgetMode == "suggest") { //suggest the budget we see
SubmitFinalBudget();
}
int nCurrentHeight = GetBestHeight();
//this function should be called 1/14 blocks, allowing up to 100 votes per day on all proposals
if (nCurrentHeight % 14 != 0) return;
// incremental sync with our peers
if (g_tiertwo_sync_state.IsSynced()) {
LogPrint(BCLog::MNBUDGET,"%s: incremental sync started\n", __func__);
// Once every 7 days, try to relay the complete budget data
if (GetRandInt(Params().IsRegTestNet() ? 2 : 720) == 0) {
ResetSync();
}
CBudgetManager* manager = this;
g_connman->ForEachNode([manager](CNode* pnode){
if (pnode->nVersion >= ActiveProtocol())
manager->Sync(pnode, true);
});
MarkSynced();
}
// remove expired/heavily downvoted budgets
CheckAndRemove();
{
LOCK(cs_proposals);
LogPrint(BCLog::MNBUDGET,"%s: mapProposals cleanup - size: %d\n", __func__, mapProposals.size());
for (auto& it: mapProposals) {