forked from bitcoin/bitcoin
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
governance.h
415 lines (327 loc) · 12.5 KB
/
governance.h
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
// Copyright (c) 2014-2023 The Dash Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_GOVERNANCE_GOVERNANCE_H
#define BITCOIN_GOVERNANCE_GOVERNANCE_H
#include <governance/classes.h>
#include <governance/object.h>
#include <cachemap.h>
#include <cachemultimap.h>
#include <net_types.h>
#include <util/check.h>
#include <optional>
class CBloomFilter;
class CBlockIndex;
class CConnman;
template<typename T>
class CFlatDB;
class CInv;
class PeerManager;
class CDeterministicMNManager;
class CGovernanceManager;
class CGovernanceObject;
class CGovernanceVote;
class CMasternodeMetaMan;
class CMasternodeSync;
class CNetFulfilledRequestManager;
class CSporkManager;
static constexpr int RATE_BUFFER_SIZE = 5;
static constexpr bool DEFAULT_GOVERNANCE_ENABLE{true};
class CDeterministicMNList;
using CDeterministicMNListPtr = std::shared_ptr<CDeterministicMNList>;
class CRateCheckBuffer
{
private:
std::vector<int64_t> vecTimestamps;
int nDataStart;
int nDataEnd;
bool fBufferEmpty;
public:
CRateCheckBuffer() :
vecTimestamps(RATE_BUFFER_SIZE),
nDataStart(0),
nDataEnd(0),
fBufferEmpty(true)
{
}
void AddTimestamp(int64_t nTimestamp)
{
if ((nDataEnd == nDataStart) && !fBufferEmpty) {
// Buffer full, discard 1st element
nDataStart = (nDataStart + 1) % RATE_BUFFER_SIZE;
}
vecTimestamps[nDataEnd] = nTimestamp;
nDataEnd = (nDataEnd + 1) % RATE_BUFFER_SIZE;
fBufferEmpty = false;
}
int64_t GetMinTimestamp()
{
int nIndex = nDataStart;
int64_t nMin = std::numeric_limits<int64_t>::max();
if (fBufferEmpty) {
return nMin;
}
do {
if (vecTimestamps[nIndex] < nMin) {
nMin = vecTimestamps[nIndex];
}
nIndex = (nIndex + 1) % RATE_BUFFER_SIZE;
} while (nIndex != nDataEnd);
return nMin;
}
int64_t GetMaxTimestamp()
{
int nIndex = nDataStart;
int64_t nMax = 0;
if (fBufferEmpty) {
return nMax;
}
do {
if (vecTimestamps[nIndex] > nMax) {
nMax = vecTimestamps[nIndex];
}
nIndex = (nIndex + 1) % RATE_BUFFER_SIZE;
} while (nIndex != nDataEnd);
return nMax;
}
int GetCount() const
{
if (fBufferEmpty) {
return 0;
}
if (nDataEnd > nDataStart) {
return nDataEnd - nDataStart;
}
return RATE_BUFFER_SIZE - nDataStart + nDataEnd;
}
double GetRate()
{
int nCount = GetCount();
if (nCount < RATE_BUFFER_SIZE) {
return 0.0;
}
int64_t nMin = GetMinTimestamp();
int64_t nMax = GetMaxTimestamp();
if (nMin == nMax) {
// multiple objects with the same timestamp => infinite rate
return 1.0e10;
}
return double(nCount) / double(nMax - nMin);
}
SERIALIZE_METHODS(CRateCheckBuffer, obj)
{
READWRITE(obj.vecTimestamps, obj.nDataStart, obj.nDataEnd, obj.fBufferEmpty);
}
};
class GovernanceStore
{
protected:
struct last_object_rec {
explicit last_object_rec(bool fStatusOKIn = true) :
triggerBuffer(),
fStatusOK(fStatusOKIn)
{
}
SERIALIZE_METHODS(last_object_rec, obj)
{
READWRITE(obj.triggerBuffer, obj.fStatusOK);
}
CRateCheckBuffer triggerBuffer;
bool fStatusOK;
};
using object_ref_cm_t = CacheMap<uint256, CGovernanceObject*>;
using txout_m_t = std::map<COutPoint, last_object_rec>;
using vote_cmm_t = CacheMultiMap<uint256, vote_time_pair_t>;
protected:
static constexpr int MAX_CACHE_SIZE = 1000000;
static const std::string SERIALIZATION_VERSION_STRING;
public:
// critical section to protect the inner data structures
mutable RecursiveMutex cs;
protected:
// keep track of the scanning errors
std::map<uint256, CGovernanceObject> mapObjects GUARDED_BY(cs);
// mapErasedGovernanceObjects contains key-value pairs, where
// key - governance object's hash
// value - expiration time for deleted objects
std::map<uint256, int64_t> mapErasedGovernanceObjects;
object_ref_cm_t cmapVoteToObject;
CacheMap<uint256, CGovernanceVote> cmapInvalidVotes;
vote_cmm_t cmmapOrphanVotes;
txout_m_t mapLastMasternodeObject;
// used to check for changed voting keys
CDeterministicMNListPtr lastMNListForVotingKeys;
public:
GovernanceStore();
~GovernanceStore() = default;
template<typename Stream>
void Serialize(Stream &s) const
{
LOCK(cs);
s << SERIALIZATION_VERSION_STRING
<< mapErasedGovernanceObjects
<< cmapInvalidVotes
<< cmmapOrphanVotes
<< mapObjects
<< mapLastMasternodeObject
<< *lastMNListForVotingKeys;
}
template<typename Stream>
void Unserialize(Stream &s)
{
Clear();
LOCK(cs);
std::string strVersion;
s >> strVersion;
if (strVersion != SERIALIZATION_VERSION_STRING) {
return;
}
s >> mapErasedGovernanceObjects
>> cmapInvalidVotes
>> cmmapOrphanVotes
>> mapObjects
>> mapLastMasternodeObject
>> *lastMNListForVotingKeys;
}
void Clear();
std::string ToString() const;
};
//
// Governance Manager : Contains all proposals for the budget
//
class CGovernanceManager : public GovernanceStore
{
friend class CGovernanceObject;
private:
using hash_s_t = std::set<uint256>;
using db_type = CFlatDB<GovernanceStore>;
class ScopedLockBool
{
bool& ref;
bool fPrevValue;
public:
ScopedLockBool(RecursiveMutex& _cs, bool& _ref, bool _value) :
ref(_ref)
{
AssertLockHeld(_cs);
fPrevValue = ref;
ref = _value;
}
~ScopedLockBool()
{
ref = fPrevValue;
}
};
private:
static const int MAX_TIME_FUTURE_DEVIATION;
static const int RELIABLE_PROPAGATION_TIME;
private:
const std::unique_ptr<db_type> m_db;
bool is_valid{false};
CMasternodeMetaMan& m_mn_metaman;
CNetFulfilledRequestManager& m_netfulfilledman;
const std::unique_ptr<CDeterministicMNManager>& m_dmnman;
const std::unique_ptr<CMasternodeSync>& m_mn_sync;
int64_t nTimeLastDiff;
// keep track of current block height
int nCachedBlockHeight;
std::map<uint256, CGovernanceObject> mapPostponedObjects;
hash_s_t setAdditionalRelayObjects;
hash_s_t setRequestedObjects;
hash_s_t setRequestedVotes;
bool fRateChecksEnabled;
std::optional<uint256> votedFundingYesTriggerHash;
std::map<uint256, std::shared_ptr<CSuperblock>> mapTrigger;
public:
explicit CGovernanceManager(CMasternodeMetaMan& mn_metaman, CNetFulfilledRequestManager& netfulfilledman,
const std::unique_ptr<CDeterministicMNManager>& dmnman,
const std::unique_ptr<CMasternodeSync>& mn_sync);
~CGovernanceManager();
bool LoadCache(bool load_cache);
bool IsValid() const { return is_valid; }
/**
* This is called by AlreadyHave in net_processing.cpp as part of the inventory
* retrieval process. Returns true if we want to retrieve the object, otherwise
* false. (Note logic is inverted in AlreadyHave).
*/
bool ConfirmInventoryRequest(const CInv& inv);
void SyncSingleObjVotes(CNode& peer, PeerManager& peerman, const uint256& nProp, const CBloomFilter& filter, CConnman& connman);
PeerMsgRet SyncObjects(CNode& peer, PeerManager& peerman, CConnman& connman) const;
PeerMsgRet ProcessMessage(CNode& peer, CConnman& connman, PeerManager& peerman, std::string_view msg_type, CDataStream& vRecv);
void ResetVotedFundingTrigger();
void DoMaintenance(CConnman& connman);
const CGovernanceObject* FindConstGovernanceObject(const uint256& nHash) const EXCLUSIVE_LOCKS_REQUIRED(cs);
CGovernanceObject* FindGovernanceObject(const uint256& nHash) EXCLUSIVE_LOCKS_REQUIRED(cs);
CGovernanceObject* FindGovernanceObjectByDataHash(const uint256& nDataHash) EXCLUSIVE_LOCKS_REQUIRED(cs);
void DeleteGovernanceObject(const uint256& nHash);
// These commands are only used in RPC
std::vector<CGovernanceVote> GetCurrentVotes(const uint256& nParentHash, const COutPoint& mnCollateralOutpointFilter) const;
void GetAllNewerThan(std::vector<CGovernanceObject>& objs, int64_t nMoreThanTime) const;
void AddGovernanceObject(CGovernanceObject& govobj, PeerManager& peerman, const CNode* pfrom = nullptr);
void CheckAndRemove();
UniValue ToJson() const;
void UpdatedBlockTip(const CBlockIndex* pindex, CConnman& connman, PeerManager& peerman, const CActiveMasternodeManager* const mn_activeman);
int64_t GetLastDiffTime() const { return nTimeLastDiff; }
void UpdateLastDiffTime(int64_t nTimeIn) { nTimeLastDiff = nTimeIn; }
int GetCachedBlockHeight() const { return nCachedBlockHeight; }
// Accessors for thread-safe access to maps
bool HaveObjectForHash(const uint256& nHash) const;
bool HaveVoteForHash(const uint256& nHash) const;
int GetVoteCount() const;
bool SerializeObjectForHash(const uint256& nHash, CDataStream& ss) const;
bool SerializeVoteForHash(const uint256& nHash, CDataStream& ss) const;
void AddPostponedObject(const CGovernanceObject& govobj)
{
LOCK(cs);
mapPostponedObjects.insert(std::make_pair(govobj.GetHash(), govobj));
}
void MasternodeRateUpdate(const CGovernanceObject& govobj);
bool MasternodeRateCheck(const CGovernanceObject& govobj, bool fUpdateFailStatus = false);
bool MasternodeRateCheck(const CGovernanceObject& govobj, bool fUpdateFailStatus, bool fForce, bool& fRateCheckBypassed);
bool ProcessVoteAndRelay(const CGovernanceVote& vote, CGovernanceException& exception, CConnman& connman, PeerManager& peerman);
void CheckPostponedObjects(PeerManager& peerman);
bool AreRateChecksEnabled() const
{
LOCK(cs);
return fRateChecksEnabled;
}
void InitOnLoad();
int RequestGovernanceObjectVotes(CNode& peer, CConnman& connman) const;
int RequestGovernanceObjectVotes(Span<CNode*> vNodesCopy, CConnman& connman) const;
/*
* Trigger Management (formerly CGovernanceTriggerManager)
* - Track governance objects which are triggers
* - After triggers are activated and executed, they can be removed
*/
std::vector<std::shared_ptr<CSuperblock>> GetActiveTriggers();
bool AddNewTrigger(uint256 nHash);
void CleanAndRemoveTriggers();
private:
std::optional<const CSuperblock> CreateSuperblockCandidate(int nHeight) const;
std::optional<const CGovernanceObject> CreateGovernanceTrigger(const std::optional<const CSuperblock>& sb_opt, PeerManager& peerman,
const CActiveMasternodeManager& mn_activeman);
void VoteGovernanceTriggers(const std::optional<const CGovernanceObject>& trigger_opt, CConnman& connman, PeerManager& peerman,
const CActiveMasternodeManager& mn_activeman);
bool VoteFundingTrigger(const uint256& nHash, const vote_outcome_enum_t outcome, CConnman& connman, PeerManager& peerman,
const CActiveMasternodeManager& mn_activeman);
bool HasAlreadyVotedFundingTrigger() const;
void RequestGovernanceObject(CNode* pfrom, const uint256& nHash, CConnman& connman, bool fUseFilter = false) const;
void AddInvalidVote(const CGovernanceVote& vote)
{
cmapInvalidVotes.Insert(vote.GetHash(), vote);
}
bool ProcessVote(CNode* pfrom, const CGovernanceVote& vote, CGovernanceException& exception, CConnman& connman);
/// Called to indicate a requested object has been received
bool AcceptObjectMessage(const uint256& nHash);
/// Called to indicate a requested vote has been received
bool AcceptVoteMessage(const uint256& nHash);
static bool AcceptMessage(const uint256& nHash, hash_s_t& setHash);
void CheckOrphanVotes(CGovernanceObject& govobj, PeerManager& peerman);
void RebuildIndexes();
void AddCachedTriggers();
void RequestOrphanObjects(CConnman& connman);
void CleanOrphanObjects();
void RemoveInvalidVotes();
};
bool AreSuperblocksEnabled(const CSporkManager& sporkman);
#endif // BITCOIN_GOVERNANCE_GOVERNANCE_H