From b6523fd1e55d548e951871a947a6b0e5ebd03bd0 Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Thu, 23 Apr 2026 17:21:29 +0200 Subject: [PATCH 1/6] sv2: capture client id by value in handler thread launcher Avoid capturing a reference to the Sv2Client object in the lambda run by the per-client handler thread. The client iteration happens under ForEachClient and the reference would dangle if the client list mutates while the thread is running. Pass the id by value, as ThreadSv2ClientHandler takes a size_t anyway. --- src/sv2/template_provider.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/sv2/template_provider.cpp b/src/sv2/template_provider.cpp index a669e120..179a878f 100644 --- a/src/sv2/template_provider.cpp +++ b/src/sv2/template_provider.cpp @@ -269,10 +269,12 @@ void Sv2TemplateProvider::ThreadSv2Handler() if (client_threads.contains(client.m_id)) return; - client_threads.emplace(client.m_id, + const size_t client_id{client.m_id}; + + client_threads.emplace(client_id, std::thread(&util::TraceThread, - strprintf("sv2-%zu", client.m_id), - [this, &client] { ThreadSv2ClientHandler(client.m_id); })); + strprintf("sv2-%zu", client_id), + [this, client_id] { ThreadSv2ClientHandler(client_id); })); }); // Take a break (handling new connections is not urgent) From 43708363a7cd7a1ea9d2333de2365b0536fe1b27 Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Thu, 23 Apr 2026 17:21:45 +0200 Subject: [PATCH 2/6] sv2: expose an interrupt request without IPC Let tests set the shutdown flag before unblocking mock waitNext() calls, so the handler exits instead of issuing another IPC request. --- src/sv2/template_provider.h | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/sv2/template_provider.h b/src/sv2/template_provider.h index 3ff57efb..a47dc9ec 100644 --- a/src/sv2/template_provider.h +++ b/src/sv2/template_provider.h @@ -187,6 +187,14 @@ class Sv2TemplateProvider : public Sv2EventsInterface */ void ProcessSv2Message(const node::Sv2NetMsg& sv2_header, Sv2Client& client) EXCLUSIVE_LOCKS_REQUIRED(!m_tp_mutex); + /** + * Set the interrupt flag without performing any IPC. TPTester uses this + * before shutting down the mock directly, so handlers do not issue further + * IPC calls during teardown. Later Interrupt() calls return immediately; + * pending mining waits must be unblocked separately. + */ + void RequestInterrupt() noexcept { m_flag_interrupt_sv2 = true; } + // Only used for tests XOnlyPubKey m_authority_pubkey; From f7525090e39cd551e3a43a9ef2160835fc62480e Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Thu, 23 Apr 2026 17:21:51 +0200 Subject: [PATCH 3/6] test: implement MockMining::interrupt() Interrupt blocked createNewBlock() calls without affecting waitNext(), matching the node mining interface. Keep mining interruption separate from the direct mock shutdown used during fixture teardown. Test both interrupting template creation and stopping a client blocked in waitNext() through interruptWait() over IPC. The latter must finish well before the five-second template interval, without mock shutdown. --- src/test/sv2_mock_mining.cpp | 12 ++++-- src/test/sv2_mock_mining.h | 2 + src/test/sv2_tester_lifecycle_tests.cpp | 49 +++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 3 deletions(-) diff --git a/src/test/sv2_mock_mining.cpp b/src/test/sv2_mock_mining.cpp index 37fd0537..95798b57 100644 --- a/src/test/sv2_mock_mining.cpp +++ b/src/test/sv2_mock_mining.cpp @@ -186,11 +186,11 @@ std::unique_ptr MockMining::createNewBlock(const node state->cv.notify_all(); // Bound the pause so a failing test can't leave fixture teardown waiting forever. if (!state->cv.wait_for(lock, std::chrono::seconds{5}, [&]() EXCLUSIVE_LOCKS_REQUIRED(state->m) { - return state->shutdown || !state->pause_create; + return state->shutdown || state->mining_interrupted || !state->pause_create; })) { throw std::runtime_error("createNewBlock pause timed out"); } - if (state->shutdown) return nullptr; + if (state->shutdown || state->mining_interrupted) return nullptr; if (state->max_reserved_weight && options.block_reserved_weight > state->max_reserved_weight) { throw std::runtime_error(strprintf("block_reserved_weight (%d) exceeds block_max_weight (%d)", options.block_reserved_weight, state->max_reserved_weight)); @@ -198,7 +198,13 @@ std::unique_ptr MockMining::createNewBlock(const node uint64_t seq = ++state->chain.template_seq; return std::make_unique(state, state->chain.prev_hash, state->txs, seq, state->chain.pending_fee_sum); } -void MockMining::interrupt() { LogPrintLevel(BCLog::SV2, BCLog::Level::Trace, "mock interrupt()"); } +void MockMining::interrupt() +{ + LogPrintLevel(BCLog::SV2, BCLog::Level::Trace, "mock interrupt()"); + LOCK(state->m); + state->mining_interrupted = true; + state->cv.notify_all(); +} bool MockMining::checkBlock(const CBlock&, const node::BlockCheckOptions&, std::string&, std::string&) { return true; } bool MockMining::submitBlock(const CBlock&, std::string&, std::string&) { return true; } std::vector MockMining::getTransactionsByTxID(const std::vector&) { return {}; } diff --git a/src/test/sv2_mock_mining.h b/src/test/sv2_mock_mining.h index 6b104d9b..106ca0e0 100644 --- a/src/test/sv2_mock_mining.h +++ b/src/test/sv2_mock_mining.h @@ -57,6 +57,8 @@ struct MockState { std::vector create_weights GUARDED_BY(m); //! Pause createNewBlock() after recording its options, until resumed or shut down. bool pause_create GUARDED_BY(m){false}; + //! Mining::interrupt() cancels template creation, but not waitNext(). + bool mining_interrupted GUARDED_BY(m){false}; //! Make waitNext() throw, e.g. to simulate a failed IPC call. Protected by //! m, but not GUARDED_BY(m) because waitNext() waits on a std::unique_lock, //! like for shutdown below. diff --git a/src/test/sv2_tester_lifecycle_tests.cpp b/src/test/sv2_tester_lifecycle_tests.cpp index 8fe5065b..e381625d 100644 --- a/src/test/sv2_tester_lifecycle_tests.cpp +++ b/src/test/sv2_tester_lifecycle_tests.cpp @@ -4,12 +4,17 @@ #include +#include #include +#include +#include +#include #include #include // Sv2BasicTestingSetup fixture #include #include +#include #include #include @@ -33,6 +38,50 @@ BOOST_AUTO_TEST_CASE(ipc_failure_reaches_caller) BOOST_CHECK(!tester.m_mining_proxy->getTip().has_value()); } +BOOST_AUTO_TEST_CASE(mining_interrupt_unblocks_template_creation) +{ + TPTester tester{}; + tester.m_mining_control->PauseCreate(true); + auto create{std::async(std::launch::async, [&] { + return tester.m_mining_proxy->createNewBlock(node::BlockCreateOptions{}); + })}; + BOOST_REQUIRE(tester.m_mining_control->WaitForCreateCalls(1)); + + tester.m_mining_proxy->interrupt(); + BOOST_CHECK(create.wait_for(std::chrono::milliseconds{1500}) == std::future_status::ready); + BOOST_CHECK(!create.get()); + // Mining interruption is distinct from node shutdown. + LOCK(tester.m_state->m); + BOOST_CHECK(!tester.m_state->shutdown); +} + +BOOST_AUTO_TEST_CASE(tp_interrupt_unblocks_wait_next) +{ + Sv2TemplateProviderOptions opts; + opts.is_test = false; + opts.template_interval = std::chrono::seconds{5}; + TPTester tester{opts}; + tester.handshake(); + tester.SendSetupConnection(); + tester.SendCoinbaseOutputConstraints(); + tester.ReceiveTemplatePair(); + BOOST_REQUIRE(tester.m_mining_control->WaitForWaitNext()); + + // Exercise interruptWait() over IPC before fixture teardown can unblock + // waitNext() through the direct mock shutdown. Mining::interrupt() alone + // must not release this wait. + const auto interrupt_start{std::chrono::steady_clock::now()}; + tester.m_tp->Interrupt(); + tester.m_tp->StopThreads(); + const auto interrupt_elapsed_ms{std::chrono::duration_cast( + std::chrono::steady_clock::now() - interrupt_start).count()}; + BOOST_CHECK_MESSAGE(interrupt_elapsed_ms < 1500, "Interrupting waitNext() took " << interrupt_elapsed_ms << "ms"); + LOCK(tester.m_state->m); + BOOST_CHECK(!tester.m_state->shutdown); + BOOST_CHECK_EQUAL(tester.m_state->wait_next_waiters, 0); + BOOST_CHECK_GT(tester.m_state->wait_interrupt_generation, 0U); +} + BOOST_AUTO_TEST_CASE(tp_tester_repeated_construction) { // Run a few iterations; keep count modest to stay fast in CI while From fc2b0ffe5e923a3982e44d0e830469a6baeae7c3 Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Thu, 23 Apr 2026 17:23:37 +0200 Subject: [PATCH 4/6] test: portable IPC socketpair in sv2 TPTester Replace the Unix-only socketpair() setup in TPTester with mp::SocketPair(), and store the socket ids in a small std::array initialised with mp::SocketError so the code is valid when SocketId is an unsigned type (as on Windows). Drops / from the test harness. --- src/test/sv2_tp_tester.cpp | 9 ++------- src/test/sv2_tp_tester.h | 4 +++- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/src/test/sv2_tp_tester.cpp b/src/test/sv2_tp_tester.cpp index 9e9a2038..eeb051e7 100644 --- a/src/test/sv2_tp_tester.cpp +++ b/src/test/sv2_tp_tester.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -23,8 +24,6 @@ extern std::function G_TEST_LOG_FUN; #include #include -#include -#include namespace { //! Simulates a node without getTransactionsByTxID(), by throwing the same @@ -101,11 +100,7 @@ TPTester::TPTester(Sv2TemplateProviderOptions opts, MockNodeVersion version) loop_ready.get_future().wait(); // Create socketpair for in-process IPC stream - int fds[2]; - int rc = ::socketpair(AF_UNIX, SOCK_STREAM, 0, fds); - BOOST_REQUIRE_EQUAL(rc, 0); - m_ipc_fds[0] = fds[0]; - m_ipc_fds[1] = fds[1]; + m_ipc_fds = mp::SocketPair(); // Create server Init exposing MockMining via shared state m_server_init = std::make_unique(m_state); diff --git a/src/test/sv2_tp_tester.h b/src/test/sv2_tp_tester.h index 9bd3877f..00538177 100644 --- a/src/test/sv2_tp_tester.h +++ b/src/test/sv2_tp_tester.h @@ -5,12 +5,14 @@ #ifndef BITCOIN_TEST_SV2_TP_TESTER_H #define BITCOIN_TEST_SV2_TP_TESTER_H +#include #include #include #include #include #include +#include #include #include #include @@ -49,7 +51,7 @@ class TPTester { mp::EventLoop* m_loop{nullptr}; std::unique_ptr m_server_init; std::unique_ptr m_client_init; - int m_ipc_fds[2]{-1, -1}; + std::array m_ipc_fds{mp::SocketError, mp::SocketError}; public: std::unique_ptr m_tp; //!< Sv2TemplateProvider being tested From 4eb72c1cc14a508c0ac6cf1b6a8ca87f432dd5ad Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Thu, 23 Apr 2026 17:24:41 +0200 Subject: [PATCH 5/6] test: rework TPTester teardown via explicit IPC connection Stop the handler before releasing its IPC proxies, and hold the server connection explicitly so teardown can destroy it on the event loop. This avoids depending on socket disconnects to release the loop. Keep all server connection access on the event-loop thread, including the reset after a disconnect may already have destroyed it. --- src/test/sv2_tp_tester.cpp | 42 +++++++++++++++++++++++++++++++------- src/test/sv2_tp_tester.h | 6 +++++- 2 files changed, 40 insertions(+), 8 deletions(-) diff --git a/src/test/sv2_tp_tester.cpp b/src/test/sv2_tp_tester.cpp index eeb051e7..44b5e148 100644 --- a/src/test/sv2_tp_tester.cpp +++ b/src/test/sv2_tp_tester.cpp @@ -68,6 +68,8 @@ class OldNodeMining : public interfaces::Mining std::unique_ptr m_mining; }; +} // namespace + struct MockInit : public interfaces::Init { std::shared_ptr state; explicit MockInit(std::shared_ptr s) : state(std::move(s)) {} @@ -76,7 +78,6 @@ struct MockInit : public interfaces::Init { return std::make_unique(state); } }; -} // namespace TPTester::TPTester() : TPTester(Sv2TemplateProviderOptions{.is_test = true}) {} @@ -104,12 +105,19 @@ TPTester::TPTester(Sv2TemplateProviderOptions opts, MockNodeVersion version) // Create server Init exposing MockMining via shared state m_server_init = std::make_unique(m_state); + MockInit& server_init = *m_server_init; // Register server side on the event loop thread m_loop->sync([&] { - mp::ServeStream( + mp::Stream server_stream{mp::MakeStream(*m_loop, m_ipc_fds[0])}; + m_server_connection = std::make_unique( *m_loop, - mp::MakeStream(*m_loop, m_ipc_fds[0]), - *static_cast(m_server_init.get())); + std::move(server_stream), + [&server_init](mp::Connection& connection) { + auto server_proxy = kj::heap>( + std::shared_ptr(&server_init, [](MockInit*) {}), connection); + return capnp::Capability::Client(kj::mv(server_proxy)); + }); + m_server_connection->onDisconnect([this] { m_server_connection.reset(); }); }); // Connect client side and fetch Mining proxy @@ -137,22 +145,42 @@ TPTester::TPTester(Sv2TemplateProviderOptions opts, MockNodeVersion version) TPTester::~TPTester() { + // Set the interrupt flag before unblocking waitNext(), so the handler + // exits instead of issuing another IPC request during teardown. + if (m_tp) { + m_tp->RequestInterrupt(); + } + + // Signal the mock state directly (bypasses IPC) so that any + // MockBlockTemplate::waitNext() blocked on a server worker thread + // returns immediately. + m_mining_control->Shutdown(); + + // Wait for the handler thread before releasing its IPC proxies. + if (m_tp) { + m_tp->StopThreads(); + } + // Hold a loop ref while tearing down dependent objects to keep loop alive. if (m_loop) { mp::EventLoopRef loop_ref{*m_loop}; - // Destroy objects that may post work to the loop while the loop is guaranteed alive. m_tp.reset(); m_mining_proxy.reset(); m_client_init.reset(); - // Server init can go after clients; it only owns exported capabilities. + + // Process pending release/disconnect messages, then destroy the server + // connection on the event-loop thread before releasing the final loop ref. + m_loop->sync([] {}); + m_loop->sync([this] { m_server_connection.reset(); }); + m_server_init.reset(); } else { + m_server_connection.reset(); m_tp.reset(); m_mining_proxy.reset(); m_client_init.reset(); m_server_init.reset(); } - // Join loop thread (loop exits automatically when refs & connections reach zero). if (m_loop_thread.joinable()) m_loop_thread.join(); } diff --git a/src/test/sv2_tp_tester.h b/src/test/sv2_tp_tester.h index 00538177..1875de88 100644 --- a/src/test/sv2_tp_tester.h +++ b/src/test/sv2_tp_tester.h @@ -21,8 +21,11 @@ // Forward declarations class Sv2Transport; namespace mp { class EventLoop; } +namespace mp { class Connection; } namespace interfaces { class Init; class Mining; } +struct MockInit; + //! Which version of the mining interface the simulated node has. Methods that //! it does not have throw, like they do when the IPC layer finds that the //! other side does not implement them. @@ -49,7 +52,8 @@ class TPTester { // IPC loopback components std::thread m_loop_thread; mp::EventLoop* m_loop{nullptr}; - std::unique_ptr m_server_init; + std::unique_ptr m_server_connection; + std::unique_ptr m_server_init; std::unique_ptr m_client_init; std::array m_ipc_fds{mp::SocketError, mp::SocketError}; From 42feb835e1ffe648c42e2fea67d7fe04b66ab3f5 Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Fri, 21 Aug 2026 18:58:39 +0200 Subject: [PATCH 6/6] sv2: initialize networking before opening sockets Call SetupNetworking() from sv2-tp's own entry point. On Windows this initializes Winsock for both IPC and SV2 sockets; on Unix it is a no-op. --- src/sv2-tp.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/sv2-tp.cpp b/src/sv2-tp.cpp index 3aa9eb9d..d07462ac 100644 --- a/src/sv2-tp.cpp +++ b/src/sv2-tp.cpp @@ -180,6 +180,10 @@ MAIN_FUNCTION tfm::format(std::cerr, "Error: Specified data directory \"%s\" does not exist.\n", args.GetArg("-datadir", "")); return EXIT_FAILURE; } + if (!SetupNetworking()) { + tfm::format(std::cerr, "Error: Initializing networking failed\n"); + return EXIT_FAILURE; + } SelectParams(args.GetChainType()); // Set logging options using sv2-tp defaults