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 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) 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; 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 diff --git a/src/test/sv2_tp_tester.cpp b/src/test/sv2_tp_tester.cpp index 9e9a2038..44b5e148 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 @@ -69,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)) {} @@ -77,7 +78,6 @@ struct MockInit : public interfaces::Init { return std::make_unique(state); } }; -} // namespace TPTester::TPTester() : TPTester(Sv2TemplateProviderOptions{.is_test = true}) {} @@ -101,20 +101,23 @@ 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); + 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 @@ -142,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 9bd3877f..1875de88 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 @@ -19,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. @@ -47,9 +52,10 @@ 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; - 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