From 4463055a5892f66b8abe861ad279e2a72ec96065 Mon Sep 17 00:00:00 2001 From: minuszka Date: Mon, 19 Oct 2026 22:32:25 +0200 Subject: [PATCH] wallet: guard CoinJoin client lifetime with scoped callbacks Keep each CoinJoin client alive while RPC, GUI and shutdown callbacks use it. Move mixing state to the wallet to avoid the keypool lock inversion, and initialize enable/autostart settings without restarting other wallets. Backport Dash Core #7259 (e118d0cdd8cbd807691e18b5e69f180ab8922165), adapted to this fork's wallet manager and existing RPC responses. Upstream authors: Konstantin Akimov, UdjinM6, PastaClaw and Pasta. Add lifetime, lock-order and initialization regressions, plus legacy and descriptor CoinJoin RPC coverage. --- src/coinjoin/client.cpp | 36 +++--- src/coinjoin/client.h | 14 ++- src/coinjoin/interfaces.cpp | 15 ++- src/dummywallet.cpp | 2 +- src/init.cpp | 1 - src/interfaces/coinjoin.h | 5 +- src/qt/bitcoingui.cpp | 2 +- src/qt/optionsdialog.cpp | 2 +- src/qt/overviewpage.cpp | 72 +++++++----- src/qt/walletmodel.cpp | 4 +- src/qt/walletmodel.h | 3 +- src/rpc/coinjoin.cpp | 62 ++++++----- src/wallet/init.cpp | 20 +--- src/wallet/test/coinjoin_tests.cpp | 170 +++++++++++++++++++++++++++-- src/wallet/wallet.cpp | 13 ++- src/wallet/wallet.h | 7 ++ src/walletinitinterface.h | 3 +- test/functional/rpc_coinjoin.py | 35 +++++- 18 files changed, 337 insertions(+), 129 deletions(-) diff --git a/src/coinjoin/client.cpp b/src/coinjoin/client.cpp index ea5fc4c4c1..bcc1f51784 100644 --- a/src/coinjoin/client.cpp +++ b/src/coinjoin/client.cpp @@ -246,17 +246,16 @@ void CCoinJoinClientSession::ProcessMessage(CNode& peer, CChainState& active_cha } bool CCoinJoinClientManager::StartMixing() { - bool expected{false}; - return fMixing.compare_exchange_strong(expected, true); + return m_wallet->StartMixing(); } void CCoinJoinClientManager::StopMixing() { - fMixing = false; + m_wallet->StopMixing(); } bool CCoinJoinClientManager::IsMixing() const { - return fMixing; + return m_wallet->IsMixing(); } void CCoinJoinClientSession::ResetPool() @@ -1905,7 +1904,10 @@ void CoinJoinWalletManager::Add(const std::shared_ptr& wallet) m_mn_sync, m_isman, m_queueman, m_is_masternode)); } - g_wallet_init_interface.InitCoinJoinSettings(*this); + if (!CCoinJoinClientOptions::IsEnabled()) return; + DoForClient(wallet->GetName(), [](CCoinJoinClientManager& manager) { + g_wallet_init_interface.InitCoinJoinSettings(manager); + }); } void CoinJoinWalletManager::DoMaintenance(CConnman& connman) @@ -1916,26 +1918,18 @@ void CoinJoinWalletManager::DoMaintenance(CConnman& connman) } } -void CoinJoinWalletManager::Remove(const std::string& name) { - { - LOCK(cs_wallet_manager_map); - m_wallet_manager_map.erase(name); - } - g_wallet_init_interface.InitCoinJoinSettings(*this); -} - -void CoinJoinWalletManager::Flush(const std::string& name) +void CoinJoinWalletManager::Remove(const std::string& name) { - auto clientman = Assert(Get(name)); - clientman->ResetPool(); - clientman->StopMixing(); + LOCK(cs_wallet_manager_map); + m_wallet_manager_map.erase(name); } -CCoinJoinClientManager* CoinJoinWalletManager::Get(const std::string& name) const +void CoinJoinWalletManager::Flush(const std::string& name) { - LOCK(cs_wallet_manager_map); - auto it = m_wallet_manager_map.find(name); - return (it != m_wallet_manager_map.end()) ? it->second.get() : nullptr; + DoForClient(name, [](CCoinJoinClientManager& manager) { + manager.ResetPool(); + manager.StopMixing(); + }); } CDeterministicMNCPtr CCoinJoinClientManager::GetRandomUsedMasternode() diff --git a/src/coinjoin/client.h b/src/coinjoin/client.h index 3d08595cfd..95c7ccab83 100644 --- a/src/coinjoin/client.h +++ b/src/coinjoin/client.h @@ -102,7 +102,17 @@ class CoinJoinWalletManager { void Remove(const std::string& name); void Flush(const std::string& name); - CCoinJoinClientManager* Get(const std::string& name) const; + //! Invoke func under the manager lock. The client must not escape func. + //! Return false without calling func when the wallet has been removed. + template + bool DoForClient(const std::string& name, Callable&& func) EXCLUSIVE_LOCKS_REQUIRED(!cs_wallet_manager_map) + { + LOCK(cs_wallet_manager_map); + const auto it = m_wallet_manager_map.find(name); + if (it == m_wallet_manager_map.end()) return false; + func(*it->second); + return true; + } template void ForEachCJClientMan(Callable&& func) @@ -283,8 +293,6 @@ class CCoinJoinClientManager // TODO: or map ?? std::deque deqSessions GUARDED_BY(cs_deqsessions); - std::atomic fMixing{false}; - int nCachedLastSuccessBlock{0}; int nMinBlocksToWait{1}; // how many blocks to wait for after one successful mixing tx in non-multisession mode bilingual_str strAutoDenomResult; diff --git a/src/coinjoin/interfaces.cpp b/src/coinjoin/interfaces.cpp index 6c40a3b6d3..06d47c0cc7 100644 --- a/src/coinjoin/interfaces.cpp +++ b/src/coinjoin/interfaces.cpp @@ -5,6 +5,8 @@ #include #include +#include +#include #include #include @@ -65,7 +67,10 @@ class CoinJoinLoaderImpl : public interfaces::CoinJoin::Loader public: explicit CoinJoinLoaderImpl(CoinJoinWalletManager& walletman) - : m_walletman(walletman) {} + : m_walletman(walletman) + { + CCoinJoinClientOptions::SetEnabled(gArgs.GetBoolArg("-enablecoinjoin", true)); + } void AddWallet(const std::shared_ptr& wallet) override { m_walletman.Add(wallet); } void RemoveWallet(const std::string& name) override @@ -76,10 +81,12 @@ class CoinJoinLoaderImpl : public interfaces::CoinJoin::Loader { m_walletman.Flush(name); } - std::unique_ptr GetClient(const std::string& name) override + bool WithClient(const std::string& name, const std::function& func) override { - auto clientman = m_walletman.Get(name); - return clientman ? std::make_unique(*clientman) : nullptr; + return m_walletman.DoForClient(name, [&](CCoinJoinClientManager& manager) { + CoinJoinClientImpl client{manager}; + func(client); + }); } CoinJoinWalletManager& walletman() override { diff --git a/src/dummywallet.cpp b/src/dummywallet.cpp index ad0d1c52d4..9b3a8a49a9 100644 --- a/src/dummywallet.cpp +++ b/src/dummywallet.cpp @@ -24,7 +24,7 @@ class DummyWalletInit : public WalletInitInterface { // Dash Specific WalletInitInterface InitCoinJoinSettings void AutoLockMasternodeCollaterals() const override {} - void InitCoinJoinSettings(const CoinJoinWalletManager& cjwalletman) const override {} + void InitCoinJoinSettings(CCoinJoinClientManager& manager) const override {} bool InitAutoBackup() const override {return true;} }; diff --git a/src/init.cpp b/src/init.cpp index 9ddc979c64..6fe26861b9 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -2063,7 +2063,6 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) #ifdef ENABLE_WALLET node.coinjoin_loader = interfaces::MakeCoinJoinLoader(*node.cj_ctx->walletman); - g_wallet_init_interface.InitCoinJoinSettings(*node.cj_ctx->walletman); #endif // ENABLE_WALLET // ********************************************************* Step 7d: Setup other Dash services diff --git a/src/interfaces/coinjoin.h b/src/interfaces/coinjoin.h index 7f881bf07f..13bd902ed4 100644 --- a/src/interfaces/coinjoin.h +++ b/src/interfaces/coinjoin.h @@ -5,6 +5,7 @@ #ifndef BITCOIN_INTERFACES_COINJOIN_H #define BITCOIN_INTERFACES_COINJOIN_H +#include #include #include @@ -37,7 +38,9 @@ class Loader //! Remove wallet from CoinJoin client manager virtual void RemoveWallet(const std::string&) = 0; virtual void FlushWallet(const std::string&) = 0; - virtual std::unique_ptr GetClient(const std::string&) = 0; + //! Invoke func while the named client is protected from concurrent removal. + //! References to the client must not escape the callback. + virtual bool WithClient(const std::string& name, const std::function& func) = 0; virtual CoinJoinWalletManager& walletman() = 0; }; } // namespace CoinJoin diff --git a/src/qt/bitcoingui.cpp b/src/qt/bitcoingui.cpp index b4a9111d08..24798c78d2 100644 --- a/src/qt/bitcoingui.cpp +++ b/src/qt/bitcoingui.cpp @@ -1901,7 +1901,7 @@ void BitcoinGUI::setNumBlocks(int count, const QDateTime& blockDate, const QStri #ifdef ENABLE_WALLET if (enableWallet) { for (const auto& wallet : m_node.walletLoader().getWallets()) { - disableAppNap |= m_node.coinJoinLoader()->GetClient(wallet->getWalletName())->isMixing(); + m_node.coinJoinLoader()->WithClient(wallet->getWalletName(), [&](auto& client) { disableAppNap |= client.isMixing(); }); } } #endif // ENABLE_WALLET diff --git a/src/qt/optionsdialog.cpp b/src/qt/optionsdialog.cpp index 22d8fbdc09..5bd5b20e26 100644 --- a/src/qt/optionsdialog.cpp +++ b/src/qt/optionsdialog.cpp @@ -422,7 +422,7 @@ void OptionsDialog::on_okButton_clicked() #ifdef ENABLE_WALLET if (m_enable_wallet) { for (auto& wallet : model->node().walletLoader().getWallets()) { - model->node().coinJoinLoader()->GetClient(wallet->getWalletName())->resetCachedBlocks(); + model->node().coinJoinLoader()->WithClient(wallet->getWalletName(), [](auto& client) { client.resetCachedBlocks(); }); wallet->markDirty(); } } diff --git a/src/qt/overviewpage.cpp b/src/qt/overviewpage.cpp index b1dca8952b..af9fc0a2e3 100644 --- a/src/qt/overviewpage.cpp +++ b/src/qt/overviewpage.cpp @@ -698,7 +698,7 @@ void OverviewPage::setWalletModel(WalletModel *model) // Disable coinJoinClient builtin support for automatic backups while we are in GUI, // we'll handle automatic backups and user warnings in coinJoinStatus() - walletModel->coinJoin()->disableAutobackups(); + walletModel->withCoinJoin([](auto& client) { client.disableAutobackups(); }); connect(ui->toggleCoinJoin, &QPushButton::clicked, this, &OverviewPage::toggleCoinJoin); @@ -918,7 +918,11 @@ void OverviewPage::coinJoinStatus(bool fForce) int nBestHeight = clientModel->node().getNumBlocks(); // We are processing more than 1 block per second, we'll just leave - if (nBestHeight > walletModel->coinJoin()->getCachedBlocks() && GetTime() - nLastDSProgressBlockTime <= 1) return; + bool tooFast{false}; + walletModel->withCoinJoin([&](auto& client) { + tooFast = nBestHeight > client.getCachedBlocks() && GetTime() - nLastDSProgressBlockTime <= 1; + }); + if (tooFast) return; nLastDSProgressBlockTime = GetTime(); QString strKeysLeftText(tr("keys left: %1").arg(walletModel->getKeysLeftSinceAutoBackup())); @@ -932,12 +936,17 @@ void OverviewPage::coinJoinStatus(bool fForce) ui->labelCoinJoinEnabled->setToolTip(strKeysLeftText); QString strCoinJoinName = QString::fromStdString(gCoinJoinName); - if (!walletModel->coinJoin()->isMixing()) { - if (nBestHeight != walletModel->coinJoin()->getCachedBlocks()) { - walletModel->coinJoin()->setCachedBlocks(nBestHeight); - updateCoinJoinProgress(); + bool notMixing{false}; + bool refreshProgress{false}; + walletModel->withCoinJoin([&](auto& client) { + notMixing = !client.isMixing(); + if (notMixing && nBestHeight != client.getCachedBlocks()) { + client.setCachedBlocks(nBestHeight); + refreshProgress = true; } - + }); + if (refreshProgress) updateCoinJoinProgress(); + if (notMixing) { setWidgetsVisible(false); ui->toggleCoinJoin->setText(tr("Start %1").arg(strCoinJoinName)); @@ -995,7 +1004,8 @@ void OverviewPage::coinJoinStatus(bool fForce) } } - QString strEnabled = walletModel->coinJoin()->isMixing() ? tr("Enabled") : tr("Disabled"); + QString strEnabled; + walletModel->withCoinJoin([&](auto& client) { strEnabled = client.isMixing() ? tr("Enabled") : tr("Disabled"); }); // Show how many keys left in advanced PS UI mode only if(fShowAdvancedCJUI && !strKeysLeftText.isEmpty()) strEnabled += ", " + strKeysLeftText; ui->labelCoinJoinEnabled->setText(strEnabled); @@ -1019,15 +1029,18 @@ void OverviewPage::coinJoinStatus(bool fForce) } // check coinjoin status and unlock if needed - if(nBestHeight != walletModel->coinJoin()->getCachedBlocks()) { - // Balance and number of transactions might have changed - walletModel->coinJoin()->setCachedBlocks(nBestHeight); - updateCoinJoinProgress(); - } + bool refreshProgressTail{false}; + walletModel->withCoinJoin([&](auto& client) { + if (nBestHeight != client.getCachedBlocks()) { + // Balance and number of transactions might have changed + client.setCachedBlocks(nBestHeight); + refreshProgressTail = true; + } + ui->labelSubmittedDenom->setText(m_privacy ? "####" : QString(client.getSessionDenoms().c_str())); + }); + if (refreshProgressTail) updateCoinJoinProgress(); setWidgetsVisible(true); - - ui->labelSubmittedDenom->setText(m_privacy ? "####" : QString(walletModel->coinJoin()->getSessionDenoms().c_str())); } void OverviewPage::toggleCoinJoin(){ @@ -1042,7 +1055,9 @@ void OverviewPage::toggleCoinJoin(){ settings.setValue("hasMixed", "hasMixed"); } - if (!walletModel->coinJoin()->isMixing()) { + bool mixing{false}; + walletModel->withCoinJoin([&](auto& client) { mixing = client.isMixing(); }); + if (!mixing) { auto& options = walletModel->node().coinJoinOptions(); const CAmount nMinAmount = options.getSmallestDenomination() + options.getMaxCollateralAmount(); if(m_balances.balance < nMinAmount) { @@ -1060,7 +1075,7 @@ void OverviewPage::toggleCoinJoin(){ if(!ctx.isValid()) { //unlock was cancelled - walletModel->coinJoin()->resetCachedBlocks(); + walletModel->withCoinJoin([](auto& client) { client.resetCachedBlocks(); }); QMessageBox::warning(this, strCoinJoinName, tr("Wallet is locked and user declined to unlock. Disabling %1.").arg(strCoinJoinName), QMessageBox::Ok, QMessageBox::Ok); @@ -1071,16 +1086,17 @@ void OverviewPage::toggleCoinJoin(){ } - walletModel->coinJoin()->resetCachedBlocks(); - - if (walletModel->coinJoin()->isMixing()) { - ui->toggleCoinJoin->setText(tr("Start %1").arg(strCoinJoinName)); - walletModel->coinJoin()->resetPool(); - walletModel->coinJoin()->stopMixing(); - } else { - ui->toggleCoinJoin->setText(tr("Stop %1").arg(strCoinJoinName)); - walletModel->coinJoin()->startMixing(); - } + walletModel->withCoinJoin([&](auto& client) { + client.resetCachedBlocks(); + if (client.isMixing()) { + ui->toggleCoinJoin->setText(tr("Start %1").arg(strCoinJoinName)); + client.resetPool(); + client.stopMixing(); + } else { + ui->toggleCoinJoin->setText(tr("Stop %1").arg(strCoinJoinName)); + client.startMixing(); + } + }); } void OverviewPage::SetupTransactionList(int nNumItems) @@ -1119,5 +1135,5 @@ void OverviewPage::DisableCoinJoinCompletely() if (nWalletBackups <= 0) { ui->labelCoinJoinEnabled->setText("(" + tr("Disabled") + ")"); } - walletModel->coinJoin()->stopMixing(); + walletModel->withCoinJoin([](auto& client) { client.stopMixing(); }); } diff --git a/src/qt/walletmodel.cpp b/src/qt/walletmodel.cpp index d4a88de83b..50e95377f6 100644 --- a/src/qt/walletmodel.cpp +++ b/src/qt/walletmodel.cpp @@ -82,9 +82,9 @@ void WalletModel::setClientModel(ClientModel* client_model) if (!m_client_model) timer->stop(); } -std::unique_ptr WalletModel::coinJoin() const +bool WalletModel::withCoinJoin(const std::function& func) const { - return m_node.coinJoinLoader()->GetClient(m_wallet->getWalletName()); + return m_node.coinJoinLoader()->WithClient(m_wallet->getWalletName(), func); } void WalletModel::updateStatus() diff --git a/src/qt/walletmodel.h b/src/qt/walletmodel.h index d15f65af91..dbd55a0f11 100644 --- a/src/qt/walletmodel.h +++ b/src/qt/walletmodel.h @@ -17,6 +17,7 @@ #include #include +#include #include #include @@ -150,7 +151,7 @@ class WalletModel : public QObject interfaces::Node& node() const { return m_node; } interfaces::Wallet& wallet() const { return *m_wallet; } void setClientModel(ClientModel* client_model); - std::unique_ptr coinJoin() const; + bool withCoinJoin(const std::function& func) const; QString getWalletName() const; QString getDisplayName() const; diff --git a/src/rpc/coinjoin.cpp b/src/rpc/coinjoin.cpp index e879ab3631..8babf2d390 100644 --- a/src/rpc/coinjoin.cpp +++ b/src/rpc/coinjoin.cpp @@ -84,8 +84,9 @@ static RPCHelpMan coinjoin_reset() ValidateCoinJoinArguments(); - auto cj_clientman = CHECK_NONFATAL(node.coinjoin_loader)->walletman().Get(wallet->GetName()); - CHECK_NONFATAL(cj_clientman)->ResetPool(); + CHECK_NONFATAL(CHECK_NONFATAL(node.coinjoin_loader)->walletman().DoForClient(wallet->GetName(), [](auto& manager) { + manager.ResetPool(); + })); return "Mixing was reset"; }, @@ -124,16 +125,18 @@ static RPCHelpMan coinjoin_start() throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please unlock wallet for mixing with walletpassphrase first."); } - auto cj_clientman = CHECK_NONFATAL(CHECK_NONFATAL(node.coinjoin_loader)->walletman().Get(wallet->GetName())); - if (!cj_clientman->StartMixing()) { - throw JSONRPCError(RPC_INTERNAL_ERROR, "Mixing has been started already."); - } - ChainstateManager& chainman = EnsureChainman(node); CTxMemPool& mempool = EnsureMemPool(node); CConnman& connman = EnsureConnman(node); - bool result = cj_clientman->DoAutomaticDenominating(chainman, connman, mempool); - return "Mixing " + (result ? "started successfully" : ("start failed: " + cj_clientman->GetStatuses().original + ", will retry")); + std::string response; + CHECK_NONFATAL(CHECK_NONFATAL(node.coinjoin_loader)->walletman().DoForClient(wallet->GetName(), [&](auto& manager) { + if (!manager.StartMixing()) { + throw JSONRPCError(RPC_INTERNAL_ERROR, "Mixing has been started already."); + } + const bool result = manager.DoAutomaticDenominating(chainman, connman, mempool); + response = "Mixing " + (result ? "started successfully" : ("start failed: " + manager.GetStatuses().original + ", will retry")); + })); + return response; }, }; } @@ -163,14 +166,12 @@ static RPCHelpMan coinjoin_stop() ValidateCoinJoinArguments(); - CHECK_NONFATAL(node.coinjoin_loader); - auto cj_clientman = node.coinjoin_loader->walletman().Get(wallet->GetName()); - - CHECK_NONFATAL(cj_clientman); - if (!cj_clientman->IsMixing()) { - throw JSONRPCError(RPC_INTERNAL_ERROR, "No mix session to stop"); - } - cj_clientman->StopMixing(); + CHECK_NONFATAL(CHECK_NONFATAL(node.coinjoin_loader)->walletman().DoForClient(wallet->GetName(), [](auto& manager) { + if (!manager.IsMixing()) { + throw JSONRPCError(RPC_INTERNAL_ERROR, "No mix session to stop"); + } + manager.StopMixing(); + })); return "Mixing was stopped"; }, @@ -234,11 +235,12 @@ static RPCHelpMan coinjoinsalt_generate() const NodeContext& node = EnsureAnyNodeContext(request.context); if (node.coinjoin_loader != nullptr) { - auto cj_clientman = node.coinjoin_loader->walletman().Get(wallet->GetName()); - if (cj_clientman != nullptr && cj_clientman->IsMixing()) { - throw JSONRPCError(RPC_WALLET_ERROR, - strprintf("Wallet \"%s\" is currently mixing, cannot change salt!", str_wallet)); - } + node.coinjoin_loader->walletman().DoForClient(wallet->GetName(), [&](auto& manager) { + if (manager.IsMixing()) { + throw JSONRPCError(RPC_WALLET_ERROR, + strprintf("Wallet \"%s\" is currently mixing, cannot change salt!", str_wallet)); + } + }); } const auto wallet_balance{wallet->GetBalance()}; @@ -336,11 +338,12 @@ static RPCHelpMan coinjoinsalt_set() const NodeContext& node = EnsureAnyNodeContext(request.context); if (node.coinjoin_loader != nullptr) { - auto cj_clientman = node.coinjoin_loader->walletman().Get(wallet->GetName()); - if (cj_clientman != nullptr && cj_clientman->IsMixing()) { - throw JSONRPCError(RPC_WALLET_ERROR, - strprintf("Wallet \"%s\" is currently mixing, cannot change salt!", str_wallet)); - } + node.coinjoin_loader->walletman().DoForClient(wallet->GetName(), [&](auto& manager) { + if (manager.IsMixing()) { + throw JSONRPCError(RPC_WALLET_ERROR, + strprintf("Wallet \"%s\" is currently mixing, cannot change salt!", str_wallet)); + } + }); } const auto wallet_balance{wallet->GetBalance()}; @@ -446,8 +449,9 @@ static RPCHelpMan getcoinjoininfo() return obj; } - auto* manager = CHECK_NONFATAL(node.coinjoin_loader->walletman().Get(wallet->GetName())); - manager->GetJsonInfo(obj); + CHECK_NONFATAL(CHECK_NONFATAL(node.coinjoin_loader)->walletman().DoForClient(wallet->GetName(), [&](auto& manager) { + manager.GetJsonInfo(obj); + })); std::string warning_msg{""}; if (wallet->IsLegacy()) { diff --git a/src/wallet/init.cpp b/src/wallet/init.cpp index 89bfbeab5a..f3661ceedc 100644 --- a/src/wallet/init.cpp +++ b/src/wallet/init.cpp @@ -46,7 +46,7 @@ class WalletInit : public WalletInitInterface // Dash Specific Wallet Init void AutoLockMasternodeCollaterals() const override; - void InitCoinJoinSettings(const CoinJoinWalletManager& cjwalletman) const override; + void InitCoinJoinSettings(CCoinJoinClientManager& manager) const override; bool InitAutoBackup() const override; }; @@ -204,22 +204,10 @@ void WalletInit::AutoLockMasternodeCollaterals() const } } -void WalletInit::InitCoinJoinSettings(const CoinJoinWalletManager& cjwalletman) const +void WalletInit::InitCoinJoinSettings(CCoinJoinClientManager& manager) const { - CCoinJoinClientOptions::SetEnabled(!GetWallets().empty() ? gArgs.GetBoolArg("-enablecoinjoin", true) : false); - if (!CCoinJoinClientOptions::IsEnabled()) { - return; - } - bool fAutoStart = gArgs.GetBoolArg("-coinjoinautostart", DEFAULT_COINJOIN_AUTOSTART); - for (auto& pwallet : GetWallets()) { - auto manager = cjwalletman.Get(pwallet->GetName()); - assert(manager != nullptr); - if (pwallet->IsLocked()) { - manager->StopMixing(); - } else if (fAutoStart) { - manager->StartMixing(); - } - } + const bool fAutoStart = gArgs.GetBoolArg("-coinjoinautostart", DEFAULT_COINJOIN_AUTOSTART); + if (fAutoStart) manager.StartMixing(); LogPrintf("CoinJoin: autostart=%d, multisession=%d," /* Continued */ "sessions=%d, rounds=%d, amount=%d, denoms_goal=%d, denoms_hardcap=%d\n", fAutoStart, CCoinJoinClientOptions::IsMultiSessionEnabled(), diff --git a/src/wallet/test/coinjoin_tests.cpp b/src/wallet/test/coinjoin_tests.cpp index 768d519767..567fd05cfd 100644 --- a/src/wallet/test/coinjoin_tests.cpp +++ b/src/wallet/test/coinjoin_tests.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -18,10 +19,19 @@ #include +#include +#include +#include +#include +#include + BOOST_FIXTURE_TEST_SUITE(coinjoin_tests, BasicTestingSetup) -BOOST_AUTO_TEST_CASE(coinjoin_options_tests) +BOOST_FIXTURE_TEST_CASE(coinjoin_options_tests, TestingSetup) { + gArgs.ForceSetArg("-enablecoinjoin", "0"); + const auto loader = interfaces::MakeCoinJoinLoader(*m_node.cj_ctx->walletman); + BOOST_CHECK_EQUAL(CCoinJoinClientOptions::GetSessions(), DEFAULT_COINJOIN_SESSIONS); BOOST_CHECK_EQUAL(CCoinJoinClientOptions::GetRounds(), DEFAULT_COINJOIN_ROUNDS); BOOST_CHECK_EQUAL(CCoinJoinClientOptions::GetRandomRounds(), COINJOIN_RANDOM_ROUNDS); @@ -211,16 +221,158 @@ class CTransactionBuilderTestSetup : public TestChain100Setup BOOST_FIXTURE_TEST_CASE(coinjoin_manager_start_stop_tests, CTransactionBuilderTestSetup) { - CCoinJoinClientManager* cj_man = m_node.cj_ctx->walletman->Get(""); - BOOST_REQUIRE(cj_man != nullptr); - BOOST_CHECK_EQUAL(cj_man->IsMixing(), false); - BOOST_CHECK_EQUAL(cj_man->StartMixing(), true); - BOOST_CHECK_EQUAL(cj_man->IsMixing(), true); - BOOST_CHECK_EQUAL(cj_man->StartMixing(), false); - cj_man->StopMixing(); - BOOST_CHECK_EQUAL(cj_man->IsMixing(), false); + BOOST_CHECK(m_node.cj_ctx->walletman->DoForClient("", [](auto& manager) { + BOOST_CHECK_EQUAL(manager.IsMixing(), false); + BOOST_CHECK_EQUAL(manager.StartMixing(), true); + BOOST_CHECK_EQUAL(manager.IsMixing(), true); + BOOST_CHECK_EQUAL(manager.StartMixing(), false); + manager.StopMixing(); + BOOST_CHECK_EQUAL(manager.IsMixing(), false); + })); +} + +static bool WithCoinJoinForTest(interfaces::CoinJoin::Loader& loader, const std::string& name, + const std::function& func) +{ + return loader.WithClient(name, func); +} + +BOOST_FIXTURE_TEST_CASE(coinjoin_callback_excludes_wallet_removal, CTransactionBuilderTestSetup) +{ + auto& loader = *m_node.coinjoin_loader; + std::promise entered; + auto entered_future = entered.get_future(); + std::promise removing; + auto removing_future = removing.get_future(); + std::promise removed; + auto removed_future = removed.get_future(); + std::thread remover([&] { + entered_future.wait(); + removing.set_value(); + try { + if (!RemoveWallet(wallet, std::nullopt)) throw std::runtime_error("wallet removal failed"); + removed.set_value(); + } catch (...) { + removed.set_exception(std::current_exception()); + } + }); + bool removed_during_callback{false}; + const bool visited = WithCoinJoinForTest(loader, "", [&](auto& client) { + entered.set_value(); + removing_future.wait(); + removed_during_callback = removed_future.wait_for(std::chrono::milliseconds{250}) == std::future_status::ready; + // Avoid touching the legacy dangling reference in the failing control. + if (!removed_during_callback) client.isMixing(); + }); + if (!visited) entered.set_value(); + remover.join(); + BOOST_CHECK(visited); + BOOST_CHECK_MESSAGE(!removed_during_callback, "wallet removal completed while the CoinJoin client was in use"); + BOOST_CHECK_NO_THROW(removed_future.get()); + bool called{false}; + BOOST_CHECK(!WithCoinJoinForTest(loader, "", [&](auto&) { called = true; })); + BOOST_CHECK(!called); +} + +BOOST_FIXTURE_TEST_CASE(coinjoin_callback_missing_and_exception, CTransactionBuilderTestSetup) +{ + auto& loader = *m_node.coinjoin_loader; + bool called{false}; + BOOST_CHECK(!WithCoinJoinForTest(loader, "missing", [&](auto&) { called = true; })); + BOOST_CHECK(!called); + BOOST_CHECK_THROW(WithCoinJoinForTest(loader, "", [](auto&) { throw std::runtime_error("callback error"); }), std::runtime_error); + BOOST_CHECK(WithCoinJoinForTest(loader, "", [&](auto&) { called = true; })); + BOOST_CHECK(called); +} + +BOOST_FIXTURE_TEST_CASE(coinjoin_newkeypool_lock_order, CTransactionBuilderTestSetup) +{ + // Establish the same map -> wallet order used by mixing maintenance before + // NewKeyPool invokes its callback while holding cs_wallet (Dash #7259). + m_node.cj_ctx->walletman->ForEachCJClientMan([&](auto& client) { + BOOST_REQUIRE(client->StartMixing()); + LOCK(wallet->cs_wallet); + BOOST_CHECK(!wallet->IsLocked()); + }); + { + LOCK(wallet->cs_wallet); + BOOST_REQUIRE(wallet->GetLegacyScriptPubKeyMan()->NewKeyPool()); + } + m_node.cj_ctx->walletman->ForEachCJClientMan([](auto& client) { + BOOST_CHECK(!client->IsMixing()); + }); } +BOOST_FIXTURE_TEST_CASE(coinjoin_locked_wallet_cannot_start, CTransactionBuilderTestSetup) +{ + auto locked_wallet = std::make_shared(m_node.chain.get(), m_node.coinjoin_loader.get(), + "coinjoin-locked", CreateDummyWalletDatabase()); + locked_wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS); + { + LOCK(locked_wallet->cs_wallet); + locked_wallet->SetupDescriptorScriptPubKeyMans(); + } + BOOST_REQUIRE(locked_wallet->EncryptWallet(SecureString{"coinjoin-test-passphrase"})); + BOOST_REQUIRE(locked_wallet->Lock()); + BOOST_REQUIRE(locked_wallet->IsLocked(/*fForMixing=*/true)); + BOOST_REQUIRE(AddWallet(locked_wallet)); + BOOST_CHECK(WithCoinJoinForTest(*m_node.coinjoin_loader, locked_wallet->GetName(), [](auto& client) { + BOOST_CHECK(!client.startMixing()); + BOOST_CHECK(!client.isMixing()); + })); + BOOST_CHECK(RemoveWallet(locked_wallet, std::nullopt)); +} + +BOOST_FIXTURE_TEST_CASE(coinjoin_wallet_add_preserves_disabled_option, CTransactionBuilderTestSetup) +{ + const bool enabled_before = CCoinJoinClientOptions::IsEnabled(); + CCoinJoinClientOptions::SetEnabled(false); + m_node.coinjoin_loader->AddWallet(wallet); + BOOST_CHECK(!CCoinJoinClientOptions::IsEnabled()); + CCoinJoinClientOptions::SetEnabled(enabled_before); +} + +BOOST_FIXTURE_TEST_CASE(coinjoin_loader_applies_enable_option, CTransactionBuilderTestSetup) +{ + const bool enabled_before = CCoinJoinClientOptions::IsEnabled(); + const bool had_arg = gArgs.IsArgSet("-enablecoinjoin"); + const std::string old_arg = gArgs.GetArg("-enablecoinjoin", ""); + CCoinJoinClientOptions::SetEnabled(false); + gArgs.ForceSetArg("-enablecoinjoin", "1"); + auto enabled_loader = interfaces::MakeCoinJoinLoader(*m_node.cj_ctx->walletman); + BOOST_CHECK(CCoinJoinClientOptions::IsEnabled()); + gArgs.ForceSetArg("-enablecoinjoin", "0"); + auto disabled_loader = interfaces::MakeCoinJoinLoader(*m_node.cj_ctx->walletman); + BOOST_CHECK(!CCoinJoinClientOptions::IsEnabled()); + if (had_arg) gArgs.ForceSetArg("-enablecoinjoin", old_arg); + else gArgs.ForceRemoveArg("-enablecoinjoin"); + CCoinJoinClientOptions::SetEnabled(enabled_before); +} + +BOOST_FIXTURE_TEST_CASE(coinjoin_autostart_only_initializes_added_wallet, CTransactionBuilderTestSetup) +{ + const bool had_arg = gArgs.IsArgSet("-coinjoinautostart"); + const std::string old_arg = gArgs.GetArg("-coinjoinautostart", ""); + const bool enabled_before = CCoinJoinClientOptions::IsEnabled(); + CCoinJoinClientOptions::SetEnabled(true); + gArgs.ForceSetArg("-coinjoinautostart", "1"); + auto added_wallet = std::make_shared(m_node.chain.get(), m_node.coinjoin_loader.get(), + "coinjoin-added", CreateDummyWalletDatabase()); + BOOST_REQUIRE(AddWallet(added_wallet)); + BOOST_CHECK(WithCoinJoinForTest(*m_node.coinjoin_loader, "", [](auto& client) { + BOOST_CHECK(!client.isMixing()); + })); + BOOST_CHECK(WithCoinJoinForTest(*m_node.coinjoin_loader, added_wallet->GetName(), [](auto& client) { + BOOST_CHECK(client.isMixing()); + })); + BOOST_CHECK(RemoveWallet(added_wallet, std::nullopt)); + BOOST_CHECK(WithCoinJoinForTest(*m_node.coinjoin_loader, "", [](auto& client) { + BOOST_CHECK(!client.isMixing()); + })); + if (had_arg) gArgs.ForceSetArg("-coinjoinautostart", old_arg); + else gArgs.ForceRemoveArg("-coinjoinautostart"); + CCoinJoinClientOptions::SetEnabled(enabled_before); +} BOOST_FIXTURE_TEST_CASE(CTransactionBuilderTest, CTransactionBuilderTestSetup) { diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index e51db0b2d1..e7be899bc0 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -1791,13 +1791,16 @@ void CWallet::UnsetBlankWalletFlag(WalletBatch& batch) UnsetWalletFlagWithDB(batch, WALLET_FLAG_BLANK_WALLET); } +bool CWallet::StartMixing() +{ + if (IsLocked(/*fForMixing=*/true)) return false; + bool expected{false}; + return m_mixing.compare_exchange_strong(expected, true); +} + void CWallet::NewKeyPoolCallback() { - // Note: GetClient(*this) can return nullptr when this wallet is in the middle of its creation. - // Skipping stopMixing() is fine in this case. - if (std::unique_ptr coinjoin_client = coinjoin_available() ? coinjoin_loader().GetClient(GetName()) : nullptr) { - coinjoin_client->stopMixing(); - } + StopMixing(); nKeysLeftSinceAutoBackup = 0; } diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index 85d3bc24b9..9a4758e9b8 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -789,6 +789,8 @@ class CWallet final : public WalletStorage, public interfaces::Chain::Notificati std::atomic fAbortRescan{false}; // reset by WalletRescanReserver::reserve() std::atomic fScanningWallet{false}; // controlled by WalletRescanReserver std::atomic m_attaching_chain{false}; + //! Transient CoinJoin state; stopping from NewKeyPool must not lock the client map. + std::atomic m_mixing{false}; std::atomic m_scanning_start{0}; std::atomic m_scanning_progress{0}; friend class WalletRescanReserver; @@ -986,6 +988,11 @@ class CWallet final : public WalletStorage, public interfaces::Chain::Notificati **/ bool SetCoinJoinSalt(const uint256& cj_salt); + //! Return false if already mixing or locked for mixing. + bool StartMixing(); + void StopMixing() { m_mixing = false; } + bool IsMixing() const { return m_mixing; } + // Map from governance object hash to governance object, they are added by gobject_prepare. std::map m_gobjects; diff --git a/src/walletinitinterface.h b/src/walletinitinterface.h index cb70b76bc6..dd84873981 100644 --- a/src/walletinitinterface.h +++ b/src/walletinitinterface.h @@ -7,6 +7,7 @@ class ArgsManager; class CoinJoinWalletManager; +class CCoinJoinClientManager; struct NodeContext; @@ -23,7 +24,7 @@ class WalletInitInterface { // Dash Specific WalletInitInterface virtual void AutoLockMasternodeCollaterals() const = 0; - virtual void InitCoinJoinSettings(const CoinJoinWalletManager& cjwalletman) const = 0; + virtual void InitCoinJoinSettings(CCoinJoinClientManager& manager) const = 0; virtual bool InitAutoBackup() const = 0; virtual ~WalletInitInterface() {} diff --git a/test/functional/rpc_coinjoin.py b/test/functional/rpc_coinjoin.py index 35ee13d5f5..b40826d6c3 100755 --- a/test/functional/rpc_coinjoin.py +++ b/test/functional/rpc_coinjoin.py @@ -7,32 +7,35 @@ from test_framework.test_framework import BitcoinTestFramework from test_framework.messages import ( - COIN, - MAX_MONEY, uint256_to_string, ) from test_framework.util import ( assert_equal, assert_is_hex_string, assert_raises_rpc_error, + force_finish_mnsync, ) # See coinjoin/options.h COINJOIN_ROUNDS_DEFAULT = 4 COINJOIN_ROUNDS_MAX = 16 COINJOIN_ROUNDS_MIN = 2 -COINJOIN_TARGET_MAX = int(MAX_MONEY / COIN) +COINJOIN_TARGET_MAX = 500_000_000 # src/coinjoin/options.h: MAX_MONEY / COIN COINJOIN_TARGET_MIN = 2 class CoinJoinTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 1 + # Keep automatic backups from stopping mixing before the keypool test. + self.extra_args = [['-keypool=200', '-createwalletbackups=10']] + if not self.options.descriptors: + self.extra_args[0].append('-usehd=0') def skip_test_if_missing_module(self): self.skip_if_no_wallet() def setup_nodes(self): - self.add_nodes(self.num_nodes) + self.add_nodes(self.num_nodes, self.extra_args) self.start_nodes() def run_test(self): @@ -47,6 +50,16 @@ def run_test(self): self.test_coinjoinsalt(w1) w1.unloadwallet() + if not self.options.descriptors: + node.createwallet(wallet_name='w_keypool', blank=False, disable_private_keys=False) + w_keypool = node.get_wallet_rpc('w_keypool') + self.generate(node, 2) + force_finish_mnsync(node) + self.test_newkeypool_stops_mixing(w_keypool) + w_keypool.unloadwallet() + else: + self.log.info('newkeypool is incompatible with descriptor wallets') + node.createwallet(wallet_name='w2', blank=True, disable_private_keys=True) w2 = node.get_wallet_rpc('w2') self.test_coinjoinsalt_disabled(w2) @@ -78,6 +91,18 @@ def test_coinjoin_start_stop(self, node): # Reset mix session assert_equal(node.coinjoin('reset'), "Mixing was reset") + def test_newkeypool_stops_mixing(self, node): + self.log.info('sethdseed keypool refresh should stop mixing without reversing the wallet/map lock order') + # The real mixing path holds the map and then cs_wallet. NewKeyPool + # calls its stop callback with cs_wallet held (Dash #7259). + with self.nodes[0].wait_for_debug_log([b'Not enough funds to mix.']): + node.coinjoin('start') + assert_equal(node.getcoinjoininfo()['running'], True) + # This fork has no standalone newkeypool RPC. Its existing sethdseed + # path calls NewKeyPool under cs_wallet and cs_KeyStore for a non-HD wallet. + node.sethdseed(True) + assert_equal(node.getcoinjoininfo()['running'], False) + def test_setcoinjoinamount(self, node): self.log.info('"setcoinjoinamount" should update mixing target') # Test normal and large values @@ -86,7 +111,7 @@ def test_setcoinjoinamount(self, node): assert_equal(node.getcoinjoininfo()['max_amount'], value) # Test values below minimum and above maximum for value in [COINJOIN_TARGET_MIN - 1, COINJOIN_TARGET_MAX + 1]: - assert_raises_rpc_error(-8, "Invalid amount of DASH as mixing goal amount", node.setcoinjoinamount, value) + assert_raises_rpc_error(-8, "Invalid amount of DFCN as mixing goal amount", node.setcoinjoinamount, value) def test_setcoinjoinrounds(self, node): self.log.info('"setcoinjoinrounds" should update mixing rounds')