forked from dashpay/dash
/
governance.cpp
1472 lines (1198 loc) · 51.8 KB
/
governance.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-2018 The BiblePay Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "governance.h"
#include "consensus/validation.h"
#include "governance-classes.h"
#include "governance-object.h"
#include "governance-validators.h"
#include "governance-vote.h"
#include "init.h"
#include "masternode-sync.h"
#include "masternode.h"
#include "masternodeman.h"
#include "messagesigner.h"
#include "net_processing.h"
#include "netfulfilledman.h"
#include "netmessagemaker.h"
#include "util.h"
#include "validationinterface.h"
CGovernanceManager governance;
int nSubmittedFinalBudget;
const std::string CGovernanceManager::SERIALIZATION_VERSION_STRING = "CGovernanceManager-Version-14";
const int CGovernanceManager::MAX_TIME_FUTURE_DEVIATION = 60 * 60;
const int CGovernanceManager::RELIABLE_PROPAGATION_TIME = 60;
CGovernanceManager::CGovernanceManager() :
nTimeLastDiff(0),
nCachedBlockHeight(0),
mapObjects(),
mapErasedGovernanceObjects(),
mapMasternodeOrphanObjects(),
cmapVoteToObject(MAX_CACHE_SIZE),
cmapInvalidVotes(MAX_CACHE_SIZE),
cmmapOrphanVotes(MAX_CACHE_SIZE),
mapLastMasternodeObject(),
setRequestedObjects(),
fRateChecksEnabled(true),
cs()
{
}
// Accessors for thread-safe access to maps
bool CGovernanceManager::HaveObjectForHash(const uint256& nHash) const
{
LOCK(cs);
return (mapObjects.count(nHash) == 1 || mapPostponedObjects.count(nHash) == 1);
}
bool CGovernanceManager::SerializeObjectForHash(const uint256& nHash, CDataStream& ss) const
{
LOCK(cs);
object_m_cit it = mapObjects.find(nHash);
if (it == mapObjects.end()) {
it = mapPostponedObjects.find(nHash);
if (it == mapPostponedObjects.end())
return false;
}
ss << it->second;
return true;
}
bool CGovernanceManager::HaveVoteForHash(const uint256& nHash) const
{
LOCK(cs);
CGovernanceObject* pGovobj = nullptr;
return cmapVoteToObject.Get(nHash, pGovobj) && pGovobj->GetVoteFile().HasVote(nHash);
}
int CGovernanceManager::GetVoteCount() const
{
LOCK(cs);
return (int)cmapVoteToObject.GetSize();
}
bool CGovernanceManager::SerializeVoteForHash(const uint256& nHash, CDataStream& ss) const
{
LOCK(cs);
CGovernanceObject* pGovobj = nullptr;
return cmapVoteToObject.Get(nHash, pGovobj) && pGovobj->GetVoteFile().SerializeVoteToStream(nHash, ss);
}
void CGovernanceManager::ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, CConnman& connman)
{
// lite mode is not supported
if (fLiteMode) return;
if (!masternodeSync.IsBlockchainSynced()) return;
// ANOTHER USER IS ASKING US TO HELP THEM SYNC GOVERNANCE OBJECT DATA
if (strCommand == NetMsgType::MNGOVERNANCESYNC) {
if (pfrom->nVersion < MIN_GOVERNANCE_PEER_PROTO_VERSION) {
LogPrint("gobject", "MNGOVERNANCESYNC -- peer=%d using obsolete version %i\n", pfrom->id, pfrom->nVersion);
connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE, strprintf("Version must be %d or greater", MIN_GOVERNANCE_PEER_PROTO_VERSION)));
return;
}
// Ignore such requests until we are fully synced.
// We could start processing this after masternode list is synced
// but this is a heavy one so it's better to finish sync first.
if (!masternodeSync.IsSynced()) return;
uint256 nProp;
CBloomFilter filter;
vRecv >> nProp;
if (pfrom->nVersion >= GOVERNANCE_FILTER_PROTO_VERSION) {
vRecv >> filter;
filter.UpdateEmptyFull();
} else {
filter.clear();
}
if (nProp == uint256()) {
SyncAll(pfrom, connman);
} else {
SyncSingleObjAndItsVotes(pfrom, nProp, filter, connman);
}
LogPrint("gobject", "MNGOVERNANCESYNC -- syncing governance objects to our peer at %s\n", pfrom->addr.ToString());
}
// A NEW GOVERNANCE OBJECT HAS ARRIVED
else if (strCommand == NetMsgType::MNGOVERNANCEOBJECT) {
// MAKE SURE WE HAVE A VALID REFERENCE TO THE TIP BEFORE CONTINUING
CGovernanceObject govobj;
vRecv >> govobj;
uint256 nHash = govobj.GetHash();
{
LOCK(cs_main);
connman.RemoveAskFor(nHash);
}
if (pfrom->nVersion < MIN_GOVERNANCE_PEER_PROTO_VERSION) {
LogPrint("gobject", "MNGOVERNANCEOBJECT -- peer=%d using obsolete version %i\n", pfrom->id, pfrom->nVersion);
connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE, strprintf("Version must be %d or greater", MIN_GOVERNANCE_PEER_PROTO_VERSION)));
return;
}
if (!masternodeSync.IsMasternodeListSynced()) {
LogPrint("gobject", "MNGOVERNANCEOBJECT -- masternode list not synced\n");
return;
}
std::string strHash = nHash.ToString();
LogPrint("gobject", "MNGOVERNANCEOBJECT -- Received object: %s\n", strHash);
if (!AcceptObjectMessage(nHash)) {
LogPrintf("MNGOVERNANCEOBJECT -- Received unrequested object: %s\n", strHash);
return;
}
LOCK2(cs_main, cs);
if (mapObjects.count(nHash) || mapPostponedObjects.count(nHash) ||
mapErasedGovernanceObjects.count(nHash) || mapMasternodeOrphanObjects.count(nHash)) {
// TODO - print error code? what if it's GOVOBJ_ERROR_IMMATURE?
LogPrint("gobject", "MNGOVERNANCEOBJECT -- Received already seen object: %s\n", strHash);
return;
}
bool fRateCheckBypassed = false;
if (!MasternodeRateCheck(govobj, true, false, fRateCheckBypassed)) {
LogPrintf("MNGOVERNANCEOBJECT -- masternode rate check failed - %s - (current block height %d) \n", strHash, nCachedBlockHeight);
return;
}
std::string strError = "";
// CHECK OBJECT AGAINST LOCAL BLOCKCHAIN
bool fMasternodeMissing = false;
bool fMissingConfirmations = false;
bool fIsValid = govobj.IsValidLocally(strError, fMasternodeMissing, fMissingConfirmations, true);
if (fRateCheckBypassed && (fIsValid || fMasternodeMissing)) {
if (!MasternodeRateCheck(govobj, true)) {
LogPrintf("MNGOVERNANCEOBJECT -- masternode rate check failed (after signature verification) - %s - (current block height %d) \n", strHash, nCachedBlockHeight);
return;
}
}
if (!fIsValid) {
if (fMasternodeMissing) {
int& count = mapMasternodeOrphanCounter[govobj.GetMasternodeOutpoint()];
if (count >= 10) {
LogPrint("gobject", "MNGOVERNANCEOBJECT -- Too many orphan objects, missing masternode=%s\n", govobj.GetMasternodeOutpoint().ToStringShort());
// ask for this object again in 2 minutes
CInv inv(MSG_GOVERNANCE_OBJECT, govobj.GetHash());
pfrom->AskFor(inv);
return;
}
count++;
ExpirationInfo info(pfrom->GetId(), GetAdjustedTime() + GOVERNANCE_ORPHAN_EXPIRATION_TIME);
mapMasternodeOrphanObjects.insert(std::make_pair(nHash, object_info_pair_t(govobj, info)));
LogPrintf("MNGOVERNANCEOBJECT -- Missing masternode for: %s, strError = %s\n", strHash, strError);
} else if (fMissingConfirmations) {
AddPostponedObject(govobj);
LogPrintf("MNGOVERNANCEOBJECT -- Not enough fee confirmations for: %s, strError = %s\n", strHash, strError);
} else {
LogPrintf("MNGOVERNANCEOBJECT -- Governance object is invalid - %s\n", strError);
// apply node's ban score (see RAN-0708)
Misbehaving(pfrom->GetId(), 1);
}
return;
}
AddGovernanceObject(govobj, connman, pfrom);
}
// A NEW GOVERNANCE OBJECT VOTE HAS ARRIVED
else if (strCommand == NetMsgType::MNGOVERNANCEOBJECTVOTE) {
CGovernanceVote vote;
vRecv >> vote;
// TODO remove this check after full DIP3 deployment
if (vote.GetTimestamp() < GetMinVoteTime()) {
// Ignore votes pre-DIP3
return;
}
uint256 nHash = vote.GetHash();
{
LOCK(cs_main);
connman.RemoveAskFor(nHash);
}
if (pfrom->nVersion < MIN_GOVERNANCE_PEER_PROTO_VERSION) {
LogPrint("gobject", "MNGOVERNANCEOBJECTVOTE -- peer=%d using obsolete version %i\n", pfrom->id, pfrom->nVersion);
connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE, strprintf("Version must be %d or greater", MIN_GOVERNANCE_PEER_PROTO_VERSION)));
}
// Ignore such messages until masternode list is synced
if (!masternodeSync.IsMasternodeListSynced()) {
LogPrint("gobject", "MNGOVERNANCEOBJECTVOTE -- masternode list not synced\n");
return;
}
if (fDebugSpam)
LogPrint("gobject", "MNGOVERNANCEOBJECTVOTE -- Received vote: %s\n", vote.ToString());
std::string strHash = nHash.ToString();
if (!AcceptVoteMessage(nHash)) {
if (fDebugSpam)
LogPrint("gobject", "MNGOVERNANCEOBJECTVOTE -- Received unrequested vote object: %s, hash: %s, peer = %d\n",
vote.ToString(), strHash, pfrom->GetId());
return;
}
CGovernanceException exception;
if (ProcessVote(pfrom, vote, exception, connman))
{
if (fDebugSpam)
LogPrint("gobject", "MNGOVERNANCEOBJECTVOTE -- %s new\n", strHash);
masternodeSync.BumpAssetLastTime("MNGOVERNANCEOBJECTVOTE");
vote.Relay(connman);
} else {
if (fDebugSpam)
LogPrint("gobject", "MNGOVERNANCEOBJECTVOTE -- Rejected vote, error = %s\n", exception.what());
if ((exception.GetNodePenalty() != 0) && masternodeSync.IsSynced()) {
LOCK(cs_main);
Misbehaving(pfrom->GetId(), exception.GetNodePenalty());
}
return;
}
// SEND NOTIFICATION TO SCRIPT/ZMQ
GetMainSignals().NotifyGovernanceVote(vote);
}
}
void CGovernanceManager::CheckOrphanVotes(CGovernanceObject& govobj, CGovernanceException& exception, CConnman& connman)
{
uint256 nHash = govobj.GetHash();
std::vector<vote_time_pair_t> vecVotePairs;
cmmapOrphanVotes.GetAll(nHash, vecVotePairs);
ScopedLockBool guard(cs, fRateChecksEnabled, false);
int64_t nNow = GetAdjustedTime();
for (auto& pairVote : vecVotePairs) {
bool fRemove = false;
CGovernanceVote& vote = pairVote.first;
CGovernanceException exception;
if (pairVote.second < nNow) {
fRemove = true;
} else if (govobj.ProcessVote(nullptr, vote, exception, connman)) {
vote.Relay(connman);
fRemove = true;
}
if (fRemove) {
cmmapOrphanVotes.Erase(nHash, pairVote);
}
}
}
void CGovernanceManager::AddGovernanceObject(CGovernanceObject& govobj, CConnman& connman, CNode* pfrom)
{
if (fDebugSpam)
DBG(std::cout << "CGovernanceManager::AddGovernanceObject START" << std::endl;);
uint256 nHash = govobj.GetHash();
std::string strHash = nHash.ToString();
// UPDATE CACHED VARIABLES FOR THIS OBJECT AND ADD IT TO OUR MANANGED DATA
govobj.UpdateSentinelVariables(); //this sets local vars in object
LOCK2(cs_main, cs);
std::string strError = "";
// MAKE SURE THIS OBJECT IS OK
if (!govobj.IsValidLocally(strError, true)) {
LogPrintf("CGovernanceManager::AddGovernanceObject -- invalid governance object - %s - (nCachedBlockHeight %d) \n", strError, nCachedBlockHeight);
return;
}
LogPrint("gobject", "CGovernanceManager::AddGovernanceObject -- Adding object: hash = %s, type = %d\n", nHash.ToString(), govobj.GetObjectType());
// INSERT INTO OUR GOVERNANCE OBJECT MEMORY
// IF WE HAVE THIS OBJECT ALREADY, WE DON'T WANT ANOTHER COPY
auto objpair = mapObjects.emplace(nHash, govobj);
if (!objpair.second)
{
if (fDebugSpam)
LogPrintf("CGovernanceManager::AddGovernanceObject -- already have governance object %s\n", nHash.ToString());
return;
}
// SHOULD WE ADD THIS OBJECT TO ANY OTHER MANANGERS?
DBG(std::cout << "CGovernanceManager::AddGovernanceObject Before trigger block, GetDataAsPlainString = "
<< govobj.GetDataAsPlainString()
<< ", nObjectType = " << govobj.nObjectType
<< std::endl;);
if (govobj.nObjectType == GOVERNANCE_OBJECT_TRIGGER) {
DBG(std::cout << "CGovernanceManager::AddGovernanceObject Before AddNewTrigger" << std::endl;);
if (!triggerman.AddNewTrigger(nHash)) {
LogPrint("gobject", "CGovernanceManager::AddGovernanceObject -- undo adding invalid trigger object: hash = %s\n", nHash.ToString());
CGovernanceObject& objref = objpair.first->second;
objref.fCachedDelete = true;
if (objref.nDeletionTime == 0) {
objref.nDeletionTime = GetAdjustedTime();
}
return;
}
DBG(std::cout << "CGovernanceManager::AddGovernanceObject After AddNewTrigger" << std::endl;);
}
if (fDebugSpam)
LogPrintf("CGovernanceManager::AddGovernanceObject -- %s new, received from %s\n", strHash, pfrom ? pfrom->GetAddrName() : "nullptr");
govobj.Relay(connman);
// Update the rate buffer
MasternodeRateUpdate(govobj);
masternodeSync.BumpAssetLastTime("CGovernanceManager::AddGovernanceObject");
// WE MIGHT HAVE PENDING/ORPHAN VOTES FOR THIS OBJECT
CGovernanceException exception;
CheckOrphanVotes(govobj, exception, connman);
// SEND NOTIFICATION TO SCRIPT/ZMQ
GetMainSignals().NotifyGovernanceObject(govobj);
DBG(std::cout << "CGovernanceManager::AddGovernanceObject END" << std::endl;);
}
void CGovernanceManager::UpdateCachesAndClean()
{
if (fDebugSpam)
LogPrint("gobject", "CGovernanceManager::UpdateCachesAndClean\n");
std::vector<uint256> vecDirtyHashes = mnodeman.GetAndClearDirtyGovernanceObjectHashes();
LOCK2(cs_main, cs);
for (const uint256& nHash : vecDirtyHashes) {
object_m_it it = mapObjects.find(nHash);
if (it == mapObjects.end()) {
continue;
}
it->second.ClearMasternodeVotes();
it->second.fDirtyCache = true;
}
ScopedLockBool guard(cs, fRateChecksEnabled, false);
// Clean up any expired or invalid triggers
triggerman.CleanAndRemove();
object_m_it it = mapObjects.begin();
int64_t nNow = GetAdjustedTime();
while (it != mapObjects.end()) {
CGovernanceObject* pObj = &((*it).second);
if (!pObj) {
++it;
continue;
}
uint256 nHash = it->first;
std::string strHash = nHash.ToString();
// IF CACHE IS NOT DIRTY, WHY DO THIS?
if (pObj->IsSetDirtyCache()) {
// UPDATE LOCAL VALIDITY AGAINST CRYPTO DATA
pObj->UpdateLocalValidity();
// UPDATE SENTINEL SIGNALING VARIABLES
pObj->UpdateSentinelVariables();
}
// IF DELETE=TRUE, THEN CLEAN THE MESS UP!
int64_t nTimeSinceDeletion = nNow - pObj->GetDeletionTime();
if (fDebugSpam)
LogPrint("gobject", "CGovernanceManager::UpdateCachesAndClean -- Checking object for deletion: %s, deletion time = %d, time since deletion = %d, delete flag = %d, expired flag = %d\n",
strHash, pObj->GetDeletionTime(), nTimeSinceDeletion, pObj->IsSetCachedDelete(), pObj->IsSetExpired());
if ((pObj->IsSetCachedDelete() || pObj->IsSetExpired()) &&
(nTimeSinceDeletion >= GOVERNANCE_DELETION_DELAY)) {
if (fDebugSpam)
LogPrintf("CGovernanceManager::UpdateCachesAndClean -- erase obj %s\n", (*it).first.ToString());
mnodeman.RemoveGovernanceObject(pObj->GetHash());
// Remove vote references
const object_ref_cm_t::list_t& listItems = cmapVoteToObject.GetItemList();
object_ref_cm_t::list_cit lit = listItems.begin();
while (lit != listItems.end()) {
if (lit->value == pObj) {
uint256 nKey = lit->key;
++lit;
cmapVoteToObject.Erase(nKey);
} else {
++lit;
}
}
int64_t nTimeExpired{0};
if (pObj->GetObjectType() == GOVERNANCE_OBJECT_PROPOSAL) {
// keep hashes of deleted proposals forever
nTimeExpired = std::numeric_limits<int64_t>::max();
} else {
int64_t nSuperblockCycleSeconds = Params().GetConsensus().nDCCSuperblockCycle * Params().GetConsensus().nPowTargetSpacing;
nTimeExpired = pObj->GetCreationTime() + 2 * nSuperblockCycleSeconds * 30 + GOVERNANCE_DELETION_DELAY;
}
mapErasedGovernanceObjects.insert(std::make_pair(nHash, nTimeExpired));
mapObjects.erase(it++);
} else {
// NOTE: triggers are handled via triggerman
if (pObj->GetObjectType() == GOVERNANCE_OBJECT_PROPOSAL) {
CProposalValidator validator(pObj->GetDataAsHexString());
if (!validator.Validate())
{
if (fDebugSpam)
LogPrintf("CGovernanceManager::UpdateCachesAndClean -- set for deletion expired obj %s\n", (*it).first.ToString());
pObj->fCachedDelete = true;
if (pObj->nDeletionTime == 0) {
pObj->nDeletionTime = nNow;
}
}
}
++it;
}
}
// forget about expired deleted objects
hash_time_m_it s_it = mapErasedGovernanceObjects.begin();
while (s_it != mapErasedGovernanceObjects.end()) {
if (s_it->second < nNow) {
mapErasedGovernanceObjects.erase(s_it++);
} else {
++s_it;
}
}
if (fDebugSpam)
LogPrintf("CGovernanceManager::UpdateCachesAndClean -- %s\n", ToString());
}
CGovernanceObject* CGovernanceManager::FindGovernanceObject(const uint256& nHash)
{
LOCK(cs);
if (mapObjects.count(nHash)) return &mapObjects[nHash];
return nullptr;
}
std::vector<CGovernanceVote> CGovernanceManager::GetMatchingVotes(const uint256& nParentHash) const
{
LOCK(cs);
std::vector<CGovernanceVote> vecResult;
object_m_cit it = mapObjects.find(nParentHash);
if (it == mapObjects.end()) {
return vecResult;
}
return it->second.GetVoteFile().GetVotes();
}
std::vector<CGovernanceVote> CGovernanceManager::GetCurrentVotes(const uint256& nParentHash, const COutPoint& mnCollateralOutpointFilter) const
{
LOCK(cs);
std::vector<CGovernanceVote> vecResult;
// Find the governance object or short-circuit.
object_m_cit it = mapObjects.find(nParentHash);
if (it == mapObjects.end()) return vecResult;
const CGovernanceObject& govobj = it->second;
CMasternode mn;
std::map<COutPoint, CMasternode> mapMasternodes;
if (mnCollateralOutpointFilter.IsNull()) {
mapMasternodes = mnodeman.GetFullMasternodeMap();
} else if (mnodeman.Get(mnCollateralOutpointFilter, mn)) {
mapMasternodes[mnCollateralOutpointFilter] = mn;
}
// Loop thru each MN collateral outpoint and get the votes for the `nParentHash` governance object
for (const auto& mnpair : mapMasternodes) {
// get a vote_rec_t from the govobj
vote_rec_t voteRecord;
if (!govobj.GetCurrentMNVotes(mnpair.first, voteRecord)) continue;
for (const auto& voteInstancePair : voteRecord.mapInstances) {
int signal = voteInstancePair.first;
int outcome = voteInstancePair.second.eOutcome;
int64_t nCreationTime = voteInstancePair.second.nCreationTime;
CGovernanceVote vote = CGovernanceVote(mnpair.first, nParentHash, (vote_signal_enum_t)signal, (vote_outcome_enum_t)outcome);
vote.SetTime(nCreationTime);
vecResult.push_back(vote);
}
}
return vecResult;
}
std::vector<const CGovernanceObject*> CGovernanceManager::GetAllNewerThan(int64_t nMoreThanTime) const
{
LOCK(cs);
std::vector<const CGovernanceObject*> vGovObjs;
for (const auto& objPair : mapObjects) {
// IF THIS OBJECT IS OLDER THAN TIME, CONTINUE
if (objPair.second.GetCreationTime() < nMoreThanTime) {
continue;
}
// ADD GOVERNANCE OBJECT TO LIST
const CGovernanceObject* pGovObj = &(objPair.second);
vGovObjs.push_back(pGovObj);
}
return vGovObjs;
}
//
// Sort by votes, if there's a tie sort by their feeHash TX
//
struct sortProposalsByVotes {
bool operator()(const std::pair<CGovernanceObject*, int>& left, const std::pair<CGovernanceObject*, int>& right)
{
if (left.second != right.second) return (left.second > right.second);
return (UintToArith256(left.first->GetCollateralHash()) > UintToArith256(right.first->GetCollateralHash()));
}
};
void CGovernanceManager::DoMaintenance(CConnman& connman)
{
if (fLiteMode || !masternodeSync.IsSynced() || ShutdownRequested()) return;
if (deterministicMNManager->IsDeterministicMNsSporkActive()) {
ClearPreDIP3Votes();
RemoveInvalidProposalVotes();
}
// CHECK OBJECTS WE'VE ASKED FOR, REMOVE OLD ENTRIES
CleanOrphanObjects();
RequestOrphanObjects(connman);
// CHECK AND REMOVE - REPROCESS GOVERNANCE OBJECTS
UpdateCachesAndClean();
}
bool CGovernanceManager::ConfirmInventoryRequest(const CInv& inv)
{
// do not request objects until it's time to sync
if (!masternodeSync.IsWinnersListSynced()) return false;
LOCK(cs);
if (fDebugSpam)
LogPrint("gobject", "CGovernanceManager::ConfirmInventoryRequest inv = %s\n", inv.ToString());
// First check if we've already recorded this object
switch (inv.type) {
case MSG_GOVERNANCE_OBJECT: {
if (mapObjects.count(inv.hash) == 1 || mapPostponedObjects.count(inv.hash) == 1) {
if (fDebugSpam)
LogPrint("gobject", "CGovernanceManager::ConfirmInventoryRequest already have governance object, returning false\n");
return false;
}
break;
}
case MSG_GOVERNANCE_OBJECT_VOTE: {
if (cmapVoteToObject.HasKey(inv.hash)) {
if (fDebugSpam) LogPrint("gobject", "CGovernanceManager::ConfirmInventoryRequest already have governance vote, returning false\n");
return false;
}
break;
}
default:
if (fDebugSpam)
LogPrint("gobject", "CGovernanceManager::ConfirmInventoryRequest unknown type, returning false\n");
return false;
}
hash_s_t* setHash = nullptr;
switch (inv.type) {
case MSG_GOVERNANCE_OBJECT:
setHash = &setRequestedObjects;
break;
case MSG_GOVERNANCE_OBJECT_VOTE:
setHash = &setRequestedVotes;
break;
default:
return false;
}
hash_s_cit it = setHash->find(inv.hash);
if (it == setHash->end()) {
setHash->insert(inv.hash);
if (fDebugSpam)
LogPrint("gobject", "CGovernanceManager::ConfirmInventoryRequest added inv to requested set\n");
}
if (fDebugSpam)
LogPrint("gobject", "CGovernanceManager::ConfirmInventoryRequest reached end, returning true\n");
return true;
}
void CGovernanceManager::SyncSingleObjAndItsVotes(CNode* pnode, const uint256& nProp, const CBloomFilter& filter, CConnman& connman)
{
// do not provide any data until our node is synced
if (!masternodeSync.IsSynced()) return;
int nVoteCount = 0;
// SYNC GOVERNANCE OBJECTS WITH OTHER CLIENT
if (fDebugSpam)
LogPrint("gobject", "CGovernanceManager::%s -- syncing single object to peer=%d, nProp = %s\n", __func__, pnode->id, nProp.ToString());
LOCK2(cs_main, cs);
// single valid object and its valid votes
object_m_it it = mapObjects.find(nProp);
if (it == mapObjects.end()) {
LogPrint("gobject", "CGovernanceManager::%s -- no matching object for hash %s, peer=%d\n", __func__, nProp.ToString(), pnode->id);
return;
}
CGovernanceObject& govobj = it->second;
std::string strHash = it->first.ToString();
if (fDebugSpam)
LogPrint("gobject", "CGovernanceManager::%s -- attempting to sync govobj: %s, peer=%d\n", __func__, strHash, pnode->id);
if (govobj.IsSetCachedDelete() || govobj.IsSetExpired())
{
if (fDebugSpam)
LogPrintf("CGovernanceManager::%s -- not syncing deleted/expired govobj: %s, peer=%d\n", __func__, strHash, pnode->id);
return;
}
// Push the govobj inventory message over to the other client
if (fDebugSpam)
LogPrint("gobject", "CGovernanceManager::%s -- syncing govobj: %s, peer=%d\n", __func__, strHash, pnode->id);
pnode->PushInventory(CInv(MSG_GOVERNANCE_OBJECT, it->first));
auto fileVotes = govobj.GetVoteFile();
for (const auto& vote : fileVotes.GetVotes()) {
uint256 nVoteHash = vote.GetHash();
bool onlyVotingKeyAllowed = govobj.GetObjectType() == GOVERNANCE_OBJECT_PROPOSAL && vote.GetSignal() == VOTE_SIGNAL_FUNDING;
if (filter.contains(nVoteHash) || !vote.IsValid(onlyVotingKeyAllowed)) {
continue;
}
pnode->PushInventory(CInv(MSG_GOVERNANCE_OBJECT_VOTE, nVoteHash));
++nVoteCount;
}
CNetMsgMaker msgMaker(pnode->GetSendVersion());
connman.PushMessage(pnode, msgMaker.Make(NetMsgType::SYNCSTATUSCOUNT, MASTERNODE_SYNC_GOVOBJ, 1));
connman.PushMessage(pnode, msgMaker.Make(NetMsgType::SYNCSTATUSCOUNT, MASTERNODE_SYNC_GOVOBJ_VOTE, nVoteCount));
if (fDebugSpam)
LogPrintf("CGovernanceManager::%s -- sent 1 object and %d votes to peer=%d\n", __func__, nVoteCount, pnode->id);
}
void CGovernanceManager::SyncAll(CNode* pnode, CConnman& connman) const
{
// do not provide any data until our node is synced
if (!masternodeSync.IsSynced()) return;
if (netfulfilledman.HasFulfilledRequest(pnode->addr, NetMsgType::MNGOVERNANCESYNC)) {
LOCK(cs_main);
// Asking for the whole list multiple times in a short period of time is no good
LogPrint("gobject", "CGovernanceManager::%s -- peer already asked me for the list\n", __func__);
Misbehaving(pnode->GetId(), 20);
return;
}
netfulfilledman.AddFulfilledRequest(pnode->addr, NetMsgType::MNGOVERNANCESYNC);
int nObjCount = 0;
int nVoteCount = 0;
// SYNC GOVERNANCE OBJECTS WITH OTHER CLIENT
LogPrint("gobject", "CGovernanceManager::%s -- syncing all objects to peer=%d\n", __func__, pnode->id);
LOCK2(cs_main, cs);
// all valid objects, no votes
for (const auto& objPair : mapObjects) {
uint256 nHash = objPair.first;
const CGovernanceObject& govobj = objPair.second;
std::string strHash = nHash.ToString();
LogPrint("gobject", "CGovernanceManager::%s -- attempting to sync govobj: %s, peer=%d\n", __func__, strHash, pnode->id);
if (govobj.IsSetCachedDelete() || govobj.IsSetExpired()) {
LogPrintf("CGovernanceManager::%s -- not syncing deleted/expired govobj: %s, peer=%d\n", __func__,
strHash, pnode->id);
continue;
}
// Push the inventory budget proposal message over to the other client
if (fDebugSpam)
LogPrint("gobject", "CGovernanceManager::%s -- syncing govobj: %s, peer=%d\n", __func__, strHash, pnode->id);
pnode->PushInventory(CInv(MSG_GOVERNANCE_OBJECT, nHash));
++nObjCount;
}
CNetMsgMaker msgMaker(pnode->GetSendVersion());
connman.PushMessage(pnode, msgMaker.Make(NetMsgType::SYNCSTATUSCOUNT, MASTERNODE_SYNC_GOVOBJ, nObjCount));
connman.PushMessage(pnode, msgMaker.Make(NetMsgType::SYNCSTATUSCOUNT, MASTERNODE_SYNC_GOVOBJ_VOTE, nVoteCount));
if (fDebugSpam)
LogPrintf("CGovernanceManager::%s -- sent %d objects and %d votes to peer=%d\n", __func__, nObjCount, nVoteCount, pnode->id);
}
void CGovernanceManager::MasternodeRateUpdate(const CGovernanceObject& govobj)
{
if (govobj.GetObjectType() != GOVERNANCE_OBJECT_TRIGGER) return;
const COutPoint& masternodeOutpoint = govobj.GetMasternodeOutpoint();
txout_m_it it = mapLastMasternodeObject.find(masternodeOutpoint);
if (it == mapLastMasternodeObject.end()) {
it = mapLastMasternodeObject.insert(txout_m_t::value_type(masternodeOutpoint, last_object_rec(true))).first;
}
int64_t nTimestamp = govobj.GetCreationTime();
it->second.triggerBuffer.AddTimestamp(nTimestamp);
if (nTimestamp > GetTime() + MAX_TIME_FUTURE_DEVIATION - RELIABLE_PROPAGATION_TIME) {
// schedule additional relay for the object
setAdditionalRelayObjects.insert(govobj.GetHash());
}
it->second.fStatusOK = true;
}
bool CGovernanceManager::MasternodeRateCheck(const CGovernanceObject& govobj, bool fUpdateFailStatus)
{
bool fRateCheckBypassed;
return MasternodeRateCheck(govobj, fUpdateFailStatus, true, fRateCheckBypassed);
}
bool CGovernanceManager::MasternodeRateCheck(const CGovernanceObject& govobj, bool fUpdateFailStatus, bool fForce, bool& fRateCheckBypassed)
{
LOCK(cs);
fRateCheckBypassed = false;
if (!masternodeSync.IsSynced() || !fRateChecksEnabled) {
return true;
}
if (govobj.GetObjectType() != GOVERNANCE_OBJECT_TRIGGER) {
return true;
}
const COutPoint& masternodeOutpoint = govobj.GetMasternodeOutpoint();
int64_t nTimestamp = govobj.GetCreationTime();
int64_t nNow = GetAdjustedTime();
// BIBLEPAY - R ANDREWS - Adjust Receive Rate buffer for gobjects
int64_t nSuperblockCycleSeconds = Params().GetConsensus().nDCCSuperblockCycle * Params().GetConsensus().nPowTargetSpacing;
std::string strHash = govobj.GetHash().ToString();
if (nTimestamp < nNow - 2 * nSuperblockCycleSeconds * 30) {
LogPrintf("CGovernanceManager::MasternodeRateCheck -- object %s rejected due to too old timestamp, masternode = %s, timestamp = %d, current time = %d\n",
strHash, masternodeOutpoint.ToStringShort(), nTimestamp, nNow);
return false;
}
if (nTimestamp > nNow + MAX_TIME_FUTURE_DEVIATION) {
LogPrintf("CGovernanceManager::MasternodeRateCheck -- object %s rejected due to too new (future) timestamp, masternode = %s, timestamp = %d, current time = %d\n",
strHash, masternodeOutpoint.ToStringShort(), nTimestamp, nNow);
return false;
}
txout_m_it it = mapLastMasternodeObject.find(masternodeOutpoint);
if (it == mapLastMasternodeObject.end()) return true;
if (it->second.fStatusOK && !fForce) {
fRateCheckBypassed = true;
return true;
}
// Allow 1 trigger per mn per cycle, with a small fudge factor
double dMaxRate = 2 * 1.1 / double(nSuperblockCycleSeconds);
// BIBLEPAY - Allow more in TestNet since we only have a few Sancs; Allow more in Prod since we have daily GSC superblocks
int iFactor = fProd ? 5 : 20;
dMaxRate = dMaxRate * iFactor;
// Temporary copy to check rate after new timestamp is added
CRateCheckBuffer buffer = it->second.triggerBuffer;
buffer.AddTimestamp(nTimestamp);
double dRate = buffer.GetRate();
if (dRate < dMaxRate) {
return true;
}
LogPrintf("CGovernanceManager::MasternodeRateCheck -- Rate too high: object hash = %s, masternode = %s, object timestamp = %d, rate = %f, max rate = %f\n",
strHash, masternodeOutpoint.ToStringShort(), nTimestamp, dRate, dMaxRate);
if (fUpdateFailStatus) {
it->second.fStatusOK = false;
}
return false;
}
bool CGovernanceManager::ProcessVote(CNode* pfrom, const CGovernanceVote& vote, CGovernanceException& exception, CConnman& connman)
{
ENTER_CRITICAL_SECTION(cs);
uint256 nHashVote = vote.GetHash();
uint256 nHashGovobj = vote.GetParentHash();
if (cmapVoteToObject.HasKey(nHashVote)) {
LogPrint("gobject", "CGovernanceObject::ProcessVote -- skipping known valid vote %s for object %s\n", nHashVote.ToString(), nHashGovobj.ToString());
LEAVE_CRITICAL_SECTION(cs);
return false;
}
if (cmapInvalidVotes.HasKey(nHashVote)) {
std::ostringstream ostr;
ostr << "CGovernanceManager::ProcessVote -- Old invalid vote "
<< ", MN outpoint = " << vote.GetMasternodeOutpoint().ToStringShort()
<< ", governance object hash = " << nHashGovobj.ToString();
LogPrintf("%s\n", ostr.str());
exception = CGovernanceException(ostr.str(), GOVERNANCE_EXCEPTION_PERMANENT_ERROR, 20);
LEAVE_CRITICAL_SECTION(cs);
return false;
}
object_m_it it = mapObjects.find(nHashGovobj);
if (it == mapObjects.end()) {
std::ostringstream ostr;
ostr << "CGovernanceManager::ProcessVote -- Unknown parent object " << nHashGovobj.ToString()
<< ", MN outpoint = " << vote.GetMasternodeOutpoint().ToStringShort();
exception = CGovernanceException(ostr.str(), GOVERNANCE_EXCEPTION_WARNING);
if (cmmapOrphanVotes.Insert(nHashGovobj, vote_time_pair_t(vote, GetAdjustedTime() + GOVERNANCE_ORPHAN_EXPIRATION_TIME))) {
LEAVE_CRITICAL_SECTION(cs);
RequestGovernanceObject(pfrom, nHashGovobj, connman);
LogPrintf("%s\n", ostr.str());
return false;
}
LogPrint("gobject", "%s\n", ostr.str());
LEAVE_CRITICAL_SECTION(cs);
return false;
}
CGovernanceObject& govobj = it->second;
if (govobj.IsSetCachedDelete() || govobj.IsSetExpired()) {
if (fDebugSpam)
LogPrint("gobject", "CGovernanceObject::ProcessVote -- ignoring vote for expired or deleted object, hash = %s\n", nHashGovobj.ToString());
LEAVE_CRITICAL_SECTION(cs);
return false;
}
bool fOk = govobj.ProcessVote(pfrom, vote, exception, connman) && cmapVoteToObject.Insert(nHashVote, &govobj);
LEAVE_CRITICAL_SECTION(cs);
return fOk;
}
void CGovernanceManager::CheckMasternodeOrphanVotes(CConnman& connman)
{
LOCK2(cs_main, cs);
ScopedLockBool guard(cs, fRateChecksEnabled, false);
for (auto& objPair : mapObjects) {
objPair.second.CheckOrphanVotes(connman);
}
}
void CGovernanceManager::CheckMasternodeOrphanObjects(CConnman& connman)
{
LOCK2(cs_main, cs);
int64_t nNow = GetAdjustedTime();
ScopedLockBool guard(cs, fRateChecksEnabled, false);
object_info_m_it it = mapMasternodeOrphanObjects.begin();
while (it != mapMasternodeOrphanObjects.end()) {
object_info_pair_t& pair = it->second;
CGovernanceObject& govobj = pair.first;
if (pair.second.nExpirationTime >= nNow) {
std::string strError;
bool fMasternodeMissing = false;
bool fConfirmationsMissing = false;
bool fIsValid = govobj.IsValidLocally(strError, fMasternodeMissing, fConfirmationsMissing, true);
if (fIsValid) {
AddGovernanceObject(govobj, connman);
} else if (fMasternodeMissing) {
++it;
continue;
}
} else {
// apply node's ban score
Misbehaving(pair.second.idFrom, 20);
}
auto it_count = mapMasternodeOrphanCounter.find(govobj.GetMasternodeOutpoint());
if (--it_count->second == 0)
mapMasternodeOrphanCounter.erase(it_count);
mapMasternodeOrphanObjects.erase(it++);
}
}
void CGovernanceManager::CheckPostponedObjects(CConnman& connman)
{
if (!masternodeSync.IsSynced()) return;
LOCK2(cs_main, cs);
// Check postponed proposals
for (object_m_it it = mapPostponedObjects.begin(); it != mapPostponedObjects.end();) {
const uint256& nHash = it->first;
CGovernanceObject& govobj = it->second;
assert(govobj.GetObjectType() != GOVERNANCE_OBJECT_TRIGGER);
std::string strError;
bool fMissingConfirmations;
if (govobj.IsCollateralValid(strError, fMissingConfirmations)) {
if (govobj.IsValidLocally(strError, false)) {
AddGovernanceObject(govobj, connman);
} else {
LogPrintf("CGovernanceManager::CheckPostponedObjects -- %s invalid\n", nHash.ToString());
}