Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/sv2-tp.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 5 additions & 3 deletions src/sv2/template_provider.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
8 changes: 8 additions & 0 deletions src/sv2/template_provider.h
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
12 changes: 9 additions & 3 deletions src/test/sv2_mock_mining.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -186,19 +186,25 @@ std::unique_ptr<interfaces::BlockTemplate> 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));
}
uint64_t seq = ++state->chain.template_seq;
return std::make_unique<MockBlockTemplate>(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<CTransactionRef> MockMining::getTransactionsByTxID(const std::vector<Txid>&) { return {}; }
Expand Down
2 changes: 2 additions & 0 deletions src/test/sv2_mock_mining.h
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ struct MockState {
std::vector<uint64_t> 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.
Expand Down
49 changes: 49 additions & 0 deletions src/test/sv2_tester_lifecycle_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,17 @@

#include <boost/test/unit_test.hpp>

#include <interfaces/mining.h>
#include <ipc/exception.h>
#include <sv2/block_options.h>
#include <sv2/template_provider.h>
#include <sync.h>
#include <test/sv2_mock_mining.h>
#include <test/sv2_test_setup.h> // Sv2BasicTestingSetup fixture
#include <test/sv2_tp_tester.h>

#include <chrono>
#include <future>
#include <memory>
#include <string_view>

Expand All @@ -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::milliseconds>(
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
Expand Down
51 changes: 37 additions & 14 deletions src/test/sv2_tp_tester.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include <interfaces/init.h>
#include <ipc/exception.h>
#include <mp/proxy-io.h>
#include <mp/util.h>
#include <src/ipc/capnp/init.capnp.h>
#include <src/ipc/capnp/init.capnp.proxy.h>
#include <sv2/messages.h>
Expand All @@ -23,8 +24,6 @@ extern std::function<void(const std::string&)> G_TEST_LOG_FUN;
#include <test/sv2_handshake_test_util.h>

#include <future>
#include <sys/socket.h>
#include <unistd.h>

namespace {
//! Simulates a node without getTransactionsByTxID(), by throwing the same
Expand Down Expand Up @@ -69,6 +68,8 @@ class OldNodeMining : public interfaces::Mining
std::unique_ptr<interfaces::Mining> m_mining;
};

} // namespace

struct MockInit : public interfaces::Init {
std::shared_ptr<MockState> state;
explicit MockInit(std::shared_ptr<MockState> s) : state(std::move(s)) {}
Expand All @@ -77,7 +78,6 @@ struct MockInit : public interfaces::Init {
return std::make_unique<MockMining>(state);
}
};
} // namespace

TPTester::TPTester() : TPTester(Sv2TemplateProviderOptions{.is_test = true}) {}

Expand All @@ -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<MockInit>(m_state);
MockInit& server_init = *m_server_init;
// Register server side on the event loop thread
m_loop->sync([&] {
mp::ServeStream<ipc::capnp::messages::Init>(
mp::Stream server_stream{mp::MakeStream(*m_loop, m_ipc_fds[0])};
m_server_connection = std::make_unique<mp::Connection>(
*m_loop,
mp::MakeStream(*m_loop, m_ipc_fds[0]),
*static_cast<MockInit*>(m_server_init.get()));
std::move(server_stream),
[&server_init](mp::Connection& connection) {
auto server_proxy = kj::heap<mp::ProxyServer<ipc::capnp::messages::Init>>(
std::shared_ptr<MockInit>(&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
Expand Down Expand Up @@ -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();
}

Expand Down
10 changes: 8 additions & 2 deletions src/test/sv2_tp_tester.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
#ifndef BITCOIN_TEST_SV2_TP_TESTER_H
#define BITCOIN_TEST_SV2_TP_TESTER_H

#include <mp/util.h>
#include <sv2/messages.h>
#include <sv2/template_provider.h>
#include <test/sv2_mock_mining.h>
#include <test/util/net.h>
#include <util/sock.h>

#include <array>
#include <cstdint>
#include <memory>
#include <thread>
Expand All @@ -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.
Expand All @@ -47,9 +52,10 @@ class TPTester {
// IPC loopback components
std::thread m_loop_thread;
mp::EventLoop* m_loop{nullptr};
std::unique_ptr<interfaces::Init> m_server_init;
std::unique_ptr<mp::Connection> m_server_connection;
std::unique_ptr<MockInit> m_server_init;
std::unique_ptr<interfaces::Init> m_client_init;
int m_ipc_fds[2]{-1, -1};
std::array<mp::SocketId, 2> m_ipc_fds{mp::SocketError, mp::SocketError};

public:
std::unique_ptr<Sv2TemplateProvider> m_tp; //!< Sv2TemplateProvider being tested
Expand Down
Loading