From 3fdd82dc8b0947bff9917b70861d4d3c9378d487 Mon Sep 17 00:00:00 2001 From: pasta Date: Sat, 3 Oct 2026 19:28:46 -0500 Subject: [PATCH 1/6] fix(coinjoin): decide server state transitions under cs_coinjoin CheckPool() runs on both the scheduler thread and the message-handling thread (via ProcessDSVIN() and ProcessDSSIGNFINALTX()), so two concurrent calls could act on the same snapshot: both could finalize, so clients would receive DSFINALTX twice, sign twice, and the duplicate signatures make AddScriptSig() fail and abort the session for everyone; or both could commit the same final transaction. A TRY_LOCK-only cs_check_pool makes it single-shot without ever blocking msghand. The signing branch also sampled signature completeness under a separate lock acquisition, and CommitFinalTransaction() then committed whatever finalMutableTransaction held, even if the session had timed out and been reset in between - pushing a cleared transaction through ATMP and notifying participants of a failure that never happened. Signature completeness is now part of the pool snapshot, and CommitFinalTransaction() takes the session id the decision was made for and revalidates it before committing. SetState() and IsSignaturesComplete() now require cs_coinjoin, so a transition and the session data it describes can only be observed together. ChargeFees() samples nState once instead of three times, which previously let it select 'didn't send' offenders and then charge and log them as 'didn't sign'. Co-Authored-By: Claude Opus 5.5 (1M context) --- src/coinjoin/server.cpp | 109 ++++++++++++++++++++++++++-------------- src/coinjoin/server.h | 32 ++++++++---- 2 files changed, 92 insertions(+), 49 deletions(-) diff --git a/src/coinjoin/server.cpp b/src/coinjoin/server.cpp index 8146bb269542..06f4646b6427 100644 --- a/src/coinjoin/server.cpp +++ b/src/coinjoin/server.cpp @@ -301,6 +301,14 @@ void CCoinJoinServer::SetNull() // void CCoinJoinServer::CheckPool() { + AssertLockNotHeld(cs_coinjoin); + + // Both the scheduler thread and the message-handling thread get here. Skip the round if the + // other one is already in it rather than blocking msghand behind its mempool work: whichever + // thread holds the lock is performing the same check we would. + TRY_LOCK(cs_check_pool, lock_check_pool); + if (!lock_check_pool) return; + // Every decision below reads several pieces of session state at once, so take them as one // snapshot. Sampling them separately let the message-handling thread commit an entry // between two reads: the side counts could be read before the last entry arrived while the @@ -350,9 +358,9 @@ void CCoinJoinServer::CheckPool() } // If we have all the signatures, try to compile the transaction - if (snap.state == POOL_STATE_SIGNING && IsSignaturesComplete()) { + if (snap.state == POOL_STATE_SIGNING && snap.signatures_complete) { LogPrint(BCLog::COINJOIN, "CCoinJoinServer::CheckPool -- SIGNING\n"); - CommitFinalTransaction(); + CommitFinalTransaction(snap.session_id); return; } } @@ -362,7 +370,7 @@ CCoinJoinServer::PoolSnapshot CCoinJoinServer::GetPoolSnapshot() const AssertLockNotHeld(cs_coinjoin); LOCK(cs_coinjoin); return PoolSnapshot{nSessionID, nState, vecEntries.size(), vecSessionCollaterals.size(), - GetMixSideCountsLocked()}; + GetMixSideCountsLocked(), IsSignaturesComplete()}; } void CCoinJoinServer::CreateFinalTransaction(int session_id) @@ -415,11 +423,22 @@ void CCoinJoinServer::CreateFinalTransaction(int session_id) RelayFinalTransaction(CTransaction(finalMutableTransaction)); } -void CCoinJoinServer::CommitFinalTransaction() +void CCoinJoinServer::CommitFinalTransaction(int session_id) { AssertLockNotHeld(cs_coinjoin); - CTransactionRef finalTransaction = WITH_LOCK(cs_coinjoin, return MakeTransactionRef(finalMutableTransaction)); + CTransactionRef finalTransaction; + { + LOCK(cs_coinjoin); + // Committing a session that is already gone would push a cleared finalMutableTransaction + // through ATMP and notify the participants of a failure that never happened. + if (nSessionID != session_id || nState != POOL_STATE_SIGNING) { + LogPrint(BCLog::COINJOIN, "CCoinJoinServer::CommitFinalTransaction -- session %d is gone, not committing\n", + session_id); + return; + } + finalTransaction = MakeTransactionRef(finalMutableTransaction); + } uint256 hashTx = finalTransaction->GetHash(); LogPrint(BCLog::COINJOIN, "CCoinJoinServer::CommitFinalTransaction -- finalTransaction=%s", /* Continued */ @@ -485,33 +504,42 @@ void CCoinJoinServer::ChargeFees() const if (GetRand(/*nMax=*/100) > 33) return; std::vector vecOffendersCollaterals; + size_t nSessionCollaterals{0}; + PoolState state{POOL_STATE_IDLE}; - if (nState == POOL_STATE_ACCEPTING_ENTRIES) { - LOCK(cs_coinjoin); - for (const auto& txCollateral : vecSessionCollaterals) { - bool fFound = std::ranges::any_of(vecEntries, [&txCollateral](const auto& entry) { - return *entry.txCollateral == *txCollateral; - }); - - // This queue entry didn't send us the promised transaction - if (!fFound) { - LogPrint(BCLog::COINJOIN, /* Continued */ - "CCoinJoinServer::ChargeFees -- found uncooperative node (didn't send transaction), found " - "offence\n"); - vecOffendersCollaterals.push_back(txCollateral); - } - } - } - - if (nState == POOL_STATE_SIGNING) { - // who didn't sign? + { LOCK(cs_coinjoin); - for (const auto& entry : vecEntries) { - for (const auto& txdsin : entry.vecTxDSIn) { - if (!txdsin.fHasSig) { + // Sample the state under the lock, together with the data it describes. Reading nState + // separately per branch let a concurrent transition select the "didn't send" offenders + // and then charge and log them as "didn't sign", or pick offenders from a session the + // state no longer describes. + state = nState; + nSessionCollaterals = vecSessionCollaterals.size(); + + if (state == POOL_STATE_ACCEPTING_ENTRIES) { + for (const auto& txCollateral : vecSessionCollaterals) { + bool fFound = std::ranges::any_of(vecEntries, [&txCollateral](const auto& entry) { + return *entry.txCollateral == *txCollateral; + }); + + // This queue entry didn't send us the promised transaction + if (!fFound) { LogPrint(BCLog::COINJOIN, /* Continued */ - "CCoinJoinServer::ChargeFees -- found uncooperative node (didn't sign), found offence\n"); - vecOffendersCollaterals.push_back(entry.txCollateral); + "CCoinJoinServer::ChargeFees -- found uncooperative node (didn't send transaction), found " + "offence\n"); + vecOffendersCollaterals.push_back(txCollateral); + } + } + } else if (state == POOL_STATE_SIGNING) { + // who didn't sign? + for (const auto& entry : vecEntries) { + for (const auto& txdsin : entry.vecTxDSIn) { + if (!txdsin.fHasSig) { + LogPrint(BCLog::COINJOIN, /* Continued */ + "CCoinJoinServer::ChargeFees -- found uncooperative node (didn't sign), found " + "offence\n"); + vecOffendersCollaterals.push_back(entry.txCollateral); + } } } } @@ -521,20 +549,18 @@ void CCoinJoinServer::ChargeFees() const if (vecOffendersCollaterals.empty()) return; //mostly offending? Charge sometimes - if (vecOffendersCollaterals.size() >= vecSessionCollaterals.size() - 1 && GetRand(/*nMax=*/100) > 33) return; + if (vecOffendersCollaterals.size() >= nSessionCollaterals - 1 && GetRand(/*nMax=*/100) > 33) return; //everyone is an offender? That's not right - if (vecOffendersCollaterals.size() >= vecSessionCollaterals.size()) return; + if (vecOffendersCollaterals.size() >= nSessionCollaterals) return; //charge one of the offenders randomly Shuffle(vecOffendersCollaterals.begin(), vecOffendersCollaterals.end(), FastRandomContext()); - if (nState == POOL_STATE_ACCEPTING_ENTRIES || nState == POOL_STATE_SIGNING) { - LogPrint(BCLog::COINJOIN, /* Continued */ - "CCoinJoinServer::ChargeFees -- found uncooperative node (didn't %s transaction), charging fees: %s", - (nState == POOL_STATE_SIGNING) ? "sign" : "send", vecOffendersCollaterals[0]->ToString()); - ConsumeCollateral(vecOffendersCollaterals[0]); - } + LogPrint(BCLog::COINJOIN, /* Continued */ + "CCoinJoinServer::ChargeFees -- found uncooperative node (didn't %s transaction), charging fees: %s", + (state == POOL_STATE_SIGNING) ? "sign" : "send", vecOffendersCollaterals[0]->ToString()); + ConsumeCollateral(vecOffendersCollaterals[0]); } /* @@ -641,6 +667,8 @@ void CCoinJoinServer::CheckTimeout() */ void CCoinJoinServer::CheckForCompleteQueue() { + AssertLockNotHeld(cs_coinjoin); + int session_denom; size_t participants; { @@ -911,8 +939,7 @@ bool CCoinJoinServer::AddScriptSig(const CTxIn& txinNew) // Check to make sure everything is signed bool CCoinJoinServer::IsSignaturesComplete() const { - AssertLockNotHeld(cs_coinjoin); - LOCK(cs_coinjoin); + AssertLockHeld(cs_coinjoin); return std::ranges::all_of(vecEntries, [](const auto& entry) { return std::ranges::all_of(entry.vecTxDSIn, [](const auto& txdsin) { return txdsin.fHasSig; }); @@ -1157,6 +1184,8 @@ bool CCoinJoinServer::AddUserToExistingSession(const CCoinJoinAccept& dsa, int n // Returns true if either max size has been reached or if the mix timed out and min size was reached bool CCoinJoinServer::IsSessionReady() const { + AssertLockHeld(cs_coinjoin); + if (nState == POOL_STATE_QUEUE) { // PRIVACY: don't start mixing until each side of the session denomination is occupied // by nobody or by at least two participants. A session that never attracts the missing @@ -1263,6 +1292,8 @@ void CCoinJoinServer::RelayCompletedTransaction(PoolMessage nMessageID) void CCoinJoinServer::SetState(PoolState nStateNew) { + AssertLockHeld(cs_coinjoin); + if (nStateNew == POOL_STATE_ERROR) { LogPrint(BCLog::COINJOIN, "CCoinJoinServer::SetState -- Can't set state to ERROR as a Masternode. \n"); return; diff --git a/src/coinjoin/server.h b/src/coinjoin/server.h index 475808c3052b..c2f8815c9e82 100644 --- a/src/coinjoin/server.h +++ b/src/coinjoin/server.h @@ -82,6 +82,13 @@ class CCoinJoinServer : public CCoinJoinBaseSession, public NetHandler private: bool fUnitTest; + /// Serializes CheckPool() against itself. CheckPool() runs both on the scheduler thread and + /// on the message-handling thread, and its finalize and commit steps have to be single-shot: + /// relaying DSFINALTX twice makes every client sign twice, and the duplicate signatures then + /// abort the session for all of them. Always acquired with TRY_LOCK and never taken by any + /// other code path, so a contended caller skips the round rather than blocking msghand. + Mutex cs_check_pool; + /// Add signature to a txin bool AddScriptSig(const CTxIn& txin) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); @@ -108,15 +115,16 @@ class CCoinJoinServer : public CCoinJoinBaseSession, public NetHandler size_t entries{0}; size_t collaterals{0}; CoinJoin::MixSideCounts sides; + bool signatures_complete{false}; }; PoolSnapshot GetPoolSnapshot() const EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); /// Is txref one of the collaterals accepted into the current session? bool HasSessionCollateral(const CTransactionRef& txref) const EXCLUSIVE_LOCKS_REQUIRED(cs_coinjoin); /// Check for process - void CheckPool(); + void CheckPool() EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin, !cs_check_pool); - void CommitFinalTransaction() EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); + void CommitFinalTransaction(int session_id) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); /// Is this nDenom and txCollateral acceptable? bool IsAcceptableDSA(const CCoinJoinAccept& dsa, PoolMessage& nMessageIDRet) const; @@ -126,12 +134,15 @@ class CCoinJoinServer : public CCoinJoinBaseSession, public NetHandler bool IsSessionReady() const EXCLUSIVE_LOCKS_REQUIRED(cs_coinjoin); /// Check that all inputs are signed. (Are all inputs signed?) - bool IsSignaturesComplete() const EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); + bool IsSignaturesComplete() const EXCLUSIVE_LOCKS_REQUIRED(cs_coinjoin); /// Check to make sure a given input matches an input in the pool and its scriptSig is valid bool IsInputScriptSigValid(const CTxIn& txin) const EXCLUSIVE_LOCKS_REQUIRED(cs_coinjoin); - // Set the 'state' value, with some logging and capturing when the state changed - void SetState(PoolState nStateNew); + // Set the 'state' value, with some logging and capturing when the state changed. + // Requires cs_coinjoin so that a transition and the session data it describes are always + // observed together: code that revalidates nState under the lock must not have it changed + // out from under it by a concurrent transition. + void SetState(PoolState nStateNew) EXCLUSIVE_LOCKS_REQUIRED(cs_coinjoin); /// Relay mixing Messages void RelayFinalTransaction(const CTransaction& txFinal) EXCLUSIVE_LOCKS_REQUIRED(cs_coinjoin); @@ -141,8 +152,8 @@ class CCoinJoinServer : public CCoinJoinBaseSession, public NetHandler void ProcessDSACCEPT(CNode& peer, CDataStream& vRecv) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); void ProcessDSQUEUE(NodeId from, CDataStream& vRecv); - void ProcessDSVIN(CNode& peer, CDataStream& vRecv) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); - void ProcessDSSIGNFINALTX(CNode& peer, CDataStream& vRecv) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); + void ProcessDSVIN(CNode& peer, CDataStream& vRecv) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin, !cs_check_pool); + void ProcessDSSIGNFINALTX(CNode& peer, CDataStream& vRecv) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin, !cs_check_pool); void SetNull() override EXCLUSIVE_LOCKS_REQUIRED(cs_coinjoin); @@ -156,14 +167,15 @@ class CCoinJoinServer : public CCoinJoinBaseSession, public NetHandler const CMasternodeSync& mn_sync, const llmq::CInstantSendManager& isman); ~CCoinJoinServer() override; - void ProcessMessage(CNode& pfrom, const std::string& msg_type, CDataStream& vRecv) override; + void ProcessMessage(CNode& pfrom, const std::string& msg_type, CDataStream& vRecv) override + EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin, !cs_check_pool); bool ProcessGetData(CNode& pfrom, const CInv& inv, const CNetMsgMaker& msgMaker) override; bool AlreadyHave(const CInv& inv) override; void Schedule(CScheduler& scheduler) override; bool HasTimedOut() const; - void CheckTimeout(); - void CheckForCompleteQueue(); + void CheckTimeout() EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); + void CheckForCompleteQueue() EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); void GetJsonInfo(UniValue& obj) const; }; From 97daa218363574d5b9fa0774f2678bbfe67aa640 Mon Sep 17 00:00:00 2001 From: pasta Date: Sat, 3 Oct 2026 19:34:25 -0500 Subject: [PATCH 2/6] fix(coinjoin): guard the session collaterals with cs_coinjoin vecSessionCollaterals had no GUARDED_BY, while setSessionCollateralPrevouts, the prevout index kept in lockstep with it, did. Most of its accesses have since been moved under cs_coinjoin one at a time, but nothing enforced it: CreateNewSession() still read its size for logging after releasing the lock, racing the scheduler thread's SetNull() and the message-handling thread's next admission, and any new read could reintroduce the same race unnoticed. The transactions and their prevout index are now a single SessionCollaterals member so they cannot drift apart or be annotated inconsistently again, and GUARDED_BY on that member makes every access - including the calls on it - checked by -Wthread-safety. Reintroducing an unlocked read is now a compile error rather than a review finding. CreateNewSession() captures the denomination and participant count it logs and announces while it still holds the lock. Co-Authored-By: Claude Opus 5.5 (1M context) --- src/coinjoin/server.cpp | 80 ++++++++++++++---------------- src/coinjoin/server.h | 50 ++++++++++++++++--- src/test/coinjoin_inouts_tests.cpp | 2 +- 3 files changed, 81 insertions(+), 51 deletions(-) diff --git a/src/coinjoin/server.cpp b/src/coinjoin/server.cpp index 06f4646b6427..3234f7844f1c 100644 --- a/src/coinjoin/server.cpp +++ b/src/coinjoin/server.cpp @@ -42,7 +42,6 @@ CCoinJoinServer::CCoinJoinServer(PeerManagerInternal* peer_manager, ChainstateMa m_mn_activeman{mn_activeman}, m_mn_sync{mn_sync}, m_isman{isman}, - vecSessionCollaterals{}, fUnitTest{false} { } @@ -87,7 +86,7 @@ void CCoinJoinServer::ProcessDSACCEPT(CNode& peer, CDataStream& vRecv) return; } - if (WITH_LOCK(cs_coinjoin, return vecSessionCollaterals.empty())) { + if (WITH_LOCK(cs_coinjoin, return m_session_collaterals.empty())) { { const auto hasQueue = m_queueman.TryHasQueueFromMasternode(m_mn_activeman.GetOutPoint()); if (!hasQueue.has_value()) return; @@ -286,8 +285,7 @@ void CCoinJoinServer::SetNull() { AssertLockHeld(cs_coinjoin); // MN side - vecSessionCollaterals.clear(); - setSessionCollateralPrevouts.clear(); + m_session_collaterals.Clear(); m_fRebalanceSession = false; m_fHasLegacyParticipant = false; m_mapDeclaredShapes.clear(); @@ -314,7 +312,7 @@ void CCoinJoinServer::CheckPool() // between two reads: the side counts could be read before the last entry arrived while the // entry count was read after it, so a session that was about to finalize looked like one // whose entries were all in but left a side uncovered - and got reset. Reading - // vecSessionCollaterals without the lock could also race SetNull() clearing it. + // the session collaterals without the lock could also race SetNull() clearing them. const auto snap = GetPoolSnapshot(); if (snap.entries != 0) @@ -369,7 +367,7 @@ CCoinJoinServer::PoolSnapshot CCoinJoinServer::GetPoolSnapshot() const { AssertLockNotHeld(cs_coinjoin); LOCK(cs_coinjoin); - return PoolSnapshot{nSessionID, nState, vecEntries.size(), vecSessionCollaterals.size(), + return PoolSnapshot{nSessionID, nState, vecEntries.size(), m_session_collaterals.size(), GetMixSideCountsLocked(), IsSignaturesComplete()}; } @@ -514,10 +512,10 @@ void CCoinJoinServer::ChargeFees() const // and then charge and log them as "didn't sign", or pick offenders from a session the // state no longer describes. state = nState; - nSessionCollaterals = vecSessionCollaterals.size(); + nSessionCollaterals = m_session_collaterals.size(); if (state == POOL_STATE_ACCEPTING_ENTRIES) { - for (const auto& txCollateral : vecSessionCollaterals) { + for (const auto& txCollateral : m_session_collaterals.txs()) { bool fFound = std::ranges::any_of(vecEntries, [&txCollateral](const auto& entry) { return *entry.txCollateral == *txCollateral; }); @@ -582,7 +580,7 @@ void CCoinJoinServer::ChargeRandomFees() const std::vector session_collaterals; { LOCK(cs_coinjoin); - session_collaterals = vecSessionCollaterals; + session_collaterals = m_session_collaterals.txs(); } for (const auto& txCollateral : session_collaterals) { @@ -631,7 +629,7 @@ bool CCoinJoinServer::IsCurrentSession(int session_id) const bool CCoinJoinServer::HasSessionCollateral(const CTransactionRef& txref) const { AssertLockHeld(cs_coinjoin); - return std::ranges::any_of(vecSessionCollaterals, + return std::ranges::any_of(m_session_collaterals.txs(), [&txref](const CTransactionRef& ref) { return *ref == *txref; }); } @@ -677,7 +675,7 @@ void CCoinJoinServer::CheckForCompleteQueue() SetState(POOL_STATE_ACCEPTING_ENTRIES); session_denom = nSessionDenom; - participants = vecSessionCollaterals.size(); + participants = m_session_collaterals.size(); } CCoinJoinQueue dsq(session_denom, m_mn_activeman.GetOutPoint(), m_mn_activeman.GetProTxHash(), GetAdjustedTime(), true); @@ -761,7 +759,7 @@ bool CCoinJoinServer::AddEntry(const CCoinJoinEntry& entry, PoolMessage& nMessag return false; } - if (static_cast(GetEntriesCountLocked()) >= vecSessionCollaterals.size()) { + if (static_cast(GetEntriesCountLocked()) >= m_session_collaterals.size()) { LogPrint(BCLog::COINJOIN, "CCoinJoinServer::%s -- ERROR: entries is full!\n", __func__); nMessageIDRet = ERR_ENTRIES_FULL; return false; @@ -965,15 +963,6 @@ bool CCoinJoinServer::IsAcceptableDSA(const CCoinJoinAccept& dsa, PoolMessage& n return true; } -void CCoinJoinServer::CommitSessionCollateral(const CMutableTransaction& txCollateral) -{ - AssertLockHeld(cs_coinjoin); - vecSessionCollaterals.push_back(MakeTransactionRef(txCollateral)); - for (const auto& txin : txCollateral.vin) { - setSessionCollateralPrevouts.insert(txin.prevout); - } -} - //! Which side of the session denomination a participant will occupy, from its declared dsa //! direction. A participant that declares nothing is mixing 1:1 and occupies both sides. static CoinJoin::MixShape DeclaredShape(const CCoinJoinAccept& dsa) @@ -1025,6 +1014,8 @@ bool CCoinJoinServer::CreateNewSession(const CCoinJoinAccept& dsa, int nPeerVers return false; } + int nDenom{0}; + size_t nParticipants{0}; { LOCK(cs_coinjoin); @@ -1046,21 +1037,25 @@ bool CCoinJoinServer::CreateNewSession(const CCoinJoinAccept& dsa, int nPeerVers SetState(POOL_STATE_QUEUE); - CommitSessionCollateral(dsa.txCollateral); + m_session_collaterals.Add(dsa.txCollateral); + nDenom = nSessionDenom; + nParticipants = m_session_collaterals.size(); } if (!fUnitTest) { //broadcast that I'm accepting entries, only if it's the first entry through - CCoinJoinQueue dsq(nSessionDenom, m_mn_activeman.GetOutPoint(), m_mn_activeman.GetProTxHash(), - GetAdjustedTime(), false); + CCoinJoinQueue dsq(nDenom, m_mn_activeman.GetOutPoint(), m_mn_activeman.GetProTxHash(), GetAdjustedTime(), false); LogPrint(BCLog::COINJOIN, "CCoinJoinServer::CreateNewSession -- signing and relaying new queue: %s\n", dsq.ToString()); dsq.vchSig = m_mn_activeman.SignBasic(dsq.GetSignatureHash()); m_peer_manager->PeerRelayDSQ(dsq); m_queueman.AddQueue(std::move(dsq)); } - LogPrint(BCLog::COINJOIN, "CCoinJoinServer::CreateNewSession -- new session created, nSessionID: %d nSessionDenom: %d (%s) vecSessionCollaterals.size(): %d CoinJoin::GetMaxPoolParticipants(): %d\n", - nSessionID, nSessionDenom, CoinJoin::DenominationToString(nSessionDenom), vecSessionCollaterals.size(), CoinJoin::GetMaxPoolParticipants()); + LogPrint(BCLog::COINJOIN, /* Continued */ + "CCoinJoinServer::CreateNewSession -- new session created, nSessionID: %d nSessionDenom: %d (%s) " + "participants: %d CoinJoin::GetMaxPoolParticipants(): %d\n", + nSessionID, nSessionDenom, CoinJoin::DenominationToString(nSessionDenom), nParticipants, + CoinJoin::GetMaxPoolParticipants()); return true; } @@ -1147,22 +1142,20 @@ bool CCoinJoinServer::AddUserToExistingSession(const CCoinJoinAccept& dsa, int n // IsSessionReady() can now hold a full session back waiting for a missing counterparty, so // the participant limit has to be enforced here rather than implied by session readiness - if (static_cast(vecSessionCollaterals.size()) >= CoinJoin::GetMaxPoolParticipants()) { + if (static_cast(m_session_collaterals.size()) >= CoinJoin::GetMaxPoolParticipants()) { LogPrint(BCLog::COINJOIN, "CCoinJoinServer::AddUserToExistingSession -- session is full\n"); nMessageIDRet = ERR_QUEUE_FULL; return false; } - // Session collaterals are only ever test-accepted, never added to the mempool, so nothing - // pins their identity: the same UTXO can be re-signed into arbitrarily many distinct txids. - // Match on input prevouts so a resent or replayed dsa cannot be counted as a new participant. - for (const auto& txin : dsa.txCollateral.vin) { - if (setSessionCollateralPrevouts.contains(txin.prevout)) { - LogPrint(BCLog::COINJOIN, "CCoinJoinServer::AddUserToExistingSession -- collateral %s spends prevout %s already committed to this session\n", - dsa.txCollateral.GetHash().ToString(), txin.prevout.ToStringShort()); - nMessageIDRet = ERR_ALREADY_HAVE; - return false; - } + // A resent or replayed dsa must not be counted as a new participant; see SessionCollaterals. + if (const auto prevout = m_session_collaterals.FindCommittedPrevout(dsa.txCollateral)) { + LogPrint(BCLog::COINJOIN, /* Continued */ + "CCoinJoinServer::AddUserToExistingSession -- collateral %s spends prevout %s already committed to " + "this session\n", + dsa.txCollateral.GetHash().ToString(), prevout->ToStringShort()); + nMessageIDRet = ERR_ALREADY_HAVE; + return false; } // count new user as accepted to an existing session @@ -1173,10 +1166,13 @@ bool CCoinJoinServer::AddUserToExistingSession(const CCoinJoinAccept& dsa, int n m_fRebalanceSession |= dsa.IsRebalance(); m_fHasLegacyParticipant |= nPeerVersion < COINJOIN_REBALANCE_VERSION; m_mapDeclaredShapes.emplace(dsa.txCollateral.GetHash(), DeclaredShape(dsa)); - CommitSessionCollateral(dsa.txCollateral); + m_session_collaterals.Add(dsa.txCollateral); - LogPrint(BCLog::COINJOIN, "CCoinJoinServer::AddUserToExistingSession -- new user accepted, nSessionID: %d nSessionDenom: %d (%s) vecSessionCollaterals.size(): %d CoinJoin::GetMaxPoolParticipants(): %d\n", - nSessionID, nSessionDenom, CoinJoin::DenominationToString(nSessionDenom), vecSessionCollaterals.size(), CoinJoin::GetMaxPoolParticipants()); + LogPrint(BCLog::COINJOIN, /* Continued */ + "CCoinJoinServer::AddUserToExistingSession -- new user accepted, nSessionID: %d nSessionDenom: %d (%s) " + "participants: %d CoinJoin::GetMaxPoolParticipants(): %d\n", + nSessionID, nSessionDenom, CoinJoin::DenominationToString(nSessionDenom), m_session_collaterals.size(), + CoinJoin::GetMaxPoolParticipants()); return true; } @@ -1191,10 +1187,10 @@ bool CCoinJoinServer::IsSessionReady() const // by nobody or by at least two participants. A session that never attracts the missing // counterparty simply expires in queue state, where no collateral is charged. if (!GetDeclaredSideCounts().IsCovered()) return false; - if (static_cast(vecSessionCollaterals.size()) >= CoinJoin::GetMaxPoolParticipants()) { + if (static_cast(m_session_collaterals.size()) >= CoinJoin::GetMaxPoolParticipants()) { return true; } - if (CCoinJoinServer::HasTimedOut() && static_cast(vecSessionCollaterals.size()) >= CoinJoin::GetMinPoolParticipants()) { + if (CCoinJoinServer::HasTimedOut() && static_cast(m_session_collaterals.size()) >= CoinJoin::GetMinPoolParticipants()) { return true; } } diff --git a/src/coinjoin/server.h b/src/coinjoin/server.h index c2f8815c9e82..fe6d7bbeb44e 100644 --- a/src/coinjoin/server.h +++ b/src/coinjoin/server.h @@ -13,6 +13,7 @@ #include #include +#include #include class CActiveMasternodeManager; @@ -48,12 +49,47 @@ class CCoinJoinServer : public CCoinJoinBaseSession, public NetHandler // Session state and entry admission live in the protected section so unit tests can seed // and drive them through a test subclass. - // Mixing uses collateral transactions to trust parties entering the pool - // to behave honestly. If they don't it takes their money. - std::vector vecSessionCollaterals; - // Input prevouts of every transaction in vecSessionCollaterals, so a dsa whose collateral - // reuses one of them can be rejected without rescanning them all. - std::unordered_set setSessionCollateralPrevouts GUARDED_BY(cs_coinjoin); + /// The collateral transactions of every peer admitted to the current session. + /// + /// Mixing uses collateral transactions to trust parties entering the pool to behave + /// honestly. If they don't it takes their money. + /// + /// Session collaterals are only ever test-accepted, never added to the mempool, so nothing + /// pins their identity: the same UTXO can be re-signed into arbitrarily many distinct txids. + /// Matching on input prevouts is what makes a resent or replayed dsa recognisable as the + /// same participant. + class SessionCollaterals + { + public: + void Add(const CMutableTransaction& txCollateral) + { + m_txs.push_back(MakeTransactionRef(txCollateral)); + for (const auto& txin : txCollateral.vin) { + m_prevouts.insert(txin.prevout); + } + } + void Clear() + { + m_txs.clear(); + m_prevouts.clear(); + } + //! The first input of txCollateral that an already admitted collateral also spends, if any. + std::optional FindCommittedPrevout(const CMutableTransaction& txCollateral) const + { + for (const auto& txin : txCollateral.vin) { + if (m_prevouts.contains(txin.prevout)) return txin.prevout; + } + return std::nullopt; + } + const std::vector& txs() const { return m_txs; } + size_t size() const { return m_txs.size(); } + bool empty() const { return m_txs.empty(); } + + private: + std::vector m_txs; + std::unordered_set m_prevouts; + }; + SessionCollaterals m_session_collaterals GUARDED_BY(cs_coinjoin); // Post-V24: true once a participant has been admitted that declared a promotion/demotion, // i.e. the final transaction may come out unbalanced. Latched on admission rather than @@ -74,8 +110,6 @@ class CCoinJoinServer : public CCoinJoinBaseSession, public NetHandler /// Add a clients entry to the pool bool AddEntry(const CCoinJoinEntry& entry, PoolMessage& nMessageIDRet) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); - /// Record an accepted collateral and index its input prevouts - void CommitSessionCollateral(const CMutableTransaction& txCollateral) EXCLUSIVE_LOCKS_REQUIRED(cs_coinjoin); /// Build and relay the final transaction if the live session is still eligible void CreateFinalTransaction(int session_id) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); diff --git a/src/test/coinjoin_inouts_tests.cpp b/src/test/coinjoin_inouts_tests.cpp index 0bbd76b6a793..122489f534f4 100644 --- a/src/test/coinjoin_inouts_tests.cpp +++ b/src/test/coinjoin_inouts_tests.cpp @@ -203,7 +203,7 @@ class TestableCoinJoinServer : public CCoinJoinServer { LOCK(cs_coinjoin); m_mapDeclaredShapes.emplace(txCollateral.GetHash(), shape); - CommitSessionCollateral(txCollateral); + m_session_collaterals.Add(txCollateral); } void SeedEntry(CCoinJoinEntry entry) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin) From 0ba94a66d76df7012d40d4efaa30f906f3982955 Mon Sep 17 00:00:00 2001 From: pasta Date: Sat, 3 Oct 2026 19:36:31 -0500 Subject: [PATCH 3/6] fix(coinjoin): serialize timeout transitions CheckTimeout() reset the pool while CheckPool() could be finalizing or committing the very same session on the message-handling thread: HasTimedOut() was tested without any lock and the reset could land between CheckPool()'s decision and its execution, clearing a live session mid-step. CheckTimeout() now takes the same cs_check_pool guard as CheckPool() - with TRY_LOCK, so a contended scheduler tick is skipped instead of blocking the message-handling thread - which makes timeout resets and finalize/commit single-flight. Offender selection also moves under cs_coinjoin, into SelectCollateralToCharge(), and into the same lock scope that closes the corresponding admission path: CheckTimeout() selects and resets atomically, and CreateFinalTransaction() selects and transitions to SIGNING atomically, so an entry that crossed the cutoff on time can no longer be charged as missing. The timeout finalization path also only charges once the live session is confirmed eligible; previously ChargeFees() ran first, and an ineligible session was charged again by the CheckTimeout() reset that followed. The collateral is consumed only after the lock is released, because ConsumeCollateral() takes cs_main and mempool submission must not run under cs_coinjoin. The session can be reset before that consumption runs: CheckTimeout() resets it right away, and RelayStatus() can reset it while CreateFinalTransaction() relays the final transaction. Session collaterals are only test-accepted, so until the consumption reaches the mempool nothing stops the charged participant from being readmitted into the next session with a collateral that is about to be spent: the same one, or a re-signed one spending the same input. The selected collateral is therefore reserved until ConsumeCollateral() has finished, and CreateNewSession() and AddUserToExistingSession() refuse a dsa whose collateral spends one of its inputs. The fee is still taken, and afterwards the mempool keeps the consumed collateral out. A post-reset session check would have avoided the readmission only by dropping the fee. AddEntry() consumes through ConsumeCollateralIfCurrentSession(), which has the same gap against a concurrent timeout, and takes the same reservation. Co-Authored-By: Claude Opus 5.5 (1M context) --- src/coinjoin/server.cpp | 250 ++++++++++++++++++----------- src/coinjoin/server.h | 36 +++-- src/test/coinjoin_inouts_tests.cpp | 9 +- 3 files changed, 184 insertions(+), 111 deletions(-) diff --git a/src/coinjoin/server.cpp b/src/coinjoin/server.cpp index 3234f7844f1c..0df3ae4bbabe 100644 --- a/src/coinjoin/server.cpp +++ b/src/coinjoin/server.cpp @@ -326,7 +326,7 @@ void CCoinJoinServer::CheckPool() if (snap.state == POOL_STATE_ACCEPTING_ENTRIES && snap.entries == snap.collaterals) { if (snap.sides.IsCovered()) { LogPrint(BCLog::COINJOIN, "CCoinJoinServer::CheckPool -- FINALIZE TRANSACTIONS\n"); - CreateFinalTransaction(snap.session_id); + CreateFinalTransaction(snap.session_id, /*charge_fees=*/false); return; } // The participant set is frozen once entries are being accepted, so this session can @@ -348,10 +348,8 @@ void CCoinJoinServer::CheckPool() // If we timed out while accepting entries, then if we have more than minimum, create final tx if (snap.state == POOL_STATE_ACCEPTING_ENTRIES && CCoinJoinServer::HasTimedOut() && snap.sides.IsCovered() && snap.entries >= static_cast(CoinJoin::GetMinPoolParticipants())) { - // Punish misbehaving participants - ChargeFees(); - // Try to complete this session ignoring the misbehaving ones - CreateFinalTransaction(snap.session_id); + // Punish misbehaving participants and try to complete this session ignoring them + CreateFinalTransaction(snap.session_id, /*charge_fees=*/true); return; } @@ -371,54 +369,67 @@ CCoinJoinServer::PoolSnapshot CCoinJoinServer::GetPoolSnapshot() const GetMixSideCountsLocked(), IsSignaturesComplete()}; } -void CCoinJoinServer::CreateFinalTransaction(int session_id) +void CCoinJoinServer::CreateFinalTransaction(int session_id, bool charge_fees) { AssertLockNotHeld(cs_coinjoin); LogPrint(BCLog::COINJOIN, "CCoinJoinServer::CreateFinalTransaction -- FINALIZE TRANSACTIONS\n"); - LOCK(cs_coinjoin); - - // The decision to finalize came from a snapshot taken before this lock, so make sure it - // still describes an eligible live session. An entry can finish validation and commit while - // the timeout path charges fees, changing a covered side from empty to a lone participant. - // Check the live entries under the same lock used to build the transaction so that entry - // admission cannot invalidate the decision before the state moves to signing. - if (!IsCurrentSession(session_id)) { - LogPrint(BCLog::COINJOIN, "CCoinJoinServer::CreateFinalTransaction -- session changed, not finalizing\n"); - return; - } - const auto sides = GetMixSideCountsLocked(); - if (vecEntries.size() < static_cast(CoinJoin::GetMinPoolParticipants()) || !sides.IsCovered()) { - LogPrint(BCLog::COINJOIN, "CCoinJoinServer::CreateFinalTransaction -- session no longer eligible, entries=%d, sides=%d/%d\n", - vecEntries.size(), sides.inputs, sides.outputs); - // Deliberately no timer refresh: on the timeout path the session stays timed out and - // the scheduler's next CheckTimeout() resets it. The missing side already had the full - // entry window, so waiting another one would only keep everyone else's coins locked. - return; - } + CTransactionRef collateral_to_charge; + { + LOCK(cs_coinjoin); - CMutableTransaction txNew; + // The decision to finalize came from a snapshot taken before this lock, so make sure it + // still describes an eligible live session. An entry can finish validation and commit in + // between, changing a covered side from empty to a lone participant. Check the live + // entries under the same lock used to build the transaction so that entry admission + // cannot invalidate the decision before the state moves to signing. + if (!IsCurrentSession(session_id)) { + LogPrint(BCLog::COINJOIN, "CCoinJoinServer::CreateFinalTransaction -- session changed, not finalizing\n"); + return; + } + const auto sides = GetMixSideCountsLocked(); + if (vecEntries.size() < static_cast(CoinJoin::GetMinPoolParticipants()) || !sides.IsCovered()) { + LogPrint(BCLog::COINJOIN, "CCoinJoinServer::CreateFinalTransaction -- session no longer eligible, entries=%d, sides=%d/%d\n", + vecEntries.size(), sides.inputs, sides.outputs); + // Deliberately no timer refresh: on the timeout path the session stays timed out and + // the scheduler's next CheckTimeout() resets it. The missing side already had the full + // entry window, so waiting another one would only keep everyone else's coins locked. + return; + } - // make our new transaction - for (const auto& entry : vecEntries) { - for (const auto& txout : entry.vecTxOut) { - txNew.vout.push_back(txout); + // Selecting the offenders and moving to signing below happen under one lock, so a + // participant whose entry commits before the cutoff can no longer be charged as missing. + if (charge_fees) { + collateral_to_charge = SelectCollateralToCharge(); } - for (const auto& txdsin : entry.vecTxDSIn) { - txNew.vin.push_back(txdsin); + + CMutableTransaction txNew; + + // make our new transaction + for (const auto& entry : vecEntries) { + for (const auto& txout : entry.vecTxOut) { + txNew.vout.push_back(txout); + } + for (const auto& txdsin : entry.vecTxDSIn) { + txNew.vin.push_back(txdsin); + } } - } - sort(txNew.vin.begin(), txNew.vin.end(), CompareInputBIP69()); - sort(txNew.vout.begin(), txNew.vout.end(), CompareOutputBIP69()); + sort(txNew.vin.begin(), txNew.vin.end(), CompareInputBIP69()); + sort(txNew.vout.begin(), txNew.vout.end(), CompareOutputBIP69()); - finalMutableTransaction = txNew; - LogPrint(BCLog::COINJOIN, "CCoinJoinServer::CreateFinalTransaction -- finalMutableTransaction=%s", /* Continued */ - txNew.ToString()); + finalMutableTransaction = txNew; + LogPrint(BCLog::COINJOIN, "CCoinJoinServer::CreateFinalTransaction -- finalMutableTransaction=%s", /* Continued */ + txNew.ToString()); - // request signatures from clients - SetState(POOL_STATE_SIGNING); - RelayFinalTransaction(CTransaction(finalMutableTransaction)); + // request signatures from clients + SetState(POOL_STATE_SIGNING); + RelayFinalTransaction(CTransaction(finalMutableTransaction)); + } + + if (collateral_to_charge) { + ConsumeReservedCollateral(collateral_to_charge); + } } void CCoinJoinServer::CommitFinalTransaction(int session_id) @@ -494,71 +505,69 @@ void CCoinJoinServer::CommitFinalTransaction(int session_id) // transaction for the client to be able to enter the pool. This transaction is kept by the Masternode // until the transaction is either complete or fails. // -void CCoinJoinServer::ChargeFees() const +/* + * Select one offender while cs_coinjoin still binds the state, entries and collaterals to the + * same session. The caller must close the relevant admission path before releasing the lock and + * consuming the returned collateral, so a late entry or signature cannot make the snapshot stale. + * The returned collateral stays reserved until ConsumeReservedCollateral() has run. + */ +CTransactionRef CCoinJoinServer::SelectCollateralToCharge() { - AssertLockNotHeld(cs_coinjoin); + AssertLockHeld(cs_coinjoin); //we don't need to charge collateral for every offence. - if (GetRand(/*nMax=*/100) > 33) return; + if (GetRand(/*nMax=*/100) > 33) return {}; std::vector vecOffendersCollaterals; - size_t nSessionCollaterals{0}; - PoolState state{POOL_STATE_IDLE}; - - { - LOCK(cs_coinjoin); - // Sample the state under the lock, together with the data it describes. Reading nState - // separately per branch let a concurrent transition select the "didn't send" offenders - // and then charge and log them as "didn't sign", or pick offenders from a session the - // state no longer describes. - state = nState; - nSessionCollaterals = m_session_collaterals.size(); - - if (state == POOL_STATE_ACCEPTING_ENTRIES) { - for (const auto& txCollateral : m_session_collaterals.txs()) { - bool fFound = std::ranges::any_of(vecEntries, [&txCollateral](const auto& entry) { - return *entry.txCollateral == *txCollateral; - }); - - // This queue entry didn't send us the promised transaction - if (!fFound) { - LogPrint(BCLog::COINJOIN, /* Continued */ - "CCoinJoinServer::ChargeFees -- found uncooperative node (didn't send transaction), found " - "offence\n"); - vecOffendersCollaterals.push_back(txCollateral); - } + const PoolState state{nState}; + const size_t nSessionCollaterals{m_session_collaterals.size()}; + + if (state == POOL_STATE_ACCEPTING_ENTRIES) { + for (const auto& txCollateral : m_session_collaterals.txs()) { + bool fFound = std::ranges::any_of(vecEntries, [&txCollateral](const auto& entry) { + return *entry.txCollateral == *txCollateral; + }); + + // This queue entry didn't send us the promised transaction + if (!fFound) { + LogPrint(BCLog::COINJOIN, /* Continued */ + "CCoinJoinServer::SelectCollateralToCharge -- found uncooperative node (didn't send " + "transaction), found offence\n"); + vecOffendersCollaterals.push_back(txCollateral); } - } else if (state == POOL_STATE_SIGNING) { - // who didn't sign? - for (const auto& entry : vecEntries) { - for (const auto& txdsin : entry.vecTxDSIn) { - if (!txdsin.fHasSig) { - LogPrint(BCLog::COINJOIN, /* Continued */ - "CCoinJoinServer::ChargeFees -- found uncooperative node (didn't sign), found " - "offence\n"); - vecOffendersCollaterals.push_back(entry.txCollateral); - } + } + } else if (state == POOL_STATE_SIGNING) { + // who didn't sign? + for (const auto& entry : vecEntries) { + for (const auto& txdsin : entry.vecTxDSIn) { + if (!txdsin.fHasSig) { + LogPrint(BCLog::COINJOIN, /* Continued */ + "CCoinJoinServer::SelectCollateralToCharge -- found uncooperative node (didn't sign), " + "found offence\n"); + vecOffendersCollaterals.push_back(entry.txCollateral); } } } } // no offences found - if (vecOffendersCollaterals.empty()) return; + if (vecOffendersCollaterals.empty()) return {}; //mostly offending? Charge sometimes - if (vecOffendersCollaterals.size() >= nSessionCollaterals - 1 && GetRand(/*nMax=*/100) > 33) return; + if (vecOffendersCollaterals.size() >= nSessionCollaterals - 1 && GetRand(/*nMax=*/100) > 33) return {}; //everyone is an offender? That's not right - if (vecOffendersCollaterals.size() >= nSessionCollaterals) return; + if (vecOffendersCollaterals.size() >= nSessionCollaterals) return {}; //charge one of the offenders randomly Shuffle(vecOffendersCollaterals.begin(), vecOffendersCollaterals.end(), FastRandomContext()); LogPrint(BCLog::COINJOIN, /* Continued */ - "CCoinJoinServer::ChargeFees -- found uncooperative node (didn't %s transaction), charging fees: %s", + "CCoinJoinServer::SelectCollateralToCharge -- found uncooperative node (didn't %s transaction), charging " + "fees: %s", (state == POOL_STATE_SIGNING) ? "sign" : "send", vecOffendersCollaterals[0]->ToString()); - ConsumeCollateral(vecOffendersCollaterals[0]); + m_collaterals_being_charged.push_back(vecOffendersCollaterals[0]); + return vecOffendersCollaterals[0]; } /* @@ -602,7 +611,29 @@ void CCoinJoinServer::ConsumeCollateral(const CTransactionRef& txref) const } } -void CCoinJoinServer::ConsumeCollateralIfCurrentSession(int session_id, const CTransactionRef& txref) const +void CCoinJoinServer::ConsumeReservedCollateral(const CTransactionRef& txref) +{ + AssertLockNotHeld(cs_coinjoin); + ConsumeCollateral(txref); + + // From here on the mempool, not the reservation, keeps a consumed collateral out of new sessions. + LOCK(cs_coinjoin); + const auto it = std::ranges::find(m_collaterals_being_charged, txref); + if (Assume(it != m_collaterals_being_charged.end())) m_collaterals_being_charged.erase(it); +} + +bool CCoinJoinServer::SpendsCollateralBeingCharged(const CMutableTransaction& txCollateral) const +{ + AssertLockHeld(cs_coinjoin); + return std::ranges::any_of(m_collaterals_being_charged, [&txCollateral](const CTransactionRef& charged) { + return std::ranges::any_of(charged->vin, [&txCollateral](const CTxIn& charged_in) { + return std::ranges::any_of(txCollateral.vin, + [&charged_in](const CTxIn& txin) { return txin.prevout == charged_in.prevout; }); + }); + }); +} + +void CCoinJoinServer::ConsumeCollateralIfCurrentSession(int session_id, const CTransactionRef& txref) { AssertLockNotHeld(cs_coinjoin); @@ -610,14 +641,18 @@ void CCoinJoinServer::ConsumeCollateralIfCurrentSession(int session_id, const CT // we get here the scheduler thread may have timed the session out and started another one. // Charging then would spend the collateral of a participant that is no longer in any // session - it may even be a replay of an innocent participant's collateral. - const bool fStillCurrent = - WITH_LOCK(cs_coinjoin, return IsCurrentSession(session_id) && HasSessionCollateral(txref)); + bool fStillCurrent{false}; + { + LOCK(cs_coinjoin); + fStillCurrent = IsCurrentSession(session_id) && HasSessionCollateral(txref); + if (fStillCurrent) m_collaterals_being_charged.push_back(txref); + } if (!fStillCurrent) { LogPrint(BCLog::COINJOIN, "CCoinJoinServer::%s -- session changed, not consuming collateral %s\n", __func__, txref->GetHash().ToString()); return; } - ConsumeCollateral(txref); + ConsumeReservedCollateral(txref); } bool CCoinJoinServer::IsCurrentSession(int session_id) const @@ -649,13 +684,28 @@ void CCoinJoinServer::CheckTimeout() { m_queueman.CheckQueue(); - // Too early to do anything - if (!CCoinJoinServer::HasTimedOut()) return; + // CheckPool can be finalizing or committing on the message-handling thread. Skipping this tick + // keeps timeout reset and finalization/commit single-flight without blocking the scheduler. + TRY_LOCK(cs_check_pool, lock_check_pool); + if (!lock_check_pool) return; - LogPrint(BCLog::COINJOIN, "CCoinJoinServer::CheckTimeout -- %s timed out -- resetting\n", - (nState == POOL_STATE_SIGNING) ? "Signing" : "Session"); - ChargeFees(); - WITH_LOCK(cs_coinjoin, SetNull()); + CTransactionRef collateral_to_charge; + { + LOCK(cs_coinjoin); + + // Too early to do anything. Recheck while holding the lock so selecting an offender and + // closing the session form one atomic cutoff for late entries and signatures. + if (!CCoinJoinServer::HasTimedOut()) return; + + LogPrint(BCLog::COINJOIN, "CCoinJoinServer::CheckTimeout -- %s timed out -- resetting\n", + (nState == POOL_STATE_SIGNING) ? "Signing" : "Session"); + collateral_to_charge = SelectCollateralToCharge(); + SetNull(); + } + + if (collateral_to_charge) { + ConsumeReservedCollateral(collateral_to_charge); + } } /* @@ -1026,6 +1076,11 @@ bool CCoinJoinServer::CreateNewSession(const CCoinJoinAccept& dsa, int nPeerVers nMessageIDRet = ERR_MODE; return false; } + if (SpendsCollateralBeingCharged(dsa.txCollateral)) { + LogPrint(BCLog::COINJOIN, "CCoinJoinServer::CreateNewSession -- collateral is being charged\n"); + nMessageIDRet = ERR_INVALID_COLLATERAL; + return false; + } // start new session nMessageIDRet = MSG_NOERR; @@ -1157,6 +1212,11 @@ bool CCoinJoinServer::AddUserToExistingSession(const CCoinJoinAccept& dsa, int n nMessageIDRet = ERR_ALREADY_HAVE; return false; } + if (SpendsCollateralBeingCharged(dsa.txCollateral)) { + LogPrint(BCLog::COINJOIN, "CCoinJoinServer::AddUserToExistingSession -- collateral is being charged\n"); + nMessageIDRet = ERR_INVALID_COLLATERAL; + return false; + } // count new user as accepted to an existing session diff --git a/src/coinjoin/server.h b/src/coinjoin/server.h index fe6d7bbeb44e..bae0eb364c63 100644 --- a/src/coinjoin/server.h +++ b/src/coinjoin/server.h @@ -110,31 +110,45 @@ class CCoinJoinServer : public CCoinJoinBaseSession, public NetHandler /// Add a clients entry to the pool bool AddEntry(const CCoinJoinEntry& entry, PoolMessage& nMessageIDRet) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); - /// Build and relay the final transaction if the live session is still eligible - void CreateFinalTransaction(int session_id) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); + /// Build and relay the final transaction if the live session is still eligible, charging one + /// missing participant first if charge_fees is set + void CreateFinalTransaction(int session_id, bool charge_fees) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); private: bool fUnitTest; - /// Serializes CheckPool() against itself. CheckPool() runs both on the scheduler thread and - /// on the message-handling thread, and its finalize and commit steps have to be single-shot: - /// relaying DSFINALTX twice makes every client sign twice, and the duplicate signatures then - /// abort the session for all of them. Always acquired with TRY_LOCK and never taken by any - /// other code path, so a contended caller skips the round rather than blocking msghand. + /// Serializes CheckPool() against itself and against CheckTimeout(). CheckPool() runs both on + /// the scheduler thread and on the message-handling thread, and its finalize and commit steps + /// have to be single-shot: relaying DSFINALTX twice makes every client sign twice, and the + /// duplicate signatures then abort the session for all of them. CheckTimeout() uses the same + /// guard so it cannot reset a session during finalization or commit. Always acquired with + /// TRY_LOCK, so a contended caller skips the round rather than blocking msghand. Mutex cs_check_pool; /// Add signature to a txin bool AddScriptSig(const CTxIn& txin) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); - /// Charge fees to bad actors (Charge clients a fee if they're abusive) - void ChargeFees() const EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); + /// Collaterals chosen to be charged whose consumption has not finished yet. They are chosen + /// under cs_coinjoin, but ConsumeCollateral() takes cs_main and runs after cs_coinjoin is + /// released, by which time the session may have been reset. Until then admission refuses any + /// collateral that spends one of their inputs, so a charged participant cannot be readmitted + /// into the next session with a collateral that is about to be spent. Survives SetNull(). + std::vector m_collaterals_being_charged GUARDED_BY(cs_coinjoin); + /// Does txCollateral spend an input of a collateral that is being charged? + bool SpendsCollateralBeingCharged(const CMutableTransaction& txCollateral) const EXCLUSIVE_LOCKS_REQUIRED(cs_coinjoin); + + /// Choose one bad actor whose collateral should be consumed, if any, and reserve it. The + /// result must be passed to ConsumeReservedCollateral(). + CTransactionRef SelectCollateralToCharge() EXCLUSIVE_LOCKS_REQUIRED(cs_coinjoin); /// Rarely charge fees to pay miners void ChargeRandomFees() const EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); /// Consume collateral in cases when peer misbehaved. Takes cs_main, which this class never /// takes under cs_coinjoin. void ConsumeCollateral(const CTransactionRef& txref) const EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); + /// Consume a collateral reserved in m_collaterals_being_charged, then release the reservation + void ConsumeReservedCollateral(const CTransactionRef& txref) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); /// Consume collateral, but only while session_id is still the live session holding it - void ConsumeCollateralIfCurrentSession(int session_id, const CTransactionRef& txref) const + void ConsumeCollateralIfCurrentSession(int session_id, const CTransactionRef& txref) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); /// Is session_id still the session we are accepting entries for? @@ -208,7 +222,7 @@ class CCoinJoinServer : public CCoinJoinBaseSession, public NetHandler void Schedule(CScheduler& scheduler) override; bool HasTimedOut() const; - void CheckTimeout() EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); + void CheckTimeout() EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin, !cs_check_pool); void CheckForCompleteQueue() EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); void GetJsonInfo(UniValue& obj) const; diff --git a/src/test/coinjoin_inouts_tests.cpp b/src/test/coinjoin_inouts_tests.cpp index 122489f534f4..28c277719351 100644 --- a/src/test/coinjoin_inouts_tests.cpp +++ b/src/test/coinjoin_inouts_tests.cpp @@ -175,8 +175,7 @@ BOOST_AUTO_TEST_CASE(entry_addscriptsig_matches_and_rejects) } } -// Test-only subclass exposing the minimal seams needed to observe how -// ProcessDSSIGNFINALTX treats messages from participants vs. non-participants +// Test-only subclass exposing the minimal seams needed to put the server into a session state // without standing up a full DKG-backed signing session. class TestableCoinJoinServer : public CCoinJoinServer { @@ -457,11 +456,11 @@ BOOST_AUTO_TEST_CASE(server_finalization_rechecks_live_side_coverage) server.EnterAcceptingEntriesState(); // A timeout snapshot could have observed only the three demotions as covered (0/3), then - // this first promotion could commit while ChargeFees() ran. Finalization must use the live - // 1/3 side counts and refuse to build the uncovered transaction, staying out of + // this first promotion could commit before finalization took the lock. Finalization must use + // the live 1/3 side counts and refuse to build the uncovered transaction, staying out of // POOL_STATE_SIGNING; the still-timed-out session is then reset by the scheduler's // regular CheckTimeout() pass instead of leaking a lone promoter on-chain. - server.CreateFinalTransaction(/*session_id=*/1); + server.CreateFinalTransaction(/*session_id=*/1, /*charge_fees=*/true); BOOST_CHECK_EQUAL(server.GetState(), int{POOL_STATE_ACCEPTING_ENTRIES}); BOOST_CHECK_EQUAL(server.GetEntriesCount(), 4); } From d1e23c79ca9718c0df9d52b305bcf752c7f12656 Mon Sep 17 00:00:00 2001 From: pasta Date: Wed, 7 Oct 2026 11:48:41 -0500 Subject: [PATCH 4/6] fix(coinjoin): prioritize progress over timeout reset The scheduler calls CheckPool() and CheckTimeout() separately, leaving a gap in which the final collateral, entry, or signature can arrive after CheckPool() takes its snapshot. The message thread then skips its own CheckPool() while the scheduler holds cs_check_pool, and an unconditional timeout reset would discard a session that can now advance. Recheck readiness, finalizability (including session-denomination side coverage, as CheckPool() and CreateFinalTransaction() require) and signature completeness under cs_coinjoin before resetting. Actionable work takes priority and is picked up by the next scheduler tick. The decision is a pure function of the session's progress, ShouldResetTimedOutSession(), so the unit test covers each case directly instead of seeding a timed-out session into the server. Co-Authored-By: Claude Opus 5.5 --- src/coinjoin/server.cpp | 32 ++++++++++++++++-- src/coinjoin/server.h | 21 ++++++++++++ src/test/coinjoin_inouts_tests.cpp | 52 ++++++++++++++++++++++++++++++ 3 files changed, 102 insertions(+), 3 deletions(-) diff --git a/src/coinjoin/server.cpp b/src/coinjoin/server.cpp index 0df3ae4bbabe..24f2c6dec508 100644 --- a/src/coinjoin/server.cpp +++ b/src/coinjoin/server.cpp @@ -677,6 +677,19 @@ bool CCoinJoinServer::HasTimedOut() const return GetTime() - nTimeLastSuccessfulStep >= nTimeout; } +bool ShouldResetTimedOutSession(const CoinJoinSessionProgress& session) +{ + if (!session.timed_out) return false; + + const bool can_advance{(session.state == POOL_STATE_QUEUE && session.queue_ready) || + (session.state == POOL_STATE_ACCEPTING_ENTRIES && + (session.entries == session.collaterals || + (session.entries >= static_cast(CoinJoin::GetMinPoolParticipants()) && + session.sides.IsCovered()))) || + (session.state == POOL_STATE_SIGNING && session.signatures_complete)}; + return !can_advance; +} + // // Check for extraneous timeout // @@ -693,9 +706,22 @@ void CCoinJoinServer::CheckTimeout() { LOCK(cs_coinjoin); - // Too early to do anything. Recheck while holding the lock so selecting an offender and - // closing the session form one atomic cutoff for late entries and signatures. - if (!CCoinJoinServer::HasTimedOut()) return; + // Decide while holding the lock so selecting an offender and closing the session form one + // atomic cutoff for late entries and signatures. + // CheckForCompleteQueue() and CheckPool() run before this method on the scheduler thread, + // but a final collateral, entry, or signature can arrive after their snapshots. The + // message-handling thread then skips its own CheckPool() if this scheduler tick still holds + // cs_check_pool. A session that can now advance takes priority over resetting it; the next + // scheduler tick will perform the transition, finalization, or commit. + if (!ShouldResetTimedOutSession({.state = nState, + .timed_out = CCoinJoinServer::HasTimedOut(), + .queue_ready = IsSessionReady(), + .entries = vecEntries.size(), + .collaterals = m_session_collaterals.size(), + .sides = GetMixSideCountsLocked(), + .signatures_complete = IsSignaturesComplete()})) { + return; + } LogPrint(BCLog::COINJOIN, "CCoinJoinServer::CheckTimeout -- %s timed out -- resetting\n", (nState == POOL_STATE_SIGNING) ? "Signing" : "Session"); diff --git a/src/coinjoin/server.h b/src/coinjoin/server.h index bae0eb364c63..1b84e02d9fda 100644 --- a/src/coinjoin/server.h +++ b/src/coinjoin/server.h @@ -28,6 +28,27 @@ class CTxMemPool; class UniValue; +/** What the server's timeout check reads from a mixing session to decide whether to reset it */ +struct CoinJoinSessionProgress { + PoolState state{POOL_STATE_IDLE}; + bool timed_out{false}; + //! The queue has enough collaterals covering both sides to start accepting entries + bool queue_ready{false}; + size_t entries{0}; + size_t collaterals{0}; + //! The sides of the session denomination occupied by the submitted entries + CoinJoin::MixSideCounts sides{}; + bool signatures_complete{false}; +}; + +/** + * Should a session be reset for timing out? Not while it can still make the transition that + * CheckForCompleteQueue() or CheckPool() would make for it: start accepting entries, finalize + * (or, with an entry for every collateral but a side uncovered, reset with the participants + * told), or commit. + */ +bool ShouldResetTimedOutSession(const CoinJoinSessionProgress& session); + /** Used to keep track of current status of mixing pool */ class CCoinJoinServer : public CCoinJoinBaseSession, public NetHandler diff --git a/src/test/coinjoin_inouts_tests.cpp b/src/test/coinjoin_inouts_tests.cpp index 28c277719351..c5dea2930c42 100644 --- a/src/test/coinjoin_inouts_tests.cpp +++ b/src/test/coinjoin_inouts_tests.cpp @@ -465,6 +465,58 @@ BOOST_AUTO_TEST_CASE(server_finalization_rechecks_live_side_coverage) BOOST_CHECK_EQUAL(server.GetEntriesCount(), 4); } +BOOST_AUTO_TEST_CASE(server_timeout_resets_only_sessions_that_cannot_advance) +{ + // The final collateral, entry or signature can arrive after the scheduler's own CheckPool() + // snapshot. A timed-out session that can still advance must be left for the next tick + // instead of being discarded, and one that cannot must still be reset. + const size_t min{static_cast(CoinJoin::GetMinPoolParticipants())}; + const CoinJoin::MixSideCounts covered{.inputs = static_cast(min), .outputs = static_cast(min)}; + // One promoter and min - 1 demoters: the promoter would hold the only session-denom input + const CoinJoin::MixSideCounts lone_promoter{.inputs = 1, .outputs = static_cast(min) - 1}; + struct Case { + std::string name; + CoinJoinSessionProgress session; + bool reset; + }; + const std::vector cases{ + {"not timed out", + {.state = POOL_STATE_SIGNING, .timed_out = false, .entries = min, .collaterals = min, .sides = covered}, + false}, + {"ready queue", {.state = POOL_STATE_QUEUE, .timed_out = true, .queue_ready = true, .collaterals = min}, false}, + {"queue not ready", {.state = POOL_STATE_QUEUE, .timed_out = true, .collaterals = min - 1}, true}, + {"every entry in, a side uncovered", + {.state = POOL_STATE_ACCEPTING_ENTRIES, .timed_out = true, .entries = min, .collaterals = min, + .sides = lone_promoter}, + false}, + {"enough covered entries, one straggler", + {.state = POOL_STATE_ACCEPTING_ENTRIES, .timed_out = true, .entries = min, .collaterals = min + 1, + .sides = covered}, + false}, + {"too few entries", + {.state = POOL_STATE_ACCEPTING_ENTRIES, .timed_out = true, .entries = min - 1, .collaterals = min, + .sides = covered}, + true}, + {"enough entries, a side uncovered, one straggler", + {.state = POOL_STATE_ACCEPTING_ENTRIES, .timed_out = true, .entries = min, .collaterals = min + 1, + .sides = lone_promoter}, + true}, + {"every input signed", + {.state = POOL_STATE_SIGNING, .timed_out = true, .entries = min, .collaterals = min, + .sides = covered, .signatures_complete = true}, + false}, + {"a signature missing", + {.state = POOL_STATE_SIGNING, .timed_out = true, .entries = min, .collaterals = min, .sides = covered}, + true}, + }; + for (const auto& [name, session, reset] : cases) { + BOOST_TEST_CONTEXT(name) + { + BOOST_CHECK_EQUAL(ShouldResetTimedOutSession(session), reset); + } + } +} + BOOST_AUTO_TEST_CASE(entry_deserializes_vectors_through_wire_cap) { const size_t wire_cap{CoinJoin::GetMaxPoolInputOutputCount()}; From 873295f4e1e51f4ab843e5e6ea827025196b6eb1 Mon Sep 17 00:00:00 2001 From: pasta Date: Wed, 7 Oct 2026 11:49:00 -0500 Subject: [PATCH 5/6] fix(coinjoin): bind completion tail to session snapshot Completion relay previously read and mutated live session state after CommitFinalTransaction() released cs_coinjoin. If all old participants disconnected, RelayCompletedTransaction() could reset the session, allowing a replacement session to open before random charging and the unconditional tail reset; those operations could then charge or clear the replacement. The invalid-transaction path also reset the pool before notifying anyone, so its ERR_INVALID_TX went to an empty participant list. Capture the committed transaction, participants, and collaterals under cs_coinjoin. Relay and charge only those snapshots, keep completion notification side-effect-free, and reset only the matching signing session. The invalid-transaction path now notifies the captured participants before reset, and CheckPool()'s uncovered-session reset captures its participants and resets in one step before telling them. Co-Authored-By: Claude Opus 5.5 (1M context) --- src/coinjoin/server.cpp | 80 +++++++++++++++++++++++++---------------- src/coinjoin/server.h | 11 ++++-- 2 files changed, 59 insertions(+), 32 deletions(-) diff --git a/src/coinjoin/server.cpp b/src/coinjoin/server.cpp index 24f2c6dec508..b4176f2ef126 100644 --- a/src/coinjoin/server.cpp +++ b/src/coinjoin/server.cpp @@ -334,13 +334,18 @@ void CCoinJoinServer::CheckPool() // timeout. Shouldn't happen: admission checks the declared shapes up front. LogPrint(BCLog::COINJOIN, "CCoinJoinServer::CheckPool -- all entries received but a session denom side is uncovered (%d in, %d out), resetting session\n", snap.sides.inputs, snap.sides.outputs); - // Tell the participants before dropping them, so they release their inputs and collateral - // right away instead of waiting out their own timeout. Must precede SetNull(), which - // clears the entries this iterates. - RelayCompletedTransaction(ERR_SESSION); // Only drop the session the snapshot described; the message-handling thread may have - // reset and restarted one while we were relaying. - WITH_LOCK(cs_coinjoin, if (IsCurrentSession(snap.session_id)) SetNull()); + // reset and restarted one since. Capture its participants in the same step, then tell + // them, so they release their inputs and collateral right away instead of waiting out + // their own timeout. + std::vector participants; + { + LOCK(cs_coinjoin); + if (!IsCurrentSession(snap.session_id)) return; + participants = GetParticipantAddrs(); + SetNull(); + } + RelayCompletedTransaction(snap.session_id, participants, ERR_SESSION); return; } @@ -437,6 +442,8 @@ void CCoinJoinServer::CommitFinalTransaction(int session_id) AssertLockNotHeld(cs_coinjoin); CTransactionRef finalTransaction; + std::vector participants; + std::vector collaterals; { LOCK(cs_coinjoin); // Committing a session that is already gone would push a cleared finalMutableTransaction @@ -447,6 +454,8 @@ void CCoinJoinServer::CommitFinalTransaction(int session_id) return; } finalTransaction = MakeTransactionRef(finalMutableTransaction); + participants = GetParticipantAddrs(); + collaterals = m_session_collaterals.txs(); } uint256 hashTx = finalTransaction->GetHash(); @@ -460,9 +469,9 @@ void CCoinJoinServer::CommitFinalTransaction(int session_id) if (!lockMain || !ATMPIfSaneFee(m_chainman, finalTransaction)) { LogPrint(BCLog::COINJOIN, /* Continued */ "CCoinJoinServer::CommitFinalTransaction -- ATMPIfSaneFee() error: Transaction not valid\n"); - WITH_LOCK(cs_coinjoin, SetNull()); // not much we can do in this case, just notify clients - RelayCompletedTransaction(ERR_INVALID_TX); + RelayCompletedTransaction(session_id, participants, ERR_INVALID_TX); + ResetSigningSessionIfCurrent(session_id); return; } } @@ -483,14 +492,14 @@ void CCoinJoinServer::CommitFinalTransaction(int session_id) m_peer_manager->PeerRelayInv(inv); // Tell the clients it was successful - RelayCompletedTransaction(MSG_SUCCESS); + RelayCompletedTransaction(session_id, participants, MSG_SUCCESS); // Randomly charge clients - ChargeRandomFees(); + ChargeRandomFees(collaterals); // Reset LogPrint(BCLog::COINJOIN, "CCoinJoinServer::CommitFinalTransaction -- COMPLETED -- RESETTING\n"); - WITH_LOCK(cs_coinjoin, SetNull()); + ResetSigningSessionIfCurrent(session_id); } // @@ -582,17 +591,11 @@ CTransactionRef CCoinJoinServer::SelectCollateralToCharge() stop these kinds of attacks 1 in 10 successful transactions are charged. This adds up to a cost of 0.001DRK per transaction on average. */ -void CCoinJoinServer::ChargeRandomFees() const +void CCoinJoinServer::ChargeRandomFees(const std::vector& collaterals) const { AssertLockNotHeld(cs_coinjoin); - std::vector session_collaterals; - { - LOCK(cs_coinjoin); - session_collaterals = m_session_collaterals.txs(); - } - - for (const auto& txCollateral : session_collaterals) { + for (const auto& txCollateral : collaterals) { if (GetRand(/*nMax=*/100) > 10) return; LogPrint(BCLog::COINJOIN, /* Continued */ "CCoinJoinServer::ChargeRandomFees -- charging random fees, txCollateral=%s", txCollateral->ToString()); @@ -1350,28 +1353,45 @@ void CCoinJoinServer::RelayStatus(PoolStatusUpdate nStatusUpdate, PoolMessage nM } } -void CCoinJoinServer::RelayCompletedTransaction(PoolMessage nMessageID) +void CCoinJoinServer::RelayCompletedTransaction(int session_id, const std::vector& participants, + PoolMessage nMessageID) { AssertLockNotHeld(cs_coinjoin); - LogPrint(BCLog::COINJOIN, "CCoinJoinServer::%s -- nSessionID: %d nSessionDenom: %d (%s)\n", - __func__, nSessionID, nSessionDenom, CoinJoin::DenominationToString(nSessionDenom)); + LogPrint(BCLog::COINJOIN, "CCoinJoinServer::%s -- nSessionID: %d\n", __func__, session_id); - // final mixing tx with empty signatures should be relayed to mixing participants only - LOCK(cs_coinjoin); - for (const auto& entry : vecEntries) { - bool fOk = connman.ForNode(entry.addr, [&nMessageID, this](CNode* pnode) { + for (const auto& addr : participants) { + const bool fOk = connman.ForNode(addr, [&nMessageID, session_id, this](CNode* pnode) { CNetMsgMaker msgMaker(pnode->GetCommonVersion()); - connman.PushMessage(pnode, msgMaker.Make(NetMsgType::DSCOMPLETE, nSessionID.load(), nMessageID)); + connman.PushMessage(pnode, msgMaker.Make(NetMsgType::DSCOMPLETE, session_id, nMessageID)); return true; }); if (!fOk) { - // no such node? maybe client disconnected or our own connection went down - RelayStatus(STATUS_REJECTED); - break; + LogPrint(BCLog::COINJOIN, "CCoinJoinServer::%s -- participant disconnected before completion\n", __func__); } } } +std::vector CCoinJoinServer::GetParticipantAddrs() const +{ + AssertLockHeld(cs_coinjoin); + std::vector participants; + participants.reserve(vecEntries.size()); + std::ranges::transform(vecEntries, std::back_inserter(participants), [](const auto& entry) { return entry.addr; }); + return participants; +} + +void CCoinJoinServer::ResetSigningSessionIfCurrent(int session_id) +{ + AssertLockNotHeld(cs_coinjoin); + LOCK(cs_coinjoin); + if (nSessionID != session_id || nState != POOL_STATE_SIGNING) { + LogPrint(BCLog::COINJOIN, /* Continued */ + "CCoinJoinServer::%s -- signing session %d is no longer current, not resetting\n", __func__, session_id); + return; + } + SetNull(); +} + void CCoinJoinServer::SetState(PoolState nStateNew) { AssertLockHeld(cs_coinjoin); diff --git a/src/coinjoin/server.h b/src/coinjoin/server.h index 1b84e02d9fda..ff287d79bd50 100644 --- a/src/coinjoin/server.h +++ b/src/coinjoin/server.h @@ -162,7 +162,7 @@ class CCoinJoinServer : public CCoinJoinBaseSession, public NetHandler /// result must be passed to ConsumeReservedCollateral(). CTransactionRef SelectCollateralToCharge() EXCLUSIVE_LOCKS_REQUIRED(cs_coinjoin); /// Rarely charge fees to pay miners - void ChargeRandomFees() const EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); + void ChargeRandomFees(const std::vector& collaterals) const EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); /// Consume collateral in cases when peer misbehaved. Takes cs_main, which this class never /// takes under cs_coinjoin. void ConsumeCollateral(const CTransactionRef& txref) const EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); @@ -194,6 +194,12 @@ class CCoinJoinServer : public CCoinJoinBaseSession, public NetHandler void CheckPool() EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin, !cs_check_pool); void CommitFinalTransaction(int session_id) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); + /// Tell the given participants of session_id how it ended. Side-effect free: the participant + /// list is captured by the caller, so a reset or replacement session cannot be notified. + void RelayCompletedTransaction(int session_id, const std::vector& participants, PoolMessage nMessageID) + EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); + /// Reset the pool, but only while session_id is still the signing session being completed + void ResetSigningSessionIfCurrent(int session_id) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); /// Is this nDenom and txCollateral acceptable? bool IsAcceptableDSA(const CCoinJoinAccept& dsa, PoolMessage& nMessageIDRet) const; @@ -217,7 +223,8 @@ class CCoinJoinServer : public CCoinJoinBaseSession, public NetHandler void RelayFinalTransaction(const CTransaction& txFinal) EXCLUSIVE_LOCKS_REQUIRED(cs_coinjoin); void PushStatus(CNode& peer, PoolStatusUpdate nStatusUpdate, PoolMessage nMessageID) const; void RelayStatus(PoolStatusUpdate nStatusUpdate, PoolMessage nMessageID = MSG_NOERR) EXCLUSIVE_LOCKS_REQUIRED(cs_coinjoin); - void RelayCompletedTransaction(PoolMessage nMessageID) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); + /// Addresses of the participants that submitted an entry to the current session + std::vector GetParticipantAddrs() const EXCLUSIVE_LOCKS_REQUIRED(cs_coinjoin); void ProcessDSACCEPT(CNode& peer, CDataStream& vRecv) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); void ProcessDSQUEUE(NodeId from, CDataStream& vRecv); From a231f0558d9cc8f9ab13964530685aae3348e04a Mon Sep 17 00:00:00 2001 From: pasta Date: Sat, 3 Oct 2026 19:48:57 -0500 Subject: [PATCH 6/6] fix(coinjoin): apply a DSSIGNFINALTX message atomically A DSSIGNFINALTX message can carry several signed inputs, but each was applied through a separate AddScriptSig() call that took and released cs_coinjoin on its own, and the signing-state and participant checks were released before the body was even decoded. At the signing-timeout boundary the scheduler's CheckTimeout() could take the lock between two inputs of the same already-received message, still find the sender's later inputs unsigned, select the sender as a non-signer to charge, and reset the session; the remaining inputs then failed against the cleared pool. Capture the signing session the sender was checked against, then revalidate it after decoding and apply the whole batch under one cs_coinjoin critical section, relaying a rejection from inside the same section if an input fails. AddScriptSig() now requires cs_coinjoin. The lock is released before CheckPool(), which then commits the fully signed session; CheckTimeout() sees IsSignaturesComplete() and defers to it. No cs_main is taken in this section: signature verification already ran under cs_coinjoin inside AddScriptSig(). Co-Authored-By: Claude Opus 5.5 (1M context) --- src/coinjoin/server.cpp | 48 +++++++++++++++++++++++++---------------- src/coinjoin/server.h | 2 +- 2 files changed, 31 insertions(+), 19 deletions(-) diff --git a/src/coinjoin/server.cpp b/src/coinjoin/server.cpp index b4176f2ef126..b06652025431 100644 --- a/src/coinjoin/server.cpp +++ b/src/coinjoin/server.cpp @@ -232,14 +232,14 @@ 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; - } + int session_id{0}; { LOCK(cs_coinjoin); + 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; + } const bool is_participant = std::ranges::any_of( vecEntries, [&peer](const auto& entry) { return entry.addr == peer.addr; }); if (!is_participant) { @@ -248,6 +248,7 @@ void CCoinJoinServer::ProcessDSSIGNFINALTX(CNode& peer, CDataStream& vRecv) PushStatus(peer, STATUS_REJECTED, ERR_INVALID_INPUT); return; } + session_id = nSessionID; } const size_t max_txins{CoinJoin::GetMaxPoolInputOutputCount()}; @@ -264,18 +265,30 @@ void CCoinJoinServer::ProcessDSSIGNFINALTX(CNode& peer, CDataStream& vRecv) LogPrint(BCLog::COINJOIN, "DSSIGNFINALTX -- vecTxIn.size() %s\n", vecTxIn.size()); - int nTxInIndex = 0; - int nTxInsCount = static_cast(vecTxIn.size()); - - for (const auto& txin : vecTxIn) { - nTxInIndex++; - if (!AddScriptSig(txin)) { - LogPrint(BCLog::COINJOIN, "DSSIGNFINALTX -- AddScriptSig() failed at %d/%d, session: %d\n", nTxInIndex, nTxInsCount, nSessionID); - LOCK(cs_coinjoin); - RelayStatus(STATUS_REJECTED); + { + LOCK(cs_coinjoin); + // Apply the whole message in one critical section, against the signing session it was + // checked for above. The lock was released while the body was decoded, and releasing it + // between inputs would let a timeout reset the session halfway through one sender's + // already-received signatures, after charging that sender as a non-signer. + if (nSessionID != session_id || nState != POOL_STATE_SIGNING) { + LogPrint(BCLog::COINJOIN, "DSSIGNFINALTX -- session %d is no longer signing, peer=%d\n", session_id, + peer.GetId()); + PushStatus(peer, STATUS_REJECTED, ERR_SESSION); return; } - LogPrint(BCLog::COINJOIN, "DSSIGNFINALTX -- AddScriptSig() %d/%d success\n", nTxInIndex, nTxInsCount); + int nTxInIndex = 0; + int nTxInsCount = static_cast(vecTxIn.size()); + for (const auto& txin : vecTxIn) { + nTxInIndex++; + if (!AddScriptSig(txin)) { + LogPrint(BCLog::COINJOIN, "DSSIGNFINALTX -- AddScriptSig() failed at %d/%d, session: %d\n", nTxInIndex, + nTxInsCount, session_id); + RelayStatus(STATUS_REJECTED); + return; + } + LogPrint(BCLog::COINJOIN, "DSSIGNFINALTX -- AddScriptSig() %d/%d success\n", nTxInIndex, nTxInsCount); + } } // all is good CheckPool(); @@ -977,10 +990,9 @@ bool CCoinJoinServer::AddEntry(const CCoinJoinEntry& entry, PoolMessage& nMessag bool CCoinJoinServer::AddScriptSig(const CTxIn& txinNew) { - AssertLockNotHeld(cs_coinjoin); + AssertLockHeld(cs_coinjoin); LogPrint(BCLog::COINJOIN, "CCoinJoinServer::AddScriptSig -- scriptSig=%s\n", ScriptToAsmStr(txinNew.scriptSig).substr(0, 24)); - LOCK(cs_coinjoin); for (const auto& entry : vecEntries) { if (std::ranges::any_of(entry.vecTxDSIn, [&txinNew](const auto& txdsin) { return txdsin.scriptSig == txinNew.scriptSig; })) { diff --git a/src/coinjoin/server.h b/src/coinjoin/server.h index ff287d79bd50..d5abb3d218b7 100644 --- a/src/coinjoin/server.h +++ b/src/coinjoin/server.h @@ -147,7 +147,7 @@ class CCoinJoinServer : public CCoinJoinBaseSession, public NetHandler Mutex cs_check_pool; /// Add signature to a txin - bool AddScriptSig(const CTxIn& txin) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin); + bool AddScriptSig(const CTxIn& txin) EXCLUSIVE_LOCKS_REQUIRED(cs_coinjoin); /// Collaterals chosen to be charged whose consumption has not finished yet. They are chosen /// under cs_coinjoin, but ConsumeCollateral() takes cs_main and runs after cs_coinjoin is