Bitcoin Core 32.1.0
P2P Digital Currency
Loading...
Searching...
No Matches
ipc_tests.cpp
Go to the documentation of this file.
1// Copyright (c) 2023-present The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#include <interfaces/init.h>
6#include <ipc/capnp/mining.capnp.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>
16#include <tinyformat.h>
17#include <util/log.h>
18#include <validation.h>
19
20#include <future>
21#include <thread>
22#include <kj/common.h>
23#include <kj/memory.h>
24#include <kj/test.h>
25#include <stdexcept>
26
27#include <boost/test/unit_test.hpp>
28
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);
33
36{
37public:
38 std::unique_ptr<interfaces::Echo> makeEcho() override { return interfaces::MakeEcho(); }
39};
40
42static std::string TempPath(std::string_view pattern)
43{
44 std::string temp{fs::PathToString(fs::path{fs::temp_directory_path()} / fs::PathFromString(std::string{pattern}))};
45 temp.push_back('\0');
46 int fd{mkstemp(temp.data())};
47 BOOST_CHECK_GE(fd, 0);
48 BOOST_CHECK_EQUAL(close(fd), 0);
49 temp.resize(temp.size() - 1);
50 fs::remove(fs::PathFromString(temp));
51 return temp;
52}
53
63{
64 // Setup: create FooImplementation object and listen for FooInterface requests
65 std::promise<std::unique_ptr<mp::ProxyClient<gen::FooInterface>>> foo_promise;
66 std::thread thread([&]() {
67 mp::EventLoop loop("IpcPipeTest", [](bool raise, const std::string& log) { LogInfo("LOG%i: %s", raise, log); });
68 auto pipe = loop.m_io_context.provider->newTwoWayPipe();
69
70 auto connection_client = std::make_unique<mp::Connection>(loop, kj::mv(pipe.ends[0]));
71 auto foo_client = std::make_unique<mp::ProxyClient<gen::FooInterface>>(
72 connection_client->m_rpc_system->bootstrap(mp::ServerVatId().vat_id).castAs<gen::FooInterface>(),
73 connection_client.get(), /* destroy_connection= */ true);
74 (void)connection_client.release();
75 foo_promise.set_value(std::move(foo_client));
76
77 auto connection_server = std::make_unique<mp::Connection>(loop, kj::mv(pipe.ends[1]), [&](mp::Connection& connection) {
78 auto foo_server = kj::heap<mp::ProxyServer<gen::FooInterface>>(std::make_shared<FooImplementation>(), connection);
79 return capnp::Capability::Client(kj::mv(foo_server));
80 });
81 connection_server->onDisconnect([&] { connection_server.reset(); });
82 loop.loop();
83 });
84 std::unique_ptr<mp::ProxyClient<gen::FooInterface>> foo{foo_promise.get_future().get()};
85
86 // Test: make sure arguments were sent and return value is received
87 BOOST_CHECK_EQUAL(foo->add(1, 2), 3);
88
89 COutPoint txout1{Txid::FromUint256(uint256{100}), 200};
90 COutPoint txout2{foo->passOutPoint(txout1)};
91 BOOST_CHECK(txout1 == txout2);
92
94 uni1.pushKV("i", 1);
95 uni1.pushKV("s", "two");
96 UniValue uni2{foo->passUniValue(uni1)};
97 BOOST_CHECK_EQUAL(uni1.write(), uni2.write());
98
100 mtx.version = 2;
101 mtx.nLockTime = 3;
102 mtx.vin.emplace_back(txout1);
103 mtx.vout.emplace_back(COIN, CScript());
104 CTransactionRef tx1{MakeTransactionRef(mtx)};
105 CTransactionRef tx2{foo->passTransaction(tx1)};
106 BOOST_CHECK(Assert(tx1)->Equals(*Assert(tx2)));
107
108 std::vector<CTransactionRef> txs1;
109 txs1.push_back(tx1);
110 txs1.push_back(nullptr);
111 std::vector<CTransactionRef> txs2(foo->passTransactions(txs1));
112 BOOST_CHECK_EQUAL(txs2.size(), 2);
113 BOOST_CHECK(Assert(txs1[0])->Equals(*Assert(txs2[0])));
114 BOOST_CHECK(!txs2[1]);
115
116 std::vector<char> vec1{'H', 'e', 'l', 'l', 'o'};
117 std::vector<char> vec2{foo->passVectorChar(vec1)};
118 BOOST_CHECK_EQUAL(std::string_view(vec1.begin(), vec1.end()), std::string_view(vec2.begin(), vec2.end()));
119
120 auto script1{CScript() << OP_11};
121 auto script2{foo->passScript(script1)};
122 BOOST_CHECK_EQUAL(HexStr(script1), HexStr(script2));
123
124 // Test cleanup: disconnect and join thread
125 foo.reset();
126 thread.join();
127}
128
131{
132 std::unique_ptr<interfaces::Init> init{std::make_unique<TestInit>()};
133 std::unique_ptr<ipc::Protocol> protocol{ipc::capnp::MakeCapnpProtocol("IpcSocketPairTest")};
134 mp::Stream client_stream;
135 std::promise<void> promise;
136 std::thread thread([&]() {
137 protocol->serve(*init, [&] {
138 auto pair{mp::SocketPair()};
139 client_stream = protocol->makeStream(pair[0]);
140 promise.set_value();
141 return protocol->makeStream(pair[1]);
142 });
143 });
144 promise.get_future().wait();
145 std::unique_ptr<interfaces::Init> remote_init{protocol->connect(std::move(client_stream))};
146 std::unique_ptr<interfaces::Echo> remote_echo{remote_init->makeEcho()};
147 BOOST_CHECK_EQUAL(remote_echo->echo("echo test"), "echo test");
148 remote_echo.reset();
149 remote_init.reset();
150 thread.join();
151}
152
154void IpcSocketTest(const fs::path& datadir)
155{
156 std::unique_ptr<interfaces::Init> init{std::make_unique<TestInit>()};
157 std::unique_ptr<ipc::Protocol> protocol{ipc::capnp::MakeCapnpProtocol("IpcSocketTest")};
158 std::unique_ptr<ipc::Process> process{ipc::MakeProcess()};
159
160 std::string invalid_bind{"invalid:"};
161 BOOST_CHECK_THROW(process->bind(datadir, "test_bitcoin", invalid_bind), std::invalid_argument);
162 BOOST_CHECK_THROW(process->connect(datadir, "test_bitcoin", invalid_bind), std::invalid_argument);
163
164 auto bind_and_listen{[&](const std::string& bind_address) {
165 std::string address{bind_address};
166 mp::SocketId serve_fd = process->bind(datadir, "test_bitcoin", address);
168 BOOST_CHECK_EQUAL(address, bind_address);
169 protocol->listen(serve_fd, *init);
170 }};
171
172 auto connect_and_test{[&](const std::string& connect_address) {
173 std::string address{connect_address};
174 mp::SocketId connect_fd{process->connect(datadir, "test_bitcoin", address)};
175 BOOST_CHECK_EQUAL(address, connect_address);
176 std::unique_ptr<interfaces::Init> remote_init{protocol->connect(protocol->makeStream(connect_fd))};
177 std::unique_ptr<interfaces::Echo> remote_echo{remote_init->makeEcho()};
178 BOOST_CHECK_EQUAL(remote_echo->echo("echo test"), "echo test");
179 }};
180
181 // Need to specify explicit socket addresses outside the data directory, because the data
182 // directory path is so long that the default socket address and any other
183 // 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 length
185 std::vector<std::string> addresses{
186 strprintf("unix:%s", TempPath("bitcoin_sock0_XXXXXX")),
187 strprintf("unix:%s", TempPath("bitcoin_sock1_XXXXXX")),
188 };
189
190 // Bind and listen on multiple addresses
191 for (const auto& address : addresses) {
192 bind_and_listen(address);
193 }
194
195 // Connect and test each address multiple times.
196 for (int i : {0, 1, 0, 0, 1}) {
197 connect_and_test(addresses[i]);
198 }
199}
200
203{
204 IpcPipeTest();
206 IpcSocketTest(m_args.GetDataDirNet());
207}
208
209// Test address parsing.
210BOOST_AUTO_TEST_CASE(parse_address_test)
211{
212 std::unique_ptr<ipc::Process> process{ipc::MakeProcess()};
213 fs::path datadir{"/var/empty/notexist"};
214 auto check_notexist{[](const std::system_error& e) { return e.code() == std::errc::no_such_file_or_directory; }};
215 auto check_address{[&](std::string address, std::string expect_address, std::string expect_error) {
216 if (expect_error.empty()) {
217 BOOST_CHECK_EXCEPTION(process->connect(datadir, "test_bitcoin", address), std::system_error, check_notexist);
218 } else {
219 BOOST_CHECK_EXCEPTION(process->connect(datadir, "test_bitcoin", address), std::invalid_argument, HasReason(expect_error));
220 }
221 BOOST_CHECK_EQUAL(address, expect_address);
222 }};
223 std::string prefix{fs::PathToString(datadir / "")};
224 check_address("unix", "unix:" + prefix + "test_bitcoin.sock", "");
225 check_address("unix:", "unix:" + prefix + "test_bitcoin.sock", "");
226 check_address("unix:path.sock", "unix:" + prefix + "path.sock", "");
227 check_address("unix:0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.sock",
228 "unix:" + prefix + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.sock",
229 "Unix address path \"" + prefix + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.sock\" exceeded maximum socket path length");
230 check_address("invalid", "invalid", "Unrecognized address 'invalid'");
231}
232
constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition amount.h:26
constexpr CAmount COIN
The amount of satoshis in one BTC.
Definition amount.h:15
#define Assert(val)
Identity function.
Definition check.h:116
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition transaction.h:30
CScript()=default
BOOST_CHECK_EXCEPTION predicates to check the specific validation error.
Definition common.h:19
TestInit(NodeContext &node)
std::unique_ptr< interfaces::Echo > makeEcho() override
Definition ipc_tests.cpp:38
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
void pushKV(std::string key, UniValue val)
Definition univalue.cpp:125
kj::AsyncIoContext m_io_context
Capnp IO context.
Definition proxy-io.h:334
static transaction_identifier FromUint256(const uint256 &id)
256-bit opaque blob.
Definition uint256.h:196
BOOST_FIXTURE_TEST_SUITE(cuckoocache_tests, BasicTestingSetup)
Test Suite for CuckooCache.
BOOST_AUTO_TEST_SUITE_END()
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition hex_base.cpp:30
BOOST_CHECK_EXCEPTION(req.LoadBody(reader), std::runtime_error, HasReason{"Cannot parse Content-Length value"})
BOOST_AUTO_TEST_CASE(ipc_tests)
static std::string TempPath(std::string_view pattern)
Generate a temporary path with temp_directory_path and mkstemp.
Definition ipc_tests.cpp:42
void IpcSocketTest(const fs::path &datadir)
Test ipc::Process bind() and connect() methods connecting over a unix socket.
void IpcPipeTest()
Definition ipc_tests.cpp:62
void IpcSocketPairTest()
Test ipc::Protocol connect() and serve() methods connecting over a socketpair.
#define LogInfo(...)
Definition log.h:125
Definition basic.cpp:11
std::unique_ptr< Echo > MakeEcho()
Return implementation of Echo interface.
std::unique_ptr< Protocol > MakeCapnpProtocol(const char *exe_name)
Definition protocol.cpp:160
std::unique_ptr< Process > MakeProcess()
Definition process.cpp:157
int SocketId
Definition util.h:27
SocketId Stream
Definition util.h:30
std::array< SocketId, 2 > SocketPair()
Definition util.h:36
constexpr SocketId SocketError
Definition util.h:28
#define BOOST_CHECK_THROW(stmt, excMatch)
Definition object.cpp:18
#define BOOST_CHECK_EQUAL(v1, v2)
Definition object.cpp:17
#define BOOST_CHECK(expr)
Definition object.cpp:16
constexpr unsigned int DEFAULT_COINBASE_OUTPUT_MAX_ADDITIONAL_SIGOPS
Default sigops cost to reserve for coinbase transaction outputs when creating block templates.
Definition policy.h:29
constexpr unsigned int DEFAULT_BLOCK_RESERVED_WEIGHT
Default for -blockreservedweight.
Definition policy.h:27
std::shared_ptr< const CTransaction > CTransactionRef
@ OP_11
Definition script.h:95
Basic testing setup.
A mutable version of CTransaction.
std::vector< CTxOut > vout
std::vector< CTxIn > vin
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
BOOST_CHECK_NE(OneL.ToString(), ArrayToString(ZeroArray, 32))