From d421e0db23ae99c0d27928a5d4d214023b9fb4ca Mon Sep 17 00:00:00 2001 From: minuszka Date: Mon, 19 Oct 2026 12:43:21 +0200 Subject: [PATCH] net: bound pending locks and peer-controlled message intake Backport the upstream Dash resource limits for InstantSend queues, governance vote signatures, CoinJoin messages and socket receive handling. Keep verified local locks ahead of pending verification work at capacity and avoid evicting another entry when the lock is already queued. Apply the upstream DSTX peer-accounting scores and add boundary, serialization and peer-accounting regressions. Upstream Dash commits: 0a681dbb and cb6afcbe. Upstream PRs: dashpay/dash#7440, dashpay/dash#7419, dashpay/dash#7347. Original upstream author: pasta --- src/Makefile.test.include | 3 + src/coinjoin/coinjoin.cpp | 2 +- src/coinjoin/coinjoin.h | 34 +- src/coinjoin/server.cpp | 65 +++- src/coinjoin/server.h | 2 +- src/consensus/consensus.h | 2 +- src/governance/governance.cpp | 6 +- src/governance/vote.cpp | 4 + src/governance/vote.h | 17 +- src/llmq/instantsend.cpp | 33 +- src/llmq/instantsend.h | 6 + src/net.cpp | 12 +- src/net.h | 4 + src/net_processing.cpp | 45 ++- src/test/coinjoin_inouts_tests.cpp | 362 +++++++++++++++++++++ src/test/governance_vote_wire_tests.cpp | 96 ++++++ src/test/instantsend_queue_tests.cpp | 167 ++++++++++ src/test/llmq_instantsend_tests.cpp | 14 + src/test/net_tests.cpp | 37 +++ test/functional/p2p_dstx.py | 115 +++++++ test/functional/test_framework/messages.py | 47 +++ test/functional/test_runner.py | 1 + 22 files changed, 1036 insertions(+), 38 deletions(-) create mode 100644 src/test/coinjoin_inouts_tests.cpp create mode 100644 src/test/governance_vote_wire_tests.cpp create mode 100644 src/test/instantsend_queue_tests.cpp create mode 100755 test/functional/p2p_dstx.py diff --git a/src/Makefile.test.include b/src/Makefile.test.include index 86b73725d7..07215c1fce 100644 --- a/src/Makefile.test.include +++ b/src/Makefile.test.include @@ -145,6 +145,8 @@ BITCOIN_TESTS =\ test/governance_budget_tests.cpp \ test/governance_validators_tests.cpp \ test/governance_vote_sync_tests.cpp \ + test/governance_vote_wire_tests.cpp \ + test/coinjoin_inouts_tests.cpp \ test/hash_tests.cpp \ test/i2p_tests.cpp \ test/interfaces_tests.cpp \ @@ -164,6 +166,7 @@ BITCOIN_TESTS =\ test/llmq_chainlocks_tests.cpp \ test/llmq_formation_end_tests.cpp \ test/llmq_instantsend_tests.cpp \ + test/instantsend_queue_tests.cpp \ test/llmq_invalid_type_tests.cpp \ test/llmq_quorum_base_tests.cpp \ test/logging_tests.cpp \ diff --git a/src/coinjoin/coinjoin.cpp b/src/coinjoin/coinjoin.cpp index 2e226296b9..54740e3a0a 100644 --- a/src/coinjoin/coinjoin.cpp +++ b/src/coinjoin/coinjoin.cpp @@ -129,7 +129,7 @@ bool CCoinJoinBroadcastTx::IsValidStructure() const if (tx->vin.size() < size_t(CoinJoin::GetMinPoolParticipants())) { return false; } - if (tx->vin.size() > CoinJoin::GetMaxPoolParticipants() * COINJOIN_ENTRY_MAX_SIZE) { + if (tx->vin.size() > CoinJoin::GetMaxPoolInputOutputCount()) { return false; } return ranges::all_of(tx->vout, [] (const auto& txOut){ diff --git a/src/coinjoin/coinjoin.h b/src/coinjoin/coinjoin.h index 69b7dd75e7..7a8d24ed04 100644 --- a/src/coinjoin/coinjoin.h +++ b/src/coinjoin/coinjoin.h @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -46,6 +47,15 @@ static constexpr int COINJOIN_SIGNING_TIMEOUT = 15; static constexpr size_t COINJOIN_ENTRY_MAX_SIZE = 9; +namespace CoinJoin { +/// Get the minimum/maximum number of participants for the pool +int GetMinPoolParticipants(); +int GetMaxPoolParticipants(); + +/// Maximum number of inputs or outputs across a full pool +inline size_t GetMaxPoolInputOutputCount() { return size_t(GetMaxPoolParticipants()) * COINJOIN_ENTRY_MAX_SIZE; } +} // namespace CoinJoin + // pool responses enum PoolMessage : int32_t { ERR_ALREADY_HAVE, @@ -164,9 +174,25 @@ class CCoinJoinEntry { } - SERIALIZE_METHODS(CCoinJoinEntry, obj) + template + void Serialize(Stream& s) const + { + s << vecTxDSIn << txCollateral << vecTxOut; + } + + template + void Unserialize(Stream& s) { - READWRITE(obj.vecTxDSIn, obj.txCollateral, obj.vecTxOut); + const size_t max_count{CoinJoin::GetMaxPoolInputOutputCount()}; + if (!UnserializeVectorWithMaxSize(s, vecTxDSIn, max_count)) { + throw std::ios_base::failure("CCoinJoinEntry::vecTxDSIn size too large"); + } + + s >> txCollateral; + + if (!UnserializeVectorWithMaxSize(s, vecTxOut, max_count)) { + throw std::ios_base::failure("CCoinJoinEntry::vecTxOut size too large"); + } } bool AddScriptSig(const CTxIn& txin); @@ -361,10 +387,6 @@ namespace CoinJoin { bilingual_str GetMessageByID(PoolMessage nMessageID); - /// Get the minimum/maximum number of participants for the pool - int GetMinPoolParticipants(); - int GetMaxPoolParticipants(); - constexpr CAmount GetMaxPoolAmount() { return COINJOIN_ENTRY_MAX_SIZE * vecStandardDenominations.front(); } /// If the collateral is valid given by a client diff --git a/src/coinjoin/server.cpp b/src/coinjoin/server.cpp index 181060d77c..73829d2b3f 100644 --- a/src/coinjoin/server.cpp +++ b/src/coinjoin/server.cpp @@ -37,7 +37,7 @@ PeerMsgRet CCoinJoinServer::ProcessMessage(CNode& peer, std::string_view msg_typ } else if (msg_type == NetMsgType::DSVIN) { ProcessDSVIN(peer, vRecv); } else if (msg_type == NetMsgType::DSSIGNFINALTX) { - ProcessDSSIGNFINALTX(vRecv); + ProcessDSSIGNFINALTX(peer, vRecv); } return {}; } @@ -218,10 +218,40 @@ void CCoinJoinServer::ProcessDSVIN(CNode& peer, CDataStream& vRecv) } } -void CCoinJoinServer::ProcessDSSIGNFINALTX(CDataStream& vRecv) +void CCoinJoinServer::ProcessDSSIGNFINALTX(CNode& peer, CDataStream& vRecv) { + // Only accept signatures while we are actually collecting them, and only + // from peers that are active participants in this session. Otherwise a + // stray or unauthenticated peer could abort the session for everyone. + if (nState != POOL_STATE_SIGNING) { + LogPrint(BCLog::COINJOIN, "DSSIGNFINALTX -- wrong state, nState=%d, peer=%d\n", + nState.load(), peer.GetId()); + PushStatus(peer, STATUS_REJECTED, ERR_SESSION); + return; + } + { + LOCK(cs_coinjoin); + const bool is_participant = ranges::any_of( + vecEntries, [&peer](const auto& entry) { return entry.addr == peer.addr; }); + if (!is_participant) { + LogPrint(BCLog::COINJOIN, "DSSIGNFINALTX -- ignoring message from non-participant peer=%d\n", + peer.GetId()); + PushStatus(peer, STATUS_REJECTED, ERR_INVALID_INPUT); + return; + } + } + + const size_t max_txins{CoinJoin::GetMaxPoolInputOutputCount()}; std::vector vecTxIn; - vRecv >> vecTxIn; + // Reject an over-cap count through this peer-local ERR_MAXIMUM path before a + // single CTxIn is decoded or allocated. A count above the generic MAX_SIZE cap + // is malformed and throws from ReadCompactSize, as it does for any other message. + if (!UnserializeVectorWithMaxSize(vRecv, vecTxIn, max_txins)) { + LogPrint(BCLog::COINJOIN, "DSSIGNFINALTX -- too many inputs. max=%d, peer=%d\n", + static_cast(max_txins), peer.GetId()); + PushStatus(peer, STATUS_REJECTED, ERR_MAXIMUM); + return; + } LogPrint(BCLog::COINJOIN, "DSSIGNFINALTX -- vecTxIn.size() %s\n", vecTxIn.size()); @@ -583,16 +613,31 @@ bool CCoinJoinServer::AddEntry(const CCoinJoinEntry& entry, PoolMessage& nMessag return false; } - if (!CoinJoin::IsCollateralValid(m_chainman, m_isman, mempool, *entry.txCollateral)) { - LogPrint(BCLog::COINJOIN, "CCoinJoinServer::%s -- ERROR: collateral not valid!\n", __func__); - nMessageIDRet = ERR_INVALID_COLLATERAL; + if (entry.vecTxDSIn.size() > COINJOIN_ENTRY_MAX_SIZE || entry.vecTxOut.size() > COINJOIN_ENTRY_MAX_SIZE) { + LogPrint(BCLog::COINJOIN, /* Continued */ + "CCoinJoinServer::%s -- ERROR: too many inputs or outputs! inputs=%s/%s, outputs=%s/%s\n", __func__, + entry.vecTxDSIn.size(), COINJOIN_ENTRY_MAX_SIZE, entry.vecTxOut.size(), COINJOIN_ENTRY_MAX_SIZE); + nMessageIDRet = ERR_MAXIMUM; + + CTransactionRef txCollateralToConsume; + { + LOCK(cs_coinjoin); + const auto it = ranges::find_if(vecSessionCollaterals, [&entry](const auto& txCollateral) { + return *entry.txCollateral == *txCollateral; + }); + if (it != vecSessionCollaterals.end()) { + txCollateralToConsume = *it; + } + } + if (txCollateralToConsume) { + ConsumeCollateral(txCollateralToConsume); + } return false; } - if (entry.vecTxDSIn.size() > COINJOIN_ENTRY_MAX_SIZE) { - LogPrint(BCLog::COINJOIN, "CCoinJoinServer::%s -- ERROR: too many inputs! %d/%d\n", __func__, entry.vecTxDSIn.size(), COINJOIN_ENTRY_MAX_SIZE); - nMessageIDRet = ERR_MAXIMUM; - ConsumeCollateral(entry.txCollateral); + if (!CoinJoin::IsCollateralValid(m_chainman, m_isman, mempool, *entry.txCollateral)) { + LogPrint(BCLog::COINJOIN, "CCoinJoinServer::%s -- ERROR: collateral not valid!\n", __func__); + nMessageIDRet = ERR_INVALID_COLLATERAL; return false; } diff --git a/src/coinjoin/server.h b/src/coinjoin/server.h index c0611fc4c8..f042e41deb 100644 --- a/src/coinjoin/server.h +++ b/src/coinjoin/server.h @@ -87,7 +87,7 @@ class CCoinJoinServer : public CCoinJoinBaseSession, public CCoinJoinBaseManager void ProcessDSACCEPT(CNode& peer, CDataStream& vRecv) EXCLUSIVE_LOCKS_REQUIRED(!cs_vecqueue); PeerMsgRet ProcessDSQUEUE(const CNode& peer, CDataStream& vRecv) EXCLUSIVE_LOCKS_REQUIRED(!cs_vecqueue); void ProcessDSVIN(CNode& peer, CDataStream& vRecv) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); - void ProcessDSSIGNFINALTX(CDataStream& vRecv) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); + void ProcessDSSIGNFINALTX(CNode& peer, CDataStream& vRecv) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); void SetNull() override EXCLUSIVE_LOCKS_REQUIRED(cs_coinjoin); diff --git a/src/consensus/consensus.h b/src/consensus/consensus.h index fe8491ac36..a4ae9b352b 100644 --- a/src/consensus/consensus.h +++ b/src/consensus/consensus.h @@ -9,7 +9,7 @@ /** The maximum allowed size for a serialized block, in bytes (network rule) */ static const unsigned int MAX_LEGACY_BLOCK_SIZE = 1000000; static const unsigned int MAX_DIP0001_BLOCK_SIZE = 2000000; -inline unsigned int MaxBlockSize(bool fDIP0001Active = true) +constexpr unsigned int MaxBlockSize(bool fDIP0001Active = true) { return fDIP0001Active ? MAX_DIP0001_BLOCK_SIZE : MAX_LEGACY_BLOCK_SIZE; } diff --git a/src/governance/governance.cpp b/src/governance/governance.cpp index 5fa4727754..69b6743ff5 100644 --- a/src/governance/governance.cpp +++ b/src/governance/governance.cpp @@ -326,7 +326,11 @@ PeerMsgRet CGovernanceManager::ProcessMessage(CNode& peer, CConnman& connman, Pe // A NEW GOVERNANCE OBJECT VOTE HAS ARRIVED else if (msg_type == NetMsgType::MNGOVERNANCEOBJECTVOTE) { CGovernanceVote vote; - vRecv >> vote; + try { + vRecv >> vote; + } catch (const std::ios_base::failure&) { + return tl::unexpected{100}; + } uint256 nHash = vote.GetHash(); WITH_LOCK(::cs_main, peerman.EraseObjectRequest(peer.GetId(), CInv(MSG_GOVERNANCE_OBJECT_VOTE, nHash))); diff --git a/src/governance/vote.cpp b/src/governance/vote.cpp index 4dec352f59..f5b7a6cbdd 100644 --- a/src/governance/vote.cpp +++ b/src/governance/vote.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -19,6 +20,9 @@ #include +static_assert(CGovernanceVote::COMPACT_SIG_SIZE == CPubKey::COMPACT_SIGNATURE_SIZE); +static_assert(CGovernanceVote::BLS_SIG_SIZE == CBLSSignature::SerSize); + namespace { //! Hash the inputs that determine the verification result. Dropping any of them //! breaks the memo; see CGovernanceVote::SignatureMemo. diff --git a/src/governance/vote.h b/src/governance/vote.h index 75f59e88c0..d8e6576611 100644 --- a/src/governance/vote.h +++ b/src/governance/vote.h @@ -6,6 +6,7 @@ #define BITCOIN_GOVERNANCE_VOTE_H #include +#include #include #include @@ -65,6 +66,10 @@ class CGovernanceVote friend bool operator<(const CGovernanceVote& vote1, const CGovernanceVote& vote2); +public: + static constexpr size_t COMPACT_SIG_SIZE = 65; + static constexpr size_t BLS_SIG_SIZE = 96; + private: COutPoint masternodeOutpoint; uint256 nParentHash; @@ -175,7 +180,17 @@ class CGovernanceVote { READWRITE(obj.masternodeOutpoint, obj.nParentHash, obj.nVoteOutcome, obj.nVoteSignal, obj.nTime); if (!(s.GetType() & SER_GETHASH)) { - READWRITE(obj.vchSig); + // Network reads: cap the signature vector before allocation and require + // one of the two legitimate encodings. Other paths (disk, hash, write) + // keep the unbounded default. + if (ser_action.ForRead() && (s.GetType() & SER_NETWORK)) { + READWRITE(LIMITED_VECTOR(obj.vchSig, BLS_SIG_SIZE)); + if (obj.vchSig.size() != COMPACT_SIG_SIZE && obj.vchSig.size() != BLS_SIG_SIZE) { + throw std::ios_base::failure("bad governance vote signature size"); + } + } else { + READWRITE(obj.vchSig); + } } SER_READ(obj, obj.UpdateHash()); } diff --git a/src/llmq/instantsend.cpp b/src/llmq/instantsend.cpp index c240128780..bab626f649 100644 --- a/src/llmq/instantsend.cpp +++ b/src/llmq/instantsend.cpp @@ -734,6 +734,11 @@ void CInstantSendManager::HandleNewInstantSendLockRecoveredSig(const llmq::CReco return; } LOCK(cs_pendingLocks); + // A locally recovered lock is already verified and takes priority over + // a pending verification, just like a lock leaving the no-tx queue. + if (!pendingInstantSendLocks.count(hash) && pendingInstantSendLocks.size() >= MAX_PENDING_INSTANTSEND_LOCKS) { + pendingInstantSendLocks.erase(pendingInstantSendLocks.begin()); + } pendingInstantSendLocks.emplace(hash, std::make_pair(-1, islock)); } @@ -751,6 +756,10 @@ PeerMsgRet CInstantSendManager::ProcessMessage(const CNode& pfrom, PeerManager& PeerMsgRet CInstantSendManager::ProcessMessageInstantSendLock(const CNode& pfrom, PeerManager& peerman, const llmq::CInstantSendLockPtr& islock) { + // Apply the input ceiling before hashing or walking the input set. + if (islock->inputs.size() > CInstantSendLock::MAX_INPUTS) { + return tl::unexpected{100}; + } auto hash = ::SerializeHash(*islock); WITH_LOCK(::cs_main, peerman.EraseObjectRequest(pfrom.GetId(), CInv(MSG_ISDLOCK, hash))); @@ -785,6 +794,10 @@ PeerMsgRet CInstantSendManager::ProcessMessageInstantSendLock(const CNode& pfrom islock->txid.ToString(), hash.ToString(), pfrom.GetId()); LOCK(cs_pendingLocks); + if (pendingInstantSendLocks.size() >= MAX_PENDING_INSTANTSEND_LOCKS) { + LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- pending islock queue full, dropping islock=%s\n", __func__, hash.ToString()); + return {}; + } pendingInstantSendLocks.emplace(hash, std::make_pair(pfrom.GetId(), islock)); return {}; } @@ -795,7 +808,7 @@ PeerMsgRet CInstantSendManager::ProcessMessageInstantSendLock(const CNode& pfrom */ bool CInstantSendLock::TriviallyValid() const { - if (txid.IsNull() || inputs.empty()) { + if (txid.IsNull() || inputs.empty() || inputs.size() > MAX_INPUTS) { return false; } @@ -1079,7 +1092,11 @@ void CInstantSendManager::ProcessInstantSendLock(NodeId from, PeerManager& peerm if (tx == nullptr) { // put it in a separate pending map and try again later LOCK(cs_pendingLocks); - pendingNoTxInstantSendLocks.try_emplace(hash, std::make_pair(from, islock)); + if (pendingNoTxInstantSendLocks.size() < MAX_PENDING_INSTANTSEND_LOCKS) { + pendingNoTxInstantSendLocks.try_emplace(hash, std::make_pair(from, islock)); + } else { + LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- no-tx islock queue full, dropping islock=%s\n", __func__, hash.ToString()); + } } else { db.WriteNewInstantSendLock(hash, *islock); if (pindexMined) { @@ -1128,6 +1145,12 @@ void CInstantSendManager::TransactionAddedToMempool(PeerManager& peerman, const auto it = pendingNoTxInstantSendLocks.begin(); while (it != pendingNoTxInstantSendLocks.end()) { if (it->second.second->txid == tx->GetHash()) { + // A verified lock whose transaction arrived takes priority over a + // pending verification. Do not strand it in the no-tx queue. + if (!pendingInstantSendLocks.count(it->first) && + pendingInstantSendLocks.size() >= MAX_PENDING_INSTANTSEND_LOCKS) { + pendingInstantSendLocks.erase(pendingInstantSendLocks.begin()); + } // we received an islock earlier LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s, islock=%s\n", __func__, tx->GetHash().ToString(), it->first.ToString()); @@ -1219,6 +1242,12 @@ void CInstantSendManager::AddNonLockedTx(const CTransactionRef& tx, const CBlock auto it = pendingNoTxInstantSendLocks.begin(); while (it != pendingNoTxInstantSendLocks.end()) { if (it->second.second->txid == tx->GetHash()) { + // A verified lock whose transaction arrived takes priority over a + // pending verification. Do not strand it in the no-tx queue. + if (!pendingInstantSendLocks.count(it->first) && + pendingInstantSendLocks.size() >= MAX_PENDING_INSTANTSEND_LOCKS) { + pendingInstantSendLocks.erase(pendingInstantSendLocks.begin()); + } // we received an islock earlier, let's put it back into pending and verify/lock LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s, islock=%s\n", __func__, tx->GetHash().ToString(), it->first.ToString()); diff --git a/src/llmq/instantsend.h b/src/llmq/instantsend.h index 5b33e6bdb7..eef5ff5308 100644 --- a/src/llmq/instantsend.h +++ b/src/llmq/instantsend.h @@ -7,6 +7,7 @@ #include +#include #include #include #include @@ -38,6 +39,8 @@ class CSigSharesManager; struct CInstantSendLock { static constexpr uint8_t CURRENT_VERSION{1}; + // A valid transaction fits in a block and each serialized input needs at least 41 bytes. + static constexpr size_t MAX_INPUTS{MaxBlockSize() / 41}; uint8_t nVersion{CURRENT_VERSION}; std::vector inputs; @@ -195,6 +198,7 @@ class CInstantSendDb class CInstantSendManager : public CRecoveredSigsListener { + friend struct InstantSendQueueTest; private: CInstantSendDb db; @@ -231,6 +235,8 @@ class CInstantSendManager : public CRecoveredSigsListener // maps from txid to the in-progress islock std::unordered_map txToCreatingInstantSendLocks GUARDED_BY(cs_creating); + // Bound both unverified locks and verified locks whose transaction has not arrived. + static constexpr size_t MAX_PENDING_INSTANTSEND_LOCKS{1024}; mutable Mutex cs_pendingLocks; // Incoming and not verified yet std::unordered_map, StaticSaltedHasher> pendingInstantSendLocks GUARDED_BY(cs_pendingLocks); diff --git a/src/net.cpp b/src/net.cpp index 67fded9a44..43c6d50442 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -2683,6 +2683,16 @@ void CConnman::SocketEvents(const std::vector& nodes, } } +bool HasUnpausedReceivableNode(const std::unordered_map& receivable_nodes) +{ + for (const auto& entry : receivable_nodes) { + if (!entry.second->fPauseRecv) { + return true; + } + } + return false; +} + void CConnman::SocketHandler(CMasternodeSync& mn_sync) { AssertLockNotHeld(m_total_bytes_sent_mutex); @@ -2694,7 +2704,7 @@ void CConnman::SocketHandler(CMasternodeSync& mn_sync) bool only_poll = [this]() { // Check if we have work to do and thus should avoid waiting for events LOCK2(m_nodes_mutex, cs_sendable_receivable_nodes); - if (!mapReceivableNodes.empty()) { + if (HasUnpausedReceivableNode(mapReceivableNodes)) { return true; } for (const auto& p : mapSendableNodes) { diff --git a/src/net.h b/src/net.h index b6605308a8..8bc91e44f9 100644 --- a/src/net.h +++ b/src/net.h @@ -48,6 +48,7 @@ #include #include #include +#include #include #include @@ -1183,6 +1184,9 @@ class NetEventsInterface ~NetEventsInterface() = default; }; +// Receive-paused nodes must not keep the socket loop in its zero-timeout poll path. +bool HasUnpausedReceivableNode(const std::unordered_map& receivable_nodes); + class CConnman { friend class CNode; diff --git a/src/net_processing.cpp b/src/net_processing.cpp index 7163c798ee..7d84d54c33 100644 --- a/src/net_processing.cpp +++ b/src/net_processing.cpp @@ -3756,18 +3756,31 @@ void PeerManagerImpl::ProcessGetCFCheckPt(CNode& node, Peer& peer, CDataStream& m_connman.PushMessage(&node, std::move(msg)); } -std::pair static ValidateDSTX(CDeterministicMNManager& dmnman, CDSTXManager& dstxman, ChainstateManager& chainman, - CMasternodeMetaMan& mn_metaman, CTxMemPool& mempool, CCoinJoinBroadcastTx& dstx, uint256 hashTx) +// Misbehavior penalty to apply to the relaying peer; NONE means no penalty. +enum class DSTXValidationScore : int { + NONE = 0, + UNKNOWN_MASTERNODE = 1, + INVALID = 10, +}; + +// do_return signals the caller to stop further processing of the DSTX. +struct DSTXValidationResult { + DSTXValidationScore score; + bool do_return; +}; + +static DSTXValidationResult ValidateDSTX(CDeterministicMNManager& dmnman, CDSTXManager& dstxman, ChainstateManager& chainman, + CMasternodeMetaMan& mn_metaman, CTxMemPool& mempool, CCoinJoinBroadcastTx& dstx, uint256 hashTx) { assert(mn_metaman.IsValid()); if (!dstx.IsValidStructure()) { LogPrint(BCLog::COINJOIN, "DSTX -- Invalid DSTX structure: %s\n", hashTx.ToString()); - return {false, true}; + return {DSTXValidationScore::INVALID, true}; } if (dstxman.GetDSTX(hashTx)) { LogPrint(BCLog::COINJOIN, "DSTX -- Already have %s, skipping...\n", hashTx.ToString()); - return {true, true}; // not an error + return {DSTXValidationScore::NONE, true}; // not an error } const CBlockIndex* pindex{nullptr}; @@ -3800,26 +3813,29 @@ std::pair static ValidateDSTX(CDeterministicMN if (!dmn) { LogPrint(BCLog::COINJOIN, "DSTX -- Can't find masternode %s to verify %s\n", dstx.masternodeOutpoint.ToStringShort(), hashTx.ToString()); - return {false, true}; + // We can't verify the signature here, so apply only a small penalty. + // The MN may have been removed very recently, but a peer flooding us with + // unverifiable DSTX-es should still eventually be discouraged. + return {DSTXValidationScore::UNKNOWN_MASTERNODE, true}; } if (!mn_metaman.GetMetaInfo(dmn->proTxHash)->IsValidForMixingTxes()) { LogPrint(BCLog::COINJOIN, "DSTX -- Masternode %s is sending too many transactions %s\n", dstx.masternodeOutpoint.ToStringShort(), hashTx.ToString()); - return {true, true}; + return {DSTXValidationScore::NONE, true}; // TODO: Not an error? Could it be that someone is relaying old DSTXes // we have no idea about (e.g we were offline)? How to handle them? } if (!dstx.CheckSignature(dmn->pdmnState->pubKeyOperator.Get())) { LogPrint(BCLog::COINJOIN, "DSTX -- CheckSignature() failed for %s\n", hashTx.ToString()); - return {false, true}; + return {DSTXValidationScore::INVALID, true}; } LogPrint(BCLog::COINJOIN, "DSTX -- Got Masternode transaction %s\n", hashTx.ToString()); mempool.PrioritiseTransaction(hashTx, 0.1*COIN); mn_metaman.DisallowMixing(dmn->proTxHash); - return {true, false}; + return {DSTXValidationScore::NONE, false}; } void PeerManagerImpl::ProcessBlock(CNode& node, const std::shared_ptr& block, bool force_processing) @@ -4866,12 +4882,13 @@ void PeerManagerImpl::ProcessMessage( // Process custom logic, no matter if tx will be accepted to mempool later or not if (nInvType == MSG_DSTX) { - // Validate DSTX and return bRet if we need to return from here - uint256 hashTx = tx.GetHash(); - const auto& [bRet, bDoReturn] = ValidateDSTX(*m_dmnman, *(m_cj_ctx->dstxman), m_chainman, m_mn_metaman, m_mempool, dstx, hashTx); - if (bDoReturn) { - return; - } + const auto result = ValidateDSTX(*m_dmnman, *(m_cj_ctx->dstxman), m_chainman, m_mn_metaman, m_mempool, dstx, tx.GetHash()); + if (result.do_return) { + if (result.score != DSTXValidationScore::NONE) { + Misbehaving(pfrom.GetId(), static_cast(result.score), "invalid dstx"); + } + return; + } } LOCK2(cs_main, g_cs_orphans); diff --git a/src/test/coinjoin_inouts_tests.cpp b/src/test/coinjoin_inouts_tests.cpp new file mode 100644 index 0000000000..c86f94481c --- /dev/null +++ b/src/test/coinjoin_inouts_tests.cpp @@ -0,0 +1,362 @@ +// Copyright (c) 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include