forked from dashpay/dash
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcreditpool.cpp
More file actions
349 lines (300 loc) · 13.7 KB
/
creditpool.cpp
File metadata and controls
349 lines (300 loc) · 13.7 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
// Copyright (c) 2023-2025 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 <evo/creditpool.h>
#include <evo/assetlocktx.h>
#include <evo/cbtx.h>
#include <evo/evodb.h>
#include <evo/specialtx.h>
#include <chain.h>
#include <chainparams.h>
#include <consensus/validation.h>
#include <deploymentstatus.h>
#include <logging.h>
#include <node/blockstorage.h>
#include <validation.h>
#include <algorithm>
#include <exception>
#include <memory>
#include <stack>
using node::BlockManager;
using node::ReadBlockFromDisk;
// Forward declaration to prevent a new circular dependencies through masternode/payments.h
CAmount PlatformShare(const CAmount masternodeReward);
static const std::string DB_CREDITPOOL_SNAPSHOT = "cpm_S";
static bool GetDataFromUnlockTx(const CTransaction& tx, CAmount& toUnlock, uint64_t& index, TxValidationState& state)
{
const auto opt_assetUnlockTx = GetTxPayload<CAssetUnlockPayload>(tx);
if (!opt_assetUnlockTx.has_value()) {
return state.Invalid(TxValidationResult::TX_CONSENSUS, "failed-creditpool-unlock-payload");
}
index = opt_assetUnlockTx->getIndex();
toUnlock = opt_assetUnlockTx->getFee();
for (const CTxOut& txout : tx.vout) {
if (!MoneyRange(txout.nValue)) {
return state.Invalid(TxValidationResult::TX_CONSENSUS, "failed-creditpool-unlock-txout-outofrange");
}
toUnlock += txout.nValue;
}
return true;
}
namespace {
struct CreditPoolDataPerBlock {
CAmount credit_pool{0};
CAmount unlocked{0};
std::unordered_set<uint64_t> indexes;
};
} // anonymous namespace
// it throws exception if anything went wrong
static std::optional<CreditPoolDataPerBlock> GetCreditDataFromBlock(const gsl::not_null<const CBlockIndex*> block_index,
const Consensus::Params& consensusParams)
{
// There's no CbTx before DIP0003 activation
if (!DeploymentActiveAt(*block_index, consensusParams, Consensus::DEPLOYMENT_DIP0003)) {
return std::nullopt;
}
CreditPoolDataPerBlock blockData;
static Mutex cache_mutex;
static Uint256LruHashMap<CreditPoolDataPerBlock> block_data_cache GUARDED_BY(cache_mutex){
static_cast<size_t>(Params().CreditPoolPeriodBlocks()) * 2};
if (LOCK(cache_mutex); block_data_cache.get(block_index->GetBlockHash(), blockData)) {
return blockData;
}
CBlock block;
if (!ReadBlockFromDisk(block, block_index, consensusParams)) {
throw std::runtime_error("failed-getcbforblock-read");
}
if (block.vtx.empty() || block.vtx[0]->vExtraPayload.empty() || !block.vtx[0]->IsSpecialTxVersion()) {
LogPrintf("%s: ERROR: empty CbTx for CreditPool at height=%d\n", __func__, block_index->nHeight);
return std::nullopt;
}
if (const auto opt_cbTx = GetTxPayload<CCbTx>(block.vtx[0]->vExtraPayload); opt_cbTx) {
blockData.credit_pool = opt_cbTx->creditPoolBalance;
} else {
LogPrintf("%s: WARNING: No valid CbTx at height=%d\n", __func__, block_index->nHeight);
return std::nullopt;
}
for (const CTransactionRef& tx : block.vtx) {
if (!tx->IsSpecialTxVersion() || tx->nType != TRANSACTION_ASSET_UNLOCK) continue;
CAmount unlocked{0};
TxValidationState tx_state;
uint64_t index{0};
if (!GetDataFromUnlockTx(*tx, unlocked, index, tx_state)) {
throw std::runtime_error(strprintf("%s: GetDataFromUnlockTx failed: %s", __func__, tx_state.ToString()));
}
blockData.unlocked += unlocked;
blockData.indexes.insert(index);
}
LOCK(cache_mutex);
block_data_cache.insert(block_index->GetBlockHash(), blockData);
return blockData;
}
std::string CCreditPool::ToString() const
{
return strprintf("CCreditPool(locked=%lld, currentLimit=%lld)",
locked, currentLimit);
}
std::optional<CCreditPool> CCreditPoolManager::GetFromCache(const CBlockIndex& block_index)
{
if (!DeploymentActiveAt(block_index, m_chainman.GetConsensus(), Consensus::DEPLOYMENT_V20)) return CCreditPool{};
const uint256 block_hash = block_index.GetBlockHash();
CCreditPool pool;
{
LOCK(cache_mutex);
if (creditPoolCache.get(block_hash, pool)) {
return pool;
}
}
if (block_index.nHeight % DISK_SNAPSHOT_PERIOD == 0) {
if (evoDb.Read(std::make_pair(DB_CREDITPOOL_SNAPSHOT, block_hash), pool)) {
LOCK(cache_mutex);
creditPoolCache.insert(block_hash, pool);
return pool;
}
}
return std::nullopt;
}
void CCreditPoolManager::AddToCache(const uint256& block_hash, int height, const CCreditPool &pool)
{
{
LOCK(cache_mutex);
creditPoolCache.insert(block_hash, pool);
}
if (height % DISK_SNAPSHOT_PERIOD == 0) {
evoDb.Write(std::make_pair(DB_CREDITPOOL_SNAPSHOT, block_hash), pool);
}
}
CCreditPool CCreditPoolManager::ConstructCreditPool(const gsl::not_null<const CBlockIndex*> block_index, CCreditPool prev)
{
std::optional<CreditPoolDataPerBlock> opt_block_data = GetCreditDataFromBlock(block_index, m_chainman.GetConsensus());
if (!opt_block_data) {
// If reading of previous block is not successfully, but
// prev contains credit pool related data, something strange happened
if (prev.locked != 0) {
throw std::runtime_error(strprintf("Failed to create CreditPool but previous block has value"));
}
if (!prev.indexes.IsEmpty()) {
throw std::runtime_error(
strprintf("Failed to create CreditPool but asset unlock transactions already mined"));
}
CCreditPool emptyPool;
AddToCache(block_index->GetBlockHash(), block_index->nHeight, emptyPool);
return emptyPool;
}
const CreditPoolDataPerBlock& blockData{*opt_block_data};
// We use here sliding window with Params().CreditPoolPeriodBlocks to determine
// current limits for asset unlock transactions.
// Indexes should not be duplicated since genesis block, but the Unlock Amount
// of withdrawal transaction is limited only by this window
CRangesSet indexes{std::move(prev.indexes)};
if (std::any_of(blockData.indexes.begin(), blockData.indexes.end(), [&](const uint64_t index) { return !indexes.Add(index); })) {
throw std::runtime_error(strprintf("%s: failed-getcreditpool-index-duplicated", __func__));
}
const CBlockIndex* distant_block_index{
block_index->GetAncestor(block_index->nHeight - m_chainman.GetParams().CreditPoolPeriodBlocks())};
CAmount distantUnlocked{0};
if (distant_block_index) {
if (std::optional<CreditPoolDataPerBlock> distant_block{
GetCreditDataFromBlock(distant_block_index, m_chainman.GetConsensus())};
distant_block) {
distantUnlocked = distant_block->unlocked;
}
}
CAmount currentLimit = blockData.credit_pool;
const CAmount latelyUnlocked = prev.latelyUnlocked + blockData.unlocked - distantUnlocked;
if (DeploymentActiveAt(*block_index, m_chainman, Consensus::DEPLOYMENT_V24)) {
currentLimit = std::max(CAmount(0), std::min(currentLimit, LimitAmountV24 - latelyUnlocked));
} else if (DeploymentActiveAt(*block_index, m_chainman.GetConsensus(), Consensus::DEPLOYMENT_WITHDRAWALS)) {
currentLimit = std::min(currentLimit, LimitAmountV22);
} else {
// Unlock limits in pre-v22 are max(100, min(.10 * assetlockpool, 1000)) inside window
if (currentLimit + latelyUnlocked > LimitAmountLow) {
currentLimit = std::max(LimitAmountLow, blockData.credit_pool / 10) - latelyUnlocked;
if (currentLimit < 0) currentLimit = 0;
}
currentLimit = std::min(currentLimit, LimitAmountHigh - latelyUnlocked);
}
if (currentLimit != 0 || latelyUnlocked > 0 || blockData.credit_pool > 0) {
LogPrint(BCLog::CREDITPOOL, /* Continued */
"CCreditPoolManager: asset unlock limits on height: %d locked: %d.%08d limit: %d.%08d "
"unlocked-in-window: %d.%08d\n",
block_index->nHeight, blockData.credit_pool / COIN, blockData.credit_pool % COIN, currentLimit / COIN,
currentLimit % COIN, latelyUnlocked / COIN, latelyUnlocked % COIN);
}
if (currentLimit < 0) {
throw std::runtime_error(
strprintf("Negative limit for CreditPool: %d.%08d\n", currentLimit / COIN, currentLimit % COIN));
}
CCreditPool pool{blockData.credit_pool, currentLimit, latelyUnlocked, indexes};
AddToCache(block_index->GetBlockHash(), block_index->nHeight, pool);
return pool;
}
CCreditPool CCreditPoolManager::GetCreditPool(const CBlockIndex* block_index)
{
std::stack<gsl::not_null<const CBlockIndex*>> to_calculate;
std::optional<CCreditPool> poolTmp;
while (block_index != nullptr && !(poolTmp = GetFromCache(*block_index)).has_value()) {
to_calculate.push(block_index);
block_index = block_index->pprev;
}
if (block_index == nullptr) poolTmp = CCreditPool{};
while (!to_calculate.empty()) {
poolTmp = ConstructCreditPool(to_calculate.top(), *poolTmp);
to_calculate.pop();
}
return *poolTmp;
}
CCreditPoolManager::CCreditPoolManager(CEvoDB& _evoDb, const ChainstateManager& chainman) :
evoDb{_evoDb},
m_chainman{chainman}
{
}
CCreditPoolManager::~CCreditPoolManager() = default;
CCreditPoolDiff::CCreditPoolDiff(CCreditPool starter, const CBlockIndex* pindexPrev,
const Consensus::Params& consensusParams, const CAmount blockSubsidy) :
pool(std::move(starter)),
pindexPrev(pindexPrev)
{
assert(pindexPrev);
if (DeploymentActiveAfter(pindexPrev, consensusParams, Consensus::DEPLOYMENT_MN_RR)) {
// If credit pool exists, it means v20 is activated
platformReward = PlatformShare(GetMasternodePayment(pindexPrev->nHeight + 1, blockSubsidy, /*fV20Active=*/ true));
}
}
bool CCreditPoolDiff::Lock(const CTransaction& tx, TxValidationState& state)
{
if (const auto opt_assetLockTx = GetTxPayload<CAssetLockPayload>(tx); !opt_assetLockTx) {
return state.Invalid(TxValidationResult::TX_CONSENSUS, "failed-creditpool-lock-payload");
}
for (const CTxOut& txout : tx.vout) {
if (const CScript& script = txout.scriptPubKey; script.empty() || script[0] != OP_RETURN) continue;
sessionLocked += txout.nValue;
return true;
}
return state.Invalid(TxValidationResult::TX_CONSENSUS, "failed-creditpool-lock-invalid");
}
bool CCreditPoolDiff::Unlock(const CTransaction& tx, TxValidationState& state)
{
uint64_t index{0};
CAmount toUnlock{0};
if (!GetDataFromUnlockTx(tx, toUnlock, index, state)) {
// state is set up inside GetDataFromUnlockTx
return false;
}
if (sessionUnlocked + toUnlock > pool.currentLimit) {
return state.Invalid(TxValidationResult::TX_CONSENSUS, "failed-creditpool-unlock-too-much");
}
if (pool.indexes.Contains(index) || newIndexes.count(index)) {
return state.Invalid(TxValidationResult::TX_CONSENSUS, "failed-creditpool-unlock-duplicated-index");
}
newIndexes.insert(index);
sessionUnlocked += toUnlock;
return true;
}
bool CCreditPoolDiff::ProcessLockUnlockTransaction(const BlockManager& blockman, const llmq::CQuorumManager& qman, const CTransaction& tx, TxValidationState& state)
{
if (!tx.IsSpecialTxVersion()) return true;
if (tx.nType != TRANSACTION_ASSET_LOCK && tx.nType != TRANSACTION_ASSET_UNLOCK) return true;
if (!CheckAssetLockUnlockTx(blockman, qman, tx, pindexPrev, pool.indexes, state)) {
// pass the state returned by the function above
return false;
}
try {
switch (tx.nType) {
case TRANSACTION_ASSET_LOCK:
return Lock(tx, state);
case TRANSACTION_ASSET_UNLOCK:
return Unlock(tx, state);
default:
return true;
}
} catch (const std::exception& e) {
LogPrintf("%s -- failed: %s\n", __func__, e.what());
return state.Invalid(TxValidationResult::TX_CONSENSUS, "failed-procassetlocksinblock");
}
}
std::optional<CCreditPoolDiff> GetCreditPoolDiffForBlock(CCreditPoolManager& cpoolman, const BlockManager& blockman, const llmq::CQuorumManager& qman,
const CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams,
const CAmount blockSubsidy, BlockValidationState& state)
{
try {
const CCreditPool creditPool = cpoolman.GetCreditPool(pindexPrev);
LogPrint(BCLog::CREDITPOOL, "%s: CCreditPool is %s\n", __func__, creditPool.ToString());
CCreditPoolDiff creditPoolDiff(creditPool, pindexPrev, consensusParams, blockSubsidy);
for (size_t i = 1; i < block.vtx.size(); ++i) {
const auto& tx = *block.vtx[i];
TxValidationState tx_state;
if (!creditPoolDiff.ProcessLockUnlockTransaction(blockman, qman, tx, tx_state)) {
assert(tx_state.GetResult() == TxValidationResult::TX_CONSENSUS);
state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, tx_state.GetRejectReason(),
strprintf("Process Lock/Unlock Transaction failed at Credit Pool (tx hash %s) %s", tx.GetHash().ToString(), tx_state.GetDebugMessage()));
return std::nullopt;
}
}
return creditPoolDiff;
} catch (const std::exception& e) {
LogPrintf("%s -- failed: %s\n", __func__, e.what());
state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "failed-getcreditpooldiff");
return std::nullopt;
}
}