forked from dashpay/dash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchainlock.cpp
More file actions
486 lines (413 loc) · 16.1 KB
/
chainlock.cpp
File metadata and controls
486 lines (413 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
// Copyright (c) 2019-2025 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.
#include <chainlock/chainlock.h>
#include <chain.h>
#include <chainparams.h>
#include <consensus/validation.h>
#include <node/interface_ui.h>
#include <scheduler.h>
#include <txmempool.h>
#include <util/thread.h>
#include <util/time.h>
#include <util/underlying.h>
#include <validation.h>
#include <validationinterface.h>
#include <instantsend/instantsend.h>
#include <llmq/quorums.h>
#include <masternode/sync.h>
#include <spork.h>
#include <stats/client.h>
// Forward declaration to break dependency over node/transaction.h
namespace node {
CTransactionRef GetTransaction(const CBlockIndex* const block_index, const CTxMemPool* const mempool,
const uint256& hash, const Consensus::Params& consensusParams, uint256& hashBlock);
} // namespace node
using node::GetTransaction;
namespace llmq {
namespace {
static constexpr auto CLEANUP_INTERVAL{30s};
static constexpr auto CLEANUP_SEEN_TIMEOUT{24h};
//! How long to wait for islocks until we consider a block with non-islocked TXs to be safe to sign
static constexpr auto WAIT_FOR_ISLOCK_TIMEOUT{10min};
} // anonymous namespace
bool AreChainLocksEnabled(const CSporkManager& sporkman)
{
return sporkman.IsSporkActive(SPORK_19_CHAINLOCKS_ENABLED);
}
CChainLocksHandler::CChainLocksHandler(CChainState& chainstate, CQuorumManager& _qman, CSigningManager& _sigman,
CSporkManager& sporkman, CTxMemPool& _mempool, const CMasternodeSync& mn_sync) :
m_chainstate{chainstate},
qman{_qman},
spork_manager{sporkman},
mempool{_mempool},
m_mn_sync{mn_sync},
scheduler{std::make_unique<CScheduler>()},
scheduler_thread{
std::make_unique<std::thread>(std::thread(util::TraceThread, "cl-schdlr", [&] { scheduler->serviceQueue(); }))}
{
}
CChainLocksHandler::~CChainLocksHandler()
{
scheduler->stop();
scheduler_thread->join();
}
void CChainLocksHandler::Start(const llmq::CInstantSendManager& isman)
{
if (m_signer) {
m_signer->Start();
}
scheduler->scheduleEvery(
[&]() {
CheckActiveState();
EnforceBestChainLock();
Cleanup();
// regularly retry signing the current chaintip as it might have failed before due to missing islocks
if (m_signer) {
m_signer->TrySignChainTip(isman);
}
},
std::chrono::seconds{5});
}
void CChainLocksHandler::Stop()
{
scheduler->stop();
if (m_signer) {
m_signer->Stop();
}
}
bool CChainLocksHandler::AlreadyHave(const CInv& inv) const
{
LOCK(cs);
return seenChainLocks.count(inv.hash) != 0;
}
bool CChainLocksHandler::GetChainLockByHash(const uint256& hash, chainlock::ChainLockSig& ret) const
{
LOCK(cs);
if (hash != bestChainLockHash) {
// we only propagate the best one and ditch all the old ones
return false;
}
ret = bestChainLock;
return true;
}
chainlock::ChainLockSig CChainLocksHandler::GetBestChainLock() const
{
LOCK(cs);
return bestChainLock;
}
void CChainLocksHandler::UpdateTxFirstSeenMap(const std::unordered_set<uint256, StaticSaltedHasher>& tx, const int64_t& time)
{
AssertLockNotHeld(cs);
LOCK(cs);
for (const auto& txid : tx) {
txFirstSeenTime.emplace(txid, time);
}
}
MessageProcessingResult CChainLocksHandler::ProcessNewChainLock(const NodeId from, const chainlock::ChainLockSig& clsig,
const uint256& hash)
{
CheckActiveState();
{
LOCK(cs);
if (!seenChainLocks.emplace(hash, GetTime<std::chrono::seconds>()).second) {
return {};
}
if (!bestChainLock.IsNull() && clsig.getHeight() <= bestChainLock.getHeight()) {
// no need to process/relay older CLSIGs
return {};
}
}
if (const auto ret = VerifyChainLock(clsig); ret != VerifyRecSigStatus::Valid) {
LogPrint(BCLog::CHAINLOCKS, "CChainLocksHandler::%s -- invalid CLSIG (%s), status=%d peer=%d\n", __func__,
clsig.ToString(), ToUnderlying(ret), from);
if (from != -1) {
return MisbehavingError{10};
}
return {};
}
const CBlockIndex* pindex = WITH_LOCK(::cs_main, return m_chainstate.m_blockman.LookupBlockIndex(clsig.getBlockHash()));
const CInv clsig_inv(MSG_CLSIG, hash);
{
LOCK(cs);
bestChainLockHash = hash;
bestChainLock = clsig;
if (pindex) {
if (pindex->nHeight != clsig.getHeight()) {
// Should not happen, same as the conflict check from above.
LogPrintf("CChainLocksHandler::%s -- height of CLSIG (%s) does not match the specified block's height (%d)\n",
__func__, clsig.ToString(), pindex->nHeight);
// Note: not relaying clsig here
return {};
}
bestChainLockWithKnownBlock = bestChainLock;
bestChainLockBlockIndex = pindex;
} else {
// We don't know the block/header for this CLSIG yet, so bail out for now and when the
// block/header later comes in, we will enforce the correct chain. We still relay further.
return clsig_inv;
}
}
scheduler->scheduleFromNow(
[&]() {
CheckActiveState();
EnforceBestChainLock();
},
std::chrono::seconds{0});
LogPrint(BCLog::CHAINLOCKS, "CChainLocksHandler::%s -- processed new CLSIG (%s), peer=%d\n", __func__,
clsig.ToString(), from);
return clsig_inv;
}
void CChainLocksHandler::AcceptedBlockHeader(gsl::not_null<const CBlockIndex*> pindexNew)
{
LOCK(cs);
if (pindexNew->GetBlockHash() == bestChainLock.getBlockHash()) {
LogPrint(BCLog::CHAINLOCKS, "CChainLocksHandler::%s -- block header %s came in late, updating and enforcing\n",
__func__, pindexNew->GetBlockHash().ToString());
if (bestChainLock.getHeight() != pindexNew->nHeight) {
// Should not happen, same as the conflict check from ProcessNewChainLock.
LogPrintf("CChainLocksHandler::%s -- height of CLSIG (%s) does not match the specified block's height (%d)\n",
__func__, bestChainLock.ToString(), pindexNew->nHeight);
return;
}
// when EnforceBestChainLock is called later, it might end up invalidating other chains but not activating the
// CLSIG locked chain. This happens when only the header is known but the block is still missing yet. The usual
// block processing logic will handle this when the block arrives
bestChainLockWithKnownBlock = bestChainLock;
bestChainLockBlockIndex = pindexNew;
}
}
void CChainLocksHandler::UpdatedBlockTip(const llmq::CInstantSendManager& isman)
{
// don't call TrySignChainTip directly but instead let the scheduler call it. This way we ensure that cs_main is
// never locked and TrySignChainTip is not called twice in parallel. Also avoids recursive calls due to
// EnforceBestChainLock switching chains.
// atomic[If tryLockChainTipScheduled is false, do (set it to true] and schedule signing).
if (bool expected = false; tryLockChainTipScheduled.compare_exchange_strong(expected, true)) {
scheduler->scheduleFromNow(
[&]() {
CheckActiveState();
EnforceBestChainLock();
Cleanup();
if (m_signer) {
m_signer->TrySignChainTip(isman);
}
tryLockChainTipScheduled = false;
},
std::chrono::seconds{0});
}
}
void CChainLocksHandler::CheckActiveState()
{
bool oldIsEnabled = isEnabled;
isEnabled = AreChainLocksEnabled(spork_manager);
if (!oldIsEnabled && isEnabled) {
// ChainLocks got activated just recently, but it's possible that it was already running before, leaving
// us with some stale values which we should not try to enforce anymore (there probably was a good reason
// to disable spork19)
LOCK(cs);
bestChainLockHash = uint256();
bestChainLock = bestChainLockWithKnownBlock = chainlock::ChainLockSig();
bestChainLockBlockIndex = lastNotifyChainLockBlockIndex = nullptr;
}
}
void CChainLocksHandler::TransactionAddedToMempool(const CTransactionRef& tx, int64_t nAcceptTime)
{
if (tx->IsCoinBase() || tx->vin.empty()) {
return;
}
LOCK(cs);
txFirstSeenTime.emplace(tx->GetHash(), nAcceptTime);
}
void CChainLocksHandler::BlockConnected(const std::shared_ptr<const CBlock>& pblock, gsl::not_null<const CBlockIndex*> pindex)
{
if (!m_mn_sync.IsBlockchainSynced()) {
return;
}
// We listen for BlockConnected so that we can collect all TX ids of all included TXs of newly received blocks
int64_t curTime = GetTime<std::chrono::seconds>().count();
{
LOCK(cs);
for (const auto& tx : pblock->vtx) {
if (!tx->IsCoinBase() && !tx->vin.empty()) {
txFirstSeenTime.emplace(tx->GetHash(), curTime);
}
}
}
// We need this information later when we try to sign a new tip, so that we can determine if all included TXs are safe.
if (m_signer) {
m_signer->UpdateBlockHashTxidMap(pindex->GetBlockHash(), pblock->vtx);
}
}
void CChainLocksHandler::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock,
gsl::not_null<const CBlockIndex*> pindexDisconnected)
{
if (m_signer) {
m_signer->EraseFromBlockHashTxidMap(pindexDisconnected->GetBlockHash());
}
}
int32_t CChainLocksHandler::GetBestChainLockHeight() const
{
AssertLockNotHeld(cs);
LOCK(cs);
return bestChainLock.getHeight();
}
bool CChainLocksHandler::IsTxSafeForMining(const uint256& txid) const
{
auto tx_age{0s};
{
LOCK(cs);
auto it = txFirstSeenTime.find(txid);
if (it != txFirstSeenTime.end()) {
tx_age = GetTime<std::chrono::seconds>() - it->second;
}
}
return tx_age >= WAIT_FOR_ISLOCK_TIMEOUT;
}
// WARNING: cs_main and cs should not be held!
// This should also not be called from validation signals, as this might result in recursive calls
void CChainLocksHandler::EnforceBestChainLock()
{
AssertLockNotHeld(cs);
AssertLockNotHeld(cs_main);
std::shared_ptr<chainlock::ChainLockSig> clsig;
const CBlockIndex* pindex;
const CBlockIndex* currentBestChainLockBlockIndex;
{
LOCK(cs);
if (!IsEnabled()) {
return;
}
clsig = std::make_shared<chainlock::ChainLockSig>(bestChainLockWithKnownBlock);
pindex = currentBestChainLockBlockIndex = this->bestChainLockBlockIndex;
if (currentBestChainLockBlockIndex == nullptr) {
// we don't have the header/block, so we can't do anything right now
return;
}
}
BlockValidationState dummy_state;
// Go backwards through the chain referenced by clsig until we find a block that is part of the main chain.
// For each of these blocks, check if there are children that are NOT part of the chain referenced by clsig
// and mark all of them as conflicting.
LogPrint(BCLog::CHAINLOCKS, "CChainLocksHandler::%s -- enforcing block %s via CLSIG (%s)\n", __func__,
pindex->GetBlockHash().ToString(), clsig->ToString());
m_chainstate.EnforceBlock(dummy_state, pindex);
if (/*activateNeeded =*/WITH_LOCK(::cs_main, return m_chainstate.m_chain.Tip()->GetAncestor(
currentBestChainLockBlockIndex->nHeight)) !=
currentBestChainLockBlockIndex) {
if (!m_chainstate.ActivateBestChain(dummy_state)) {
LogPrintf("CChainLocksHandler::%s -- ActivateBestChain failed: %s\n", __func__, dummy_state.ToString());
return;
}
LOCK(::cs_main);
if (m_chainstate.m_chain.Tip()->GetAncestor(currentBestChainLockBlockIndex->nHeight) !=
currentBestChainLockBlockIndex) {
return;
}
}
{
LOCK(cs);
if (lastNotifyChainLockBlockIndex == currentBestChainLockBlockIndex) return;
lastNotifyChainLockBlockIndex = currentBestChainLockBlockIndex;
}
GetMainSignals().NotifyChainLock(currentBestChainLockBlockIndex, clsig, clsig->ToString());
uiInterface.NotifyChainLock(clsig->getBlockHash().ToString(), clsig->getHeight());
::g_stats_client->gauge("chainlocks.blockHeight", clsig->getHeight(), 1.0f);
}
VerifyRecSigStatus CChainLocksHandler::VerifyChainLock(const chainlock::ChainLockSig& clsig) const
{
const auto llmqType = Params().GetConsensus().llmqTypeChainLocks;
const uint256 nRequestId = chainlock::GenSigRequestId(clsig.getHeight());
return llmq::VerifyRecoveredSig(llmqType, m_chainstate.m_chain, qman, clsig.getHeight(), nRequestId,
clsig.getBlockHash(), clsig.getSig());
}
bool CChainLocksHandler::HasChainLock(int nHeight, const uint256& blockHash) const
{
AssertLockNotHeld(cs);
LOCK(cs);
if (!IsEnabled()) {
return false;
}
if (bestChainLockBlockIndex == nullptr) {
return false;
}
if (nHeight > bestChainLockBlockIndex->nHeight) {
return false;
}
if (nHeight == bestChainLockBlockIndex->nHeight) {
return blockHash == bestChainLockBlockIndex->GetBlockHash();
}
const auto* pAncestor = bestChainLockBlockIndex->GetAncestor(nHeight);
return (pAncestor != nullptr) && pAncestor->GetBlockHash() == blockHash;
}
bool CChainLocksHandler::HasConflictingChainLock(int nHeight, const uint256& blockHash) const
{
AssertLockNotHeld(cs);
LOCK(cs);
if (!IsEnabled()) {
return false;
}
if (bestChainLockBlockIndex == nullptr) {
return false;
}
if (nHeight > bestChainLockBlockIndex->nHeight) {
return false;
}
if (nHeight == bestChainLockBlockIndex->nHeight) {
return blockHash != bestChainLockBlockIndex->GetBlockHash();
}
const auto* pAncestor = bestChainLockBlockIndex->GetAncestor(nHeight);
assert(pAncestor);
return pAncestor->GetBlockHash() != blockHash;
}
void CChainLocksHandler::Cleanup()
{
if (!m_mn_sync.IsBlockchainSynced()) {
return;
}
if (GetTime<std::chrono::seconds>() - lastCleanupTime.load() < CLEANUP_INTERVAL) {
return;
}
lastCleanupTime = GetTime<std::chrono::seconds>();
{
LOCK(cs);
for (auto it = seenChainLocks.begin(); it != seenChainLocks.end();) {
if (GetTime<std::chrono::seconds>() - it->second >= CLEANUP_SEEN_TIMEOUT) {
it = seenChainLocks.erase(it);
} else {
++it;
}
}
}
if (m_signer) {
const auto cleanup_txes{m_signer->Cleanup()};
LOCK(cs);
for (const auto& tx : cleanup_txes) {
for (const auto& txid : *tx) {
txFirstSeenTime.erase(txid);
}
}
}
LOCK(::cs_main);
LOCK2(mempool.cs, cs); // need mempool.cs due to GetTransaction calls
for (auto it = txFirstSeenTime.begin(); it != txFirstSeenTime.end();) {
uint256 hashBlock;
if (auto tx = GetTransaction(nullptr, &mempool, it->first, Params().GetConsensus(), hashBlock); !tx) {
// tx has vanished, probably due to conflicts
it = txFirstSeenTime.erase(it);
} else if (!hashBlock.IsNull()) {
const auto* pindex = m_chainstate.m_blockman.LookupBlockIndex(hashBlock);
assert(pindex); // GetTransaction gave us that hashBlock, it should resolve to a valid block index
if (m_chainstate.m_chain.Tip()->GetAncestor(pindex->nHeight) == pindex &&
m_chainstate.m_chain.Height() - pindex->nHeight > chainlock::TX_CONFIRM_THRESHOLD) {
// tx is sufficiently deep, we can stop tracking it
it = txFirstSeenTime.erase(it);
} else {
++it;
}
} else {
++it;
}
}
}
} // namespace llmq