Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2023-present The Bitcoin Core developers2// Distributed under the MIT software license, see the accompanying3// file COPYING or http://www.opensource.org/licenses/mit-license.php.5#include <interfaces/init.h>6#include <ipc/capnp/mining.capnp.h>7#include <ipc/capnp/protocol.h>8#include <ipc/process.h>9#include <ipc/protocol.h>10#include <ipc/test/ipc_test.capnp.h>11#include <ipc/test/ipc_test.capnp.proxy.h>12#include <ipc/test/ipc_test.h>13#include <mp/proxy-types.h>14#include <test/util/common.h>15#include <test/util/setup_common.h>16#include <tinyformat.h>17#include <util/log.h>18#include <validation.h>20#include <future>21#include <thread>22#include <kj/common.h>23#include <kj/memory.h>24#include <kj/test.h>25#include <stdexcept>27#include <boost/test/unit_test.hpp>29static_assert(ipc::capnp::messages::MAX_MONEY == MAX_MONEY);30static_assert(ipc::capnp::messages::MAX_DOUBLE == std::numeric_limits<double>::max());31static_assert(ipc::capnp::messages::DEFAULT_BLOCK_RESERVED_WEIGHT == DEFAULT_BLOCK_RESERVED_WEIGHT);32static_assert(ipc::capnp::messages::DEFAULT_COINBASE_OUTPUT_MAX_ADDITIONAL_SIGOPS == DEFAULT_COINBASE_OUTPUT_MAX_ADDITIONAL_SIGOPS);34//! Remote init class.35class TestInit : public interfaces::Init36{37public:38std::unique_ptr<interfaces::Echo> makeEcho() override { return interfaces::MakeEcho(); }39};41//! Generate a temporary path with temp_directory_path and mkstemp42static std::string TempPath(std::string_view pattern)43{44std::string temp{fs::PathToString(fs::path{fs::temp_directory_path()} / fs::PathFromString(std::string{pattern}))};45temp.push_back('\0');46int fd{mkstemp(temp.data())};47BOOST_CHECK_GE(fd, 0);48BOOST_CHECK_EQUAL(close(fd), 0);49temp.resize(temp.size() - 1);50fs::remove(fs::PathFromString(temp));51return temp;52}54//! Unit test that tests execution of IPC calls without actually creating a55//! separate process. This test is primarily intended to verify behavior of type56//! conversion code that converts C++ objects to Cap'n Proto messages and vice57//! versa.58//!59//! The test creates a thread which creates a FooImplementation object (defined60//! in ipc_test.h) and a two-way pipe accepting IPC requests which call methods61//! on the object through FooInterface (defined in ipc_test.capnp).62void IpcPipeTest()63{64// Setup: create FooImplementation object and listen for FooInterface requests65std::promise<std::unique_ptr<mp::ProxyClient<gen::FooInterface>>> foo_promise;66std::thread thread([&]() {67mp::EventLoop loop("IpcPipeTest", [](bool raise, const std::string& log) { LogInfo("LOG%i: %s", raise, log); });68auto pipe = loop.m_io_context.provider->newTwoWayPipe();70auto connection_client = std::make_unique<mp::Connection>(loop, kj::mv(pipe.ends[0]));71auto foo_client = std::make_unique<mp::ProxyClient<gen::FooInterface>>(72connection_client->m_rpc_system->bootstrap(mp::ServerVatId().vat_id).castAs<gen::FooInterface>(),73connection_client.get(), /* destroy_connection= */ true);74(void)connection_client.release();75foo_promise.set_value(std::move(foo_client));77auto connection_server = std::make_unique<mp::Connection>(loop, kj::mv(pipe.ends[1]), [&](mp::Connection& connection) {78auto foo_server = kj::heap<mp::ProxyServer<gen::FooInterface>>(std::make_shared<FooImplementation>(), connection);79return capnp::Capability::Client(kj::mv(foo_server));80});81connection_server->onDisconnect([&] { connection_server.reset(); });82loop.loop();83});84std::unique_ptr<mp::ProxyClient<gen::FooInterface>> foo{foo_promise.get_future().get()};86// Test: make sure arguments were sent and return value is received87BOOST_CHECK_EQUAL(foo->add(1, 2), 3);89COutPoint txout1{Txid::FromUint256(uint256{100}), 200};90COutPoint txout2{foo->passOutPoint(txout1)};91BOOST_CHECK(txout1 == txout2);93UniValue uni1{UniValue::VOBJ};94uni1.pushKV("i", 1);95uni1.pushKV("s", "two");96UniValue uni2{foo->passUniValue(uni1)};97BOOST_CHECK_EQUAL(uni1.write(), uni2.write());99CMutableTransaction mtx;100mtx.version = 2;101mtx.nLockTime = 3;102mtx.vin.emplace_back(txout1);103mtx.vout.emplace_back(COIN, CScript());104CTransactionRef tx1{MakeTransactionRef(mtx)};105CTransactionRef tx2{foo->passTransaction(tx1)};106BOOST_CHECK(Assert(tx1)->Equals(*Assert(tx2)));108std::vector<CTransactionRef> txs1;109txs1.push_back(tx1);110txs1.push_back(nullptr);111std::vector<CTransactionRef> txs2(foo->passTransactions(txs1));112BOOST_CHECK_EQUAL(txs2.size(), 2);113BOOST_CHECK(Assert(txs1[0])->Equals(*Assert(txs2[0])));114BOOST_CHECK(!txs2[1]);116std::vector<char> vec1{'H', 'e', 'l', 'l', 'o'};117std::vector<char> vec2{foo->passVectorChar(vec1)};118BOOST_CHECK_EQUAL(std::string_view(vec1.begin(), vec1.end()), std::string_view(vec2.begin(), vec2.end()));120auto script1{CScript() << OP_11};121auto script2{foo->passScript(script1)};122BOOST_CHECK_EQUAL(HexStr(script1), HexStr(script2));124// Test cleanup: disconnect and join thread125foo.reset();126thread.join();127}129//! Test ipc::Protocol connect() and serve() methods connecting over a socketpair.130void IpcSocketPairTest()131{132std::unique_ptr<interfaces::Init> init{std::make_unique<TestInit>()};133std::unique_ptr<ipc::Protocol> protocol{ipc::capnp::MakeCapnpProtocol("IpcSocketPairTest")};134mp::Stream client_stream;135std::promise<void> promise;136std::thread thread([&]() {137protocol->serve(*init, [&] {138auto pair{mp::SocketPair()};139client_stream = protocol->makeStream(pair[0]);140promise.set_value();141return protocol->makeStream(pair[1]);142});143});144promise.get_future().wait();145std::unique_ptr<interfaces::Init> remote_init{protocol->connect(std::move(client_stream))};146std::unique_ptr<interfaces::Echo> remote_echo{remote_init->makeEcho()};147BOOST_CHECK_EQUAL(remote_echo->echo("echo test"), "echo test");148remote_echo.reset();149remote_init.reset();150thread.join();151}153//! Test ipc::Process bind() and connect() methods connecting over a unix socket.154void IpcSocketTest(const fs::path& datadir)155{156std::unique_ptr<interfaces::Init> init{std::make_unique<TestInit>()};157std::unique_ptr<ipc::Protocol> protocol{ipc::capnp::MakeCapnpProtocol("IpcSocketTest")};158std::unique_ptr<ipc::Process> process{ipc::MakeProcess()};160std::string invalid_bind{"invalid:"};161BOOST_CHECK_THROW(process->bind(datadir, "test_bitcoin", invalid_bind), std::invalid_argument);162BOOST_CHECK_THROW(process->connect(datadir, "test_bitcoin", invalid_bind), std::invalid_argument);164auto bind_and_listen{[&](const std::string& bind_address) {165std::string address{bind_address};166mp::SocketId serve_fd = process->bind(datadir, "test_bitcoin", address);167BOOST_CHECK_NE(serve_fd, mp::SocketError);168BOOST_CHECK_EQUAL(address, bind_address);169protocol->listen(serve_fd, *init);170}};172auto connect_and_test{[&](const std::string& connect_address) {173std::string address{connect_address};174mp::SocketId connect_fd{process->connect(datadir, "test_bitcoin", address)};175BOOST_CHECK_EQUAL(address, connect_address);176std::unique_ptr<interfaces::Init> remote_init{protocol->connect(protocol->makeStream(connect_fd))};177std::unique_ptr<interfaces::Echo> remote_echo{remote_init->makeEcho()};178BOOST_CHECK_EQUAL(remote_echo->echo("echo test"), "echo test");179}};181// Need to specify explicit socket addresses outside the data directory, because the data182// directory path is so long that the default socket address and any other183// addresses in the data directory would fail with errors like:184// Address 'unix' path '"/tmp/test_common_Bitcoin Core/ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff/test_bitcoin.sock"' exceeded maximum socket path length185std::vector<std::string> addresses{186strprintf("unix:%s", TempPath("bitcoin_sock0_XXXXXX")),187strprintf("unix:%s", TempPath("bitcoin_sock1_XXXXXX")),188};190// Bind and listen on multiple addresses191for (const auto& address : addresses) {192bind_and_listen(address);193}195// Connect and test each address multiple times.196for (int i : {0, 1, 0, 0, 1}) {197connect_and_test(addresses[i]);198}199}201BOOST_FIXTURE_TEST_SUITE(ipc_tests, BasicTestingSetup)202BOOST_AUTO_TEST_CASE(ipc_tests)203{204IpcPipeTest();205IpcSocketPairTest();206IpcSocketTest(m_args.GetDataDirNet());207}209// Test address parsing.210BOOST_AUTO_TEST_CASE(parse_address_test)211{212std::unique_ptr<ipc::Process> process{ipc::MakeProcess()};213fs::path datadir{"/var/empty/notexist"};214auto check_notexist{[](const std::system_error& e) { return e.code() == std::errc::no_such_file_or_directory; }};215auto check_address{[&](std::string address, std::string expect_address, std::string expect_error) {216if (expect_error.empty()) {217BOOST_CHECK_EXCEPTION(process->connect(datadir, "test_bitcoin", address), std::system_error, check_notexist);218} else {219BOOST_CHECK_EXCEPTION(process->connect(datadir, "test_bitcoin", address), std::invalid_argument, HasReason(expect_error));220}221BOOST_CHECK_EQUAL(address, expect_address);222}};223std::string prefix{fs::PathToString(datadir / "")};224check_address("unix", "unix:" + prefix + "test_bitcoin.sock", "");225check_address("unix:", "unix:" + prefix + "test_bitcoin.sock", "");226check_address("unix:path.sock", "unix:" + prefix + "path.sock", "");227check_address("unix:0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.sock",228"unix:" + prefix + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.sock",229"Unix address path \"" + prefix + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.sock\" exceeded maximum socket path length");230check_address("invalid", "invalid", "Unrecognized address 'invalid'");231}233BOOST_AUTO_TEST_SUITE_END()
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.