Bitcoin Core 28.99.0
P2P Digital Currency
net_tests.cpp
Go to the documentation of this file.
1// Copyright (c) 2012-2022 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 <chainparams.h>
6#include <clientversion.h>
7#include <common/args.h>
8#include <compat/compat.h>
9#include <cstdint>
10#include <net.h>
11#include <net_processing.h>
12#include <netaddress.h>
13#include <netbase.h>
14#include <netmessagemaker.h>
16#include <serialize.h>
17#include <span.h>
18#include <streams.h>
19#include <test/util/random.h>
22#include <util/strencodings.h>
23#include <util/string.h>
24#include <validation.h>
25
26#include <boost/test/unit_test.hpp>
27
28#include <algorithm>
29#include <ios>
30#include <memory>
31#include <optional>
32#include <string>
33
34using namespace std::literals;
35using namespace util::hex_literals;
36using util::ToString;
37
39
40BOOST_AUTO_TEST_CASE(cnode_listen_port)
41{
42 // test default
43 uint16_t port{GetListenPort()};
44 BOOST_CHECK(port == Params().GetDefaultPort());
45 // test set port
46 uint16_t altPort = 12345;
47 BOOST_CHECK(gArgs.SoftSetArg("-port", ToString(altPort)));
48 port = GetListenPort();
49 BOOST_CHECK(port == altPort);
50}
51
52BOOST_AUTO_TEST_CASE(cnode_simple_test)
53{
54 NodeId id = 0;
55
56 in_addr ipv4Addr;
57 ipv4Addr.s_addr = 0xa0b0c001;
58
59 CAddress addr = CAddress(CService(ipv4Addr, 7777), NODE_NETWORK);
60 std::string pszDest;
61
62 std::unique_ptr<CNode> pnode1 = std::make_unique<CNode>(id++,
63 /*sock=*/nullptr,
64 addr,
65 /*nKeyedNetGroupIn=*/0,
66 /*nLocalHostNonceIn=*/0,
67 CAddress(),
68 pszDest,
70 /*inbound_onion=*/false);
71 BOOST_CHECK(pnode1->IsFullOutboundConn() == true);
72 BOOST_CHECK(pnode1->IsManualConn() == false);
73 BOOST_CHECK(pnode1->IsBlockOnlyConn() == false);
74 BOOST_CHECK(pnode1->IsFeelerConn() == false);
75 BOOST_CHECK(pnode1->IsAddrFetchConn() == false);
76 BOOST_CHECK(pnode1->IsInboundConn() == false);
77 BOOST_CHECK(pnode1->m_inbound_onion == false);
78 BOOST_CHECK_EQUAL(pnode1->ConnectedThroughNetwork(), Network::NET_IPV4);
79
80 std::unique_ptr<CNode> pnode2 = std::make_unique<CNode>(id++,
81 /*sock=*/nullptr,
82 addr,
83 /*nKeyedNetGroupIn=*/1,
84 /*nLocalHostNonceIn=*/1,
85 CAddress(),
86 pszDest,
88 /*inbound_onion=*/false);
89 BOOST_CHECK(pnode2->IsFullOutboundConn() == false);
90 BOOST_CHECK(pnode2->IsManualConn() == false);
91 BOOST_CHECK(pnode2->IsBlockOnlyConn() == false);
92 BOOST_CHECK(pnode2->IsFeelerConn() == false);
93 BOOST_CHECK(pnode2->IsAddrFetchConn() == false);
94 BOOST_CHECK(pnode2->IsInboundConn() == true);
95 BOOST_CHECK(pnode2->m_inbound_onion == false);
96 BOOST_CHECK_EQUAL(pnode2->ConnectedThroughNetwork(), Network::NET_IPV4);
97
98 std::unique_ptr<CNode> pnode3 = std::make_unique<CNode>(id++,
99 /*sock=*/nullptr,
100 addr,
101 /*nKeyedNetGroupIn=*/0,
102 /*nLocalHostNonceIn=*/0,
103 CAddress(),
104 pszDest,
106 /*inbound_onion=*/false);
107 BOOST_CHECK(pnode3->IsFullOutboundConn() == true);
108 BOOST_CHECK(pnode3->IsManualConn() == false);
109 BOOST_CHECK(pnode3->IsBlockOnlyConn() == false);
110 BOOST_CHECK(pnode3->IsFeelerConn() == false);
111 BOOST_CHECK(pnode3->IsAddrFetchConn() == false);
112 BOOST_CHECK(pnode3->IsInboundConn() == false);
113 BOOST_CHECK(pnode3->m_inbound_onion == false);
114 BOOST_CHECK_EQUAL(pnode3->ConnectedThroughNetwork(), Network::NET_IPV4);
115
116 std::unique_ptr<CNode> pnode4 = std::make_unique<CNode>(id++,
117 /*sock=*/nullptr,
118 addr,
119 /*nKeyedNetGroupIn=*/1,
120 /*nLocalHostNonceIn=*/1,
121 CAddress(),
122 pszDest,
124 /*inbound_onion=*/true);
125 BOOST_CHECK(pnode4->IsFullOutboundConn() == false);
126 BOOST_CHECK(pnode4->IsManualConn() == false);
127 BOOST_CHECK(pnode4->IsBlockOnlyConn() == false);
128 BOOST_CHECK(pnode4->IsFeelerConn() == false);
129 BOOST_CHECK(pnode4->IsAddrFetchConn() == false);
130 BOOST_CHECK(pnode4->IsInboundConn() == true);
131 BOOST_CHECK(pnode4->m_inbound_onion == true);
132 BOOST_CHECK_EQUAL(pnode4->ConnectedThroughNetwork(), Network::NET_ONION);
133}
134
135BOOST_AUTO_TEST_CASE(cnetaddr_basic)
136{
137 CNetAddr addr;
138
139 // IPv4, INADDR_ANY
140 addr = LookupHost("0.0.0.0", false).value();
141 BOOST_REQUIRE(!addr.IsValid());
142 BOOST_REQUIRE(addr.IsIPv4());
143
144 BOOST_CHECK(addr.IsBindAny());
146 BOOST_CHECK_EQUAL(addr.ToStringAddr(), "0.0.0.0");
147
148 // IPv4, INADDR_NONE
149 addr = LookupHost("255.255.255.255", false).value();
150 BOOST_REQUIRE(!addr.IsValid());
151 BOOST_REQUIRE(addr.IsIPv4());
152
153 BOOST_CHECK(!addr.IsBindAny());
155 BOOST_CHECK_EQUAL(addr.ToStringAddr(), "255.255.255.255");
156
157 // IPv4, casual
158 addr = LookupHost("12.34.56.78", false).value();
159 BOOST_REQUIRE(addr.IsValid());
160 BOOST_REQUIRE(addr.IsIPv4());
161
162 BOOST_CHECK(!addr.IsBindAny());
164 BOOST_CHECK_EQUAL(addr.ToStringAddr(), "12.34.56.78");
165
166 // IPv6, in6addr_any
167 addr = LookupHost("::", false).value();
168 BOOST_REQUIRE(!addr.IsValid());
169 BOOST_REQUIRE(addr.IsIPv6());
170
171 BOOST_CHECK(addr.IsBindAny());
173 BOOST_CHECK_EQUAL(addr.ToStringAddr(), "::");
174
175 // IPv6, casual
176 addr = LookupHost("1122:3344:5566:7788:9900:aabb:ccdd:eeff", false).value();
177 BOOST_REQUIRE(addr.IsValid());
178 BOOST_REQUIRE(addr.IsIPv6());
179
180 BOOST_CHECK(!addr.IsBindAny());
182 BOOST_CHECK_EQUAL(addr.ToStringAddr(), "1122:3344:5566:7788:9900:aabb:ccdd:eeff");
183
184 // IPv6, scoped/link-local. See https://tools.ietf.org/html/rfc4007
185 // We support non-negative decimal integers (uint32_t) as zone id indices.
186 // Normal link-local scoped address functionality is to append "%" plus the
187 // zone id, for example, given a link-local address of "fe80::1" and a zone
188 // id of "32", return the address as "fe80::1%32".
189 const std::string link_local{"fe80::1"};
190 const std::string scoped_addr{link_local + "%32"};
191 addr = LookupHost(scoped_addr, false).value();
192 BOOST_REQUIRE(addr.IsValid());
193 BOOST_REQUIRE(addr.IsIPv6());
194 BOOST_CHECK(!addr.IsBindAny());
195 BOOST_CHECK_EQUAL(addr.ToStringAddr(), scoped_addr);
196
197 // Test that the delimiter "%" and default zone id of 0 can be omitted for the default scope.
198 addr = LookupHost(link_local + "%0", false).value();
199 BOOST_REQUIRE(addr.IsValid());
200 BOOST_REQUIRE(addr.IsIPv6());
201 BOOST_CHECK(!addr.IsBindAny());
202 BOOST_CHECK_EQUAL(addr.ToStringAddr(), link_local);
203
204 // TORv2, no longer supported
205 BOOST_CHECK(!addr.SetSpecial("6hzph5hv6337r6p2.onion"));
206
207 // TORv3
208 const char* torv3_addr = "pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion";
209 BOOST_REQUIRE(addr.SetSpecial(torv3_addr));
210 BOOST_REQUIRE(addr.IsValid());
211 BOOST_REQUIRE(addr.IsTor());
212
213 BOOST_CHECK(!addr.IsI2P());
214 BOOST_CHECK(!addr.IsBindAny());
216 BOOST_CHECK_EQUAL(addr.ToStringAddr(), torv3_addr);
217
218 // TORv3, broken, with wrong checksum
219 BOOST_CHECK(!addr.SetSpecial("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscsad.onion"));
220
221 // TORv3, broken, with wrong version
222 BOOST_CHECK(!addr.SetSpecial("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscrye.onion"));
223
224 // TORv3, malicious
225 BOOST_CHECK(!addr.SetSpecial(std::string{
226 "pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd\0wtf.onion", 66}));
227
228 // TOR, bogus length
229 BOOST_CHECK(!addr.SetSpecial(std::string{"mfrggzak.onion"}));
230
231 // TOR, invalid base32
232 BOOST_CHECK(!addr.SetSpecial(std::string{"mf*g zak.onion"}));
233
234 // I2P
235 const char* i2p_addr = "UDHDrtrcetjm5sxzskjyr5ztpeszydbh4dpl3pl4utgqqw2v4jna.b32.I2P";
236 BOOST_REQUIRE(addr.SetSpecial(i2p_addr));
237 BOOST_REQUIRE(addr.IsValid());
238 BOOST_REQUIRE(addr.IsI2P());
239
240 BOOST_CHECK(!addr.IsTor());
241 BOOST_CHECK(!addr.IsBindAny());
243 BOOST_CHECK_EQUAL(addr.ToStringAddr(), ToLower(i2p_addr));
244
245 // I2P, correct length, but decodes to less than the expected number of bytes.
246 BOOST_CHECK(!addr.SetSpecial("udhdrtrcetjm5sxzskjyr5ztpeszydbh4dpl3pl4utgqqw2v4jn=.b32.i2p"));
247
248 // I2P, extra unnecessary padding
249 BOOST_CHECK(!addr.SetSpecial("udhdrtrcetjm5sxzskjyr5ztpeszydbh4dpl3pl4utgqqw2v4jna=.b32.i2p"));
250
251 // I2P, malicious
252 BOOST_CHECK(!addr.SetSpecial("udhdrtrcetjm5sxzskjyr5ztpeszydbh4dpl3pl4utgqqw2v\0wtf.b32.i2p"s));
253
254 // I2P, valid but unsupported (56 Base32 characters)
255 // See "Encrypted LS with Base 32 Addresses" in
256 // https://geti2p.net/spec/encryptedleaseset.txt
258 !addr.SetSpecial("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscsad.b32.i2p"));
259
260 // I2P, invalid base32
261 BOOST_CHECK(!addr.SetSpecial(std::string{"tp*szydbh4dp.b32.i2p"}));
262
263 // Internal
264 addr.SetInternal("esffpp");
265 BOOST_REQUIRE(!addr.IsValid()); // "internal" is considered invalid
266 BOOST_REQUIRE(addr.IsInternal());
267
268 BOOST_CHECK(!addr.IsBindAny());
270 BOOST_CHECK_EQUAL(addr.ToStringAddr(), "esffpvrt3wpeaygy.internal");
271
272 // Totally bogus
273 BOOST_CHECK(!addr.SetSpecial("totally bogus"));
274}
275
276BOOST_AUTO_TEST_CASE(cnetaddr_tostring_canonical_ipv6)
277{
278 // Test that CNetAddr::ToString formats IPv6 addresses with zero compression as described in
279 // RFC 5952 ("A Recommendation for IPv6 Address Text Representation").
280 const std::map<std::string, std::string> canonical_representations_ipv6{
281 {"0000:0000:0000:0000:0000:0000:0000:0000", "::"},
282 {"000:0000:000:00:0:00:000:0000", "::"},
283 {"000:000:000:000:000:000:000:000", "::"},
284 {"00:00:00:00:00:00:00:00", "::"},
285 {"0:0:0:0:0:0:0:0", "::"},
286 {"0:0:0:0:0:0:0:1", "::1"},
287 {"2001:0:0:1:0:0:0:1", "2001:0:0:1::1"},
288 {"2001:0db8:0:0:1:0:0:1", "2001:db8::1:0:0:1"},
289 {"2001:0db8:85a3:0000:0000:8a2e:0370:7334", "2001:db8:85a3::8a2e:370:7334"},
290 {"2001:0db8::0001", "2001:db8::1"},
291 {"2001:0db8::0001:0000", "2001:db8::1:0"},
292 {"2001:0db8::1:0:0:1", "2001:db8::1:0:0:1"},
293 {"2001:db8:0000:0:1::1", "2001:db8::1:0:0:1"},
294 {"2001:db8:0000:1:1:1:1:1", "2001:db8:0:1:1:1:1:1"},
295 {"2001:db8:0:0:0:0:2:1", "2001:db8::2:1"},
296 {"2001:db8:0:0:0::1", "2001:db8::1"},
297 {"2001:db8:0:0:1:0:0:1", "2001:db8::1:0:0:1"},
298 {"2001:db8:0:0:1::1", "2001:db8::1:0:0:1"},
299 {"2001:DB8:0:0:1::1", "2001:db8::1:0:0:1"},
300 {"2001:db8:0:0::1", "2001:db8::1"},
301 {"2001:db8:0:0:aaaa::1", "2001:db8::aaaa:0:0:1"},
302 {"2001:db8:0:1:1:1:1:1", "2001:db8:0:1:1:1:1:1"},
303 {"2001:db8:0::1", "2001:db8::1"},
304 {"2001:db8:85a3:0:0:8a2e:370:7334", "2001:db8:85a3::8a2e:370:7334"},
305 {"2001:db8::0:1", "2001:db8::1"},
306 {"2001:db8::0:1:0:0:1", "2001:db8::1:0:0:1"},
307 {"2001:DB8::1", "2001:db8::1"},
308 {"2001:db8::1", "2001:db8::1"},
309 {"2001:db8::1:0:0:1", "2001:db8::1:0:0:1"},
310 {"2001:db8::1:1:1:1:1", "2001:db8:0:1:1:1:1:1"},
311 {"2001:db8::aaaa:0:0:1", "2001:db8::aaaa:0:0:1"},
312 {"2001:db8:aaaa:bbbb:cccc:dddd:0:1", "2001:db8:aaaa:bbbb:cccc:dddd:0:1"},
313 {"2001:db8:aaaa:bbbb:cccc:dddd::1", "2001:db8:aaaa:bbbb:cccc:dddd:0:1"},
314 {"2001:db8:aaaa:bbbb:cccc:dddd:eeee:0001", "2001:db8:aaaa:bbbb:cccc:dddd:eeee:1"},
315 {"2001:db8:aaaa:bbbb:cccc:dddd:eeee:001", "2001:db8:aaaa:bbbb:cccc:dddd:eeee:1"},
316 {"2001:db8:aaaa:bbbb:cccc:dddd:eeee:01", "2001:db8:aaaa:bbbb:cccc:dddd:eeee:1"},
317 {"2001:db8:aaaa:bbbb:cccc:dddd:eeee:1", "2001:db8:aaaa:bbbb:cccc:dddd:eeee:1"},
318 {"2001:db8:aaaa:bbbb:cccc:dddd:eeee:aaaa", "2001:db8:aaaa:bbbb:cccc:dddd:eeee:aaaa"},
319 {"2001:db8:aaaa:bbbb:cccc:dddd:eeee:AAAA", "2001:db8:aaaa:bbbb:cccc:dddd:eeee:aaaa"},
320 {"2001:db8:aaaa:bbbb:cccc:dddd:eeee:AaAa", "2001:db8:aaaa:bbbb:cccc:dddd:eeee:aaaa"},
321 };
322 for (const auto& [input_address, expected_canonical_representation_output] : canonical_representations_ipv6) {
323 const std::optional<CNetAddr> net_addr{LookupHost(input_address, false)};
324 BOOST_REQUIRE(net_addr.value().IsIPv6());
325 BOOST_CHECK_EQUAL(net_addr.value().ToStringAddr(), expected_canonical_representation_output);
326 }
327}
328
329BOOST_AUTO_TEST_CASE(cnetaddr_serialize_v1)
330{
331 CNetAddr addr;
332 DataStream s{};
333 const auto ser_params{CAddress::V1_NETWORK};
334
335 s << ser_params(addr);
336 BOOST_CHECK_EQUAL(HexStr(s), "00000000000000000000000000000000");
337 s.clear();
338
339 addr = LookupHost("1.2.3.4", false).value();
340 s << ser_params(addr);
341 BOOST_CHECK_EQUAL(HexStr(s), "00000000000000000000ffff01020304");
342 s.clear();
343
344 addr = LookupHost("1a1b:2a2b:3a3b:4a4b:5a5b:6a6b:7a7b:8a8b", false).value();
345 s << ser_params(addr);
346 BOOST_CHECK_EQUAL(HexStr(s), "1a1b2a2b3a3b4a4b5a5b6a6b7a7b8a8b");
347 s.clear();
348
349 // TORv2, no longer supported
350 BOOST_CHECK(!addr.SetSpecial("6hzph5hv6337r6p2.onion"));
351
352 BOOST_REQUIRE(addr.SetSpecial("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion"));
353 s << ser_params(addr);
354 BOOST_CHECK_EQUAL(HexStr(s), "00000000000000000000000000000000");
355 s.clear();
356
357 addr.SetInternal("a");
358 s << ser_params(addr);
359 BOOST_CHECK_EQUAL(HexStr(s), "fd6b88c08724ca978112ca1bbdcafac2");
360 s.clear();
361}
362
363BOOST_AUTO_TEST_CASE(cnetaddr_serialize_v2)
364{
365 CNetAddr addr;
366 DataStream s{};
367 const auto ser_params{CAddress::V2_NETWORK};
368
369 s << ser_params(addr);
370 BOOST_CHECK_EQUAL(HexStr(s), "021000000000000000000000000000000000");
371 s.clear();
372
373 addr = LookupHost("1.2.3.4", false).value();
374 s << ser_params(addr);
375 BOOST_CHECK_EQUAL(HexStr(s), "010401020304");
376 s.clear();
377
378 addr = LookupHost("1a1b:2a2b:3a3b:4a4b:5a5b:6a6b:7a7b:8a8b", false).value();
379 s << ser_params(addr);
380 BOOST_CHECK_EQUAL(HexStr(s), "02101a1b2a2b3a3b4a4b5a5b6a6b7a7b8a8b");
381 s.clear();
382
383 // TORv2, no longer supported
384 BOOST_CHECK(!addr.SetSpecial("6hzph5hv6337r6p2.onion"));
385
386 BOOST_REQUIRE(addr.SetSpecial("kpgvmscirrdqpekbqjsvw5teanhatztpp2gl6eee4zkowvwfxwenqaid.onion"));
387 s << ser_params(addr);
388 BOOST_CHECK_EQUAL(HexStr(s), "042053cd5648488c4707914182655b7664034e09e66f7e8cbf1084e654eb56c5bd88");
389 s.clear();
390
391 BOOST_REQUIRE(addr.SetInternal("a"));
392 s << ser_params(addr);
393 BOOST_CHECK_EQUAL(HexStr(s), "0210fd6b88c08724ca978112ca1bbdcafac2");
394 s.clear();
395}
396
397BOOST_AUTO_TEST_CASE(cnetaddr_unserialize_v2)
398{
399 CNetAddr addr;
400 DataStream s{};
401 const auto ser_params{CAddress::V2_NETWORK};
402
403 // Valid IPv4.
404 s << "01" // network type (IPv4)
405 "04" // address length
406 "01020304"_hex; // address
407 s >> ser_params(addr);
408 BOOST_CHECK(addr.IsValid());
409 BOOST_CHECK(addr.IsIPv4());
411 BOOST_CHECK_EQUAL(addr.ToStringAddr(), "1.2.3.4");
412 BOOST_REQUIRE(s.empty());
413
414 // Invalid IPv4, valid length but address itself is shorter.
415 s << "01" // network type (IPv4)
416 "04" // address length
417 "0102"_hex; // address
418 BOOST_CHECK_EXCEPTION(s >> ser_params(addr), std::ios_base::failure, HasReason("end of data"));
419 BOOST_REQUIRE(!s.empty()); // The stream is not consumed on invalid input.
420 s.clear();
421
422 // Invalid IPv4, with bogus length.
423 s << "01" // network type (IPv4)
424 "05" // address length
425 "01020304"_hex; // address
426 BOOST_CHECK_EXCEPTION(s >> ser_params(addr), std::ios_base::failure,
427 HasReason("BIP155 IPv4 address with length 5 (should be 4)"));
428 BOOST_REQUIRE(!s.empty()); // The stream is not consumed on invalid input.
429 s.clear();
430
431 // Invalid IPv4, with extreme length.
432 s << "01" // network type (IPv4)
433 "fd0102" // address length (513 as CompactSize)
434 "01020304"_hex; // address
435 BOOST_CHECK_EXCEPTION(s >> ser_params(addr), std::ios_base::failure,
436 HasReason("Address too long: 513 > 512"));
437 BOOST_REQUIRE(!s.empty()); // The stream is not consumed on invalid input.
438 s.clear();
439
440 // Valid IPv6.
441 s << "02" // network type (IPv6)
442 "10" // address length
443 "0102030405060708090a0b0c0d0e0f10"_hex; // address
444 s >> ser_params(addr);
445 BOOST_CHECK(addr.IsValid());
446 BOOST_CHECK(addr.IsIPv6());
448 BOOST_CHECK_EQUAL(addr.ToStringAddr(), "102:304:506:708:90a:b0c:d0e:f10");
449 BOOST_REQUIRE(s.empty());
450
451 // Valid IPv6, contains embedded "internal".
452 s << "02" // network type (IPv6)
453 "10" // address length
454 "fd6b88c08724ca978112ca1bbdcafac2"_hex; // address: 0xfd + sha256("bitcoin")[0:5] +
455 // sha256(name)[0:10]
456 s >> ser_params(addr);
457 BOOST_CHECK(addr.IsInternal());
459 BOOST_CHECK_EQUAL(addr.ToStringAddr(), "zklycewkdo64v6wc.internal");
460 BOOST_REQUIRE(s.empty());
461
462 // Invalid IPv6, with bogus length.
463 s << "02" // network type (IPv6)
464 "04" // address length
465 "00"_hex; // address
466 BOOST_CHECK_EXCEPTION(s >> ser_params(addr), std::ios_base::failure,
467 HasReason("BIP155 IPv6 address with length 4 (should be 16)"));
468 BOOST_REQUIRE(!s.empty()); // The stream is not consumed on invalid input.
469 s.clear();
470
471 // Invalid IPv6, contains embedded IPv4.
472 s << "02" // network type (IPv6)
473 "10" // address length
474 "00000000000000000000ffff01020304"_hex; // address
475 s >> ser_params(addr);
476 BOOST_CHECK(!addr.IsValid());
477 BOOST_REQUIRE(s.empty());
478
479 // Invalid IPv6, contains embedded TORv2.
480 s << "02" // network type (IPv6)
481 "10" // address length
482 "fd87d87eeb430102030405060708090a"_hex; // address
483 s >> ser_params(addr);
484 BOOST_CHECK(!addr.IsValid());
485 BOOST_REQUIRE(s.empty());
486
487 // TORv2, no longer supported.
488 s << "03" // network type (TORv2)
489 "0a" // address length
490 "f1f2f3f4f5f6f7f8f9fa"_hex; // address
491 s >> ser_params(addr);
492 BOOST_CHECK(!addr.IsValid());
493 BOOST_REQUIRE(s.empty());
494
495 // Valid TORv3.
496 s << "04" // network type (TORv3)
497 "20" // address length
498 "79bcc625184b05194975c28b66b66b04" // address
499 "69f7f6556fb1ac3189a79b40dda32f1f"_hex;
500 s >> ser_params(addr);
501 BOOST_CHECK(addr.IsValid());
502 BOOST_CHECK(addr.IsTor());
505 "pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion");
506 BOOST_REQUIRE(s.empty());
507
508 // Invalid TORv3, with bogus length.
509 s << "04" // network type (TORv3)
510 "00" // address length
511 "00"_hex; // address
512 BOOST_CHECK_EXCEPTION(s >> ser_params(addr), std::ios_base::failure,
513 HasReason("BIP155 TORv3 address with length 0 (should be 32)"));
514 BOOST_REQUIRE(!s.empty()); // The stream is not consumed on invalid input.
515 s.clear();
516
517 // Valid I2P.
518 s << "05" // network type (I2P)
519 "20" // address length
520 "a2894dabaec08c0051a481a6dac88b64" // address
521 "f98232ae42d4b6fd2fa81952dfe36a87"_hex;
522 s >> ser_params(addr);
523 BOOST_CHECK(addr.IsValid());
524 BOOST_CHECK(addr.IsI2P());
527 "ukeu3k5oycgaauneqgtnvselmt4yemvoilkln7jpvamvfx7dnkdq.b32.i2p");
528 BOOST_REQUIRE(s.empty());
529
530 // Invalid I2P, with bogus length.
531 s << "05" // network type (I2P)
532 "03" // address length
533 "00"_hex; // address
534 BOOST_CHECK_EXCEPTION(s >> ser_params(addr), std::ios_base::failure,
535 HasReason("BIP155 I2P address with length 3 (should be 32)"));
536 BOOST_REQUIRE(!s.empty()); // The stream is not consumed on invalid input.
537 s.clear();
538
539 // Valid CJDNS.
540 s << "06" // network type (CJDNS)
541 "10" // address length
542 "fc000001000200030004000500060007"_hex; // address
543 s >> ser_params(addr);
544 BOOST_CHECK(addr.IsValid());
545 BOOST_CHECK(addr.IsCJDNS());
547 BOOST_CHECK_EQUAL(addr.ToStringAddr(), "fc00:1:2:3:4:5:6:7");
548 BOOST_REQUIRE(s.empty());
549
550 // Invalid CJDNS, wrong prefix.
551 s << "06" // network type (CJDNS)
552 "10" // address length
553 "aa000001000200030004000500060007"_hex; // address
554 s >> ser_params(addr);
555 BOOST_CHECK(addr.IsCJDNS());
556 BOOST_CHECK(!addr.IsValid());
557 BOOST_REQUIRE(s.empty());
558
559 // Invalid CJDNS, with bogus length.
560 s << "06" // network type (CJDNS)
561 "01" // address length
562 "00"_hex; // address
563 BOOST_CHECK_EXCEPTION(s >> ser_params(addr), std::ios_base::failure,
564 HasReason("BIP155 CJDNS address with length 1 (should be 16)"));
565 BOOST_REQUIRE(!s.empty()); // The stream is not consumed on invalid input.
566 s.clear();
567
568 // Unknown, with extreme length.
569 s << "aa" // network type (unknown)
570 "fe00000002" // address length (CompactSize's MAX_SIZE)
571 "01020304050607"_hex; // address
572 BOOST_CHECK_EXCEPTION(s >> ser_params(addr), std::ios_base::failure,
573 HasReason("Address too long: 33554432 > 512"));
574 BOOST_REQUIRE(!s.empty()); // The stream is not consumed on invalid input.
575 s.clear();
576
577 // Unknown, with reasonable length.
578 s << "aa" // network type (unknown)
579 "04" // address length
580 "01020304"_hex; // address
581 s >> ser_params(addr);
582 BOOST_CHECK(!addr.IsValid());
583 BOOST_REQUIRE(s.empty());
584
585 // Unknown, with zero length.
586 s << "aa" // network type (unknown)
587 "00" // address length
588 ""_hex; // address
589 s >> ser_params(addr);
590 BOOST_CHECK(!addr.IsValid());
591 BOOST_REQUIRE(s.empty());
592}
593
594// prior to PR #14728, this test triggers an undefined behavior
595BOOST_AUTO_TEST_CASE(ipv4_peer_with_ipv6_addrMe_test)
596{
597 // set up local addresses; all that's necessary to reproduce the bug is
598 // that a normal IPv4 address is among the entries, but if this address is
599 // !IsRoutable the undefined behavior is easier to trigger deterministically
600 in_addr raw_addr;
601 raw_addr.s_addr = htonl(0x7f000001);
602 const CNetAddr mapLocalHost_entry = CNetAddr(raw_addr);
603 {
606 lsi.nScore = 23;
607 lsi.nPort = 42;
608 mapLocalHost[mapLocalHost_entry] = lsi;
609 }
610
611 // create a peer with an IPv4 address
612 in_addr ipv4AddrPeer;
613 ipv4AddrPeer.s_addr = 0xa0b0c001;
614 CAddress addr = CAddress(CService(ipv4AddrPeer, 7777), NODE_NETWORK);
615 std::unique_ptr<CNode> pnode = std::make_unique<CNode>(/*id=*/0,
616 /*sock=*/nullptr,
617 addr,
618 /*nKeyedNetGroupIn=*/0,
619 /*nLocalHostNonceIn=*/0,
620 CAddress{},
621 /*pszDest=*/std::string{},
623 /*inbound_onion=*/false);
624 pnode->fSuccessfullyConnected.store(true);
625
626 // the peer claims to be reaching us via IPv6
627 in6_addr ipv6AddrLocal;
628 memset(ipv6AddrLocal.s6_addr, 0, 16);
629 ipv6AddrLocal.s6_addr[0] = 0xcc;
630 CAddress addrLocal = CAddress(CService(ipv6AddrLocal, 7777), NODE_NETWORK);
631 pnode->SetAddrLocal(addrLocal);
632
633 // before patch, this causes undefined behavior detectable with clang's -fsanitize=memory
634 GetLocalAddrForPeer(*pnode);
635
636 // suppress no-checks-run warning; if this test fails, it's by triggering a sanitizer
637 BOOST_CHECK(1);
638
639 // Cleanup, so that we don't confuse other tests.
640 {
642 mapLocalHost.erase(mapLocalHost_entry);
643 }
644}
645
646BOOST_AUTO_TEST_CASE(get_local_addr_for_peer_port)
647{
648 // Test that GetLocalAddrForPeer() properly selects the address to self-advertise:
649 //
650 // 1. GetLocalAddrForPeer() calls GetLocalAddress() which returns an address that is
651 // not routable.
652 // 2. GetLocalAddrForPeer() overrides the address with whatever the peer has told us
653 // he sees us as.
654 // 2.1. For inbound connections we must override both the address and the port.
655 // 2.2. For outbound connections we must override only the address.
656
657 // Pretend that we bound to this port.
658 const uint16_t bind_port = 20001;
659 m_node.args->ForceSetArg("-bind", strprintf("3.4.5.6:%u", bind_port));
660
661 // Our address:port as seen from the peer, completely different from the above.
662 in_addr peer_us_addr;
663 peer_us_addr.s_addr = htonl(0x02030405);
664 const CService peer_us{peer_us_addr, 20002};
665
666 // Create a peer with a routable IPv4 address (outbound).
667 in_addr peer_out_in_addr;
668 peer_out_in_addr.s_addr = htonl(0x01020304);
669 CNode peer_out{/*id=*/0,
670 /*sock=*/nullptr,
671 /*addrIn=*/CAddress{CService{peer_out_in_addr, 8333}, NODE_NETWORK},
672 /*nKeyedNetGroupIn=*/0,
673 /*nLocalHostNonceIn=*/0,
674 /*addrBindIn=*/CAddress{},
675 /*addrNameIn=*/std::string{},
677 /*inbound_onion=*/false};
678 peer_out.fSuccessfullyConnected = true;
679 peer_out.SetAddrLocal(peer_us);
680
681 // Without the fix peer_us:8333 is chosen instead of the proper peer_us:bind_port.
682 auto chosen_local_addr = GetLocalAddrForPeer(peer_out);
683 BOOST_REQUIRE(chosen_local_addr);
684 const CService expected{peer_us_addr, bind_port};
685 BOOST_CHECK(*chosen_local_addr == expected);
686
687 // Create a peer with a routable IPv4 address (inbound).
688 in_addr peer_in_in_addr;
689 peer_in_in_addr.s_addr = htonl(0x05060708);
690 CNode peer_in{/*id=*/0,
691 /*sock=*/nullptr,
692 /*addrIn=*/CAddress{CService{peer_in_in_addr, 8333}, NODE_NETWORK},
693 /*nKeyedNetGroupIn=*/0,
694 /*nLocalHostNonceIn=*/0,
695 /*addrBindIn=*/CAddress{},
696 /*addrNameIn=*/std::string{},
697 /*conn_type_in=*/ConnectionType::INBOUND,
698 /*inbound_onion=*/false};
699 peer_in.fSuccessfullyConnected = true;
700 peer_in.SetAddrLocal(peer_us);
701
702 // Without the fix peer_us:8333 is chosen instead of the proper peer_us:peer_us.GetPort().
703 chosen_local_addr = GetLocalAddrForPeer(peer_in);
704 BOOST_REQUIRE(chosen_local_addr);
705 BOOST_CHECK(*chosen_local_addr == peer_us);
706
707 m_node.args->ForceSetArg("-bind", "");
708}
709
710BOOST_AUTO_TEST_CASE(LimitedAndReachable_Network)
711{
717
723
729
735
741}
742
743BOOST_AUTO_TEST_CASE(LimitedAndReachable_NetworkCaseUnroutableAndInternal)
744{
745 // Should be reachable by default.
748
750
753
761}
762
763CNetAddr UtilBuildAddress(unsigned char p1, unsigned char p2, unsigned char p3, unsigned char p4)
764{
765 unsigned char ip[] = {p1, p2, p3, p4};
766
767 struct sockaddr_in sa;
768 memset(&sa, 0, sizeof(sockaddr_in)); // initialize the memory block
769 memcpy(&(sa.sin_addr), &ip, sizeof(ip));
770 return CNetAddr(sa.sin_addr);
771}
772
773
774BOOST_AUTO_TEST_CASE(LimitedAndReachable_CNetAddr)
775{
776 CNetAddr addr = UtilBuildAddress(0x001, 0x001, 0x001, 0x001); // 1.1.1.1
777
780
783
784 g_reachable_nets.Add(NET_IPV4); // have to reset this, because this is stateful.
785}
786
787
788BOOST_AUTO_TEST_CASE(LocalAddress_BasicLifecycle)
789{
790 CService addr = CService(UtilBuildAddress(0x002, 0x001, 0x001, 0x001), 1000); // 2.1.1.1:1000
791
793
794 BOOST_CHECK(!IsLocal(addr));
795 BOOST_CHECK(AddLocal(addr, 1000));
796 BOOST_CHECK(IsLocal(addr));
797
798 RemoveLocal(addr);
799 BOOST_CHECK(!IsLocal(addr));
800}
801
802BOOST_AUTO_TEST_CASE(initial_advertise_from_version_message)
803{
805
806 // Tests the following scenario:
807 // * -bind=3.4.5.6:20001 is specified
808 // * we make an outbound connection to a peer
809 // * the peer reports he sees us as 2.3.4.5:20002 in the version message
810 // (20002 is a random port assigned by our OS for the outgoing TCP connection,
811 // we cannot accept connections to it)
812 // * we should self-advertise to that peer as 2.3.4.5:20001
813
814 // Pretend that we bound to this port.
815 const uint16_t bind_port = 20001;
816 m_node.args->ForceSetArg("-bind", strprintf("3.4.5.6:%u", bind_port));
817 m_node.args->ForceSetArg("-capturemessages", "1");
818
819 // Our address:port as seen from the peer - 2.3.4.5:20002 (different from the above).
820 in_addr peer_us_addr;
821 peer_us_addr.s_addr = htonl(0x02030405);
822 const CService peer_us{peer_us_addr, 20002};
823
824 // Create a peer with a routable IPv4 address.
825 in_addr peer_in_addr;
826 peer_in_addr.s_addr = htonl(0x01020304);
827 CNode peer{/*id=*/0,
828 /*sock=*/nullptr,
829 /*addrIn=*/CAddress{CService{peer_in_addr, 8333}, NODE_NETWORK},
830 /*nKeyedNetGroupIn=*/0,
831 /*nLocalHostNonceIn=*/0,
832 /*addrBindIn=*/CAddress{},
833 /*addrNameIn=*/std::string{},
835 /*inbound_onion=*/false};
836
837 const uint64_t services{NODE_NETWORK | NODE_WITNESS};
838 const int64_t time{0};
839
840 // Force ChainstateManager::IsInitialBlockDownload() to return false.
841 // Otherwise PushAddress() isn't called by PeerManager::ProcessMessage().
842 auto& chainman = static_cast<TestChainstateManager&>(*m_node.chainman);
843 chainman.JumpOutOfIbd();
844
845 m_node.peerman->InitializeNode(peer, NODE_NETWORK);
846
847 std::atomic<bool> interrupt_dummy{false};
848 std::chrono::microseconds time_received_dummy{0};
849
850 const auto msg_version =
851 NetMsg::Make(NetMsgType::VERSION, PROTOCOL_VERSION, services, time, services, CAddress::V1_NETWORK(peer_us));
852 DataStream msg_version_stream{msg_version.data};
853
854 m_node.peerman->ProcessMessage(
855 peer, NetMsgType::VERSION, msg_version_stream, time_received_dummy, interrupt_dummy);
856
857 const auto msg_verack = NetMsg::Make(NetMsgType::VERACK);
858 DataStream msg_verack_stream{msg_verack.data};
859
860 // Will set peer.fSuccessfullyConnected to true (necessary in SendMessages()).
861 m_node.peerman->ProcessMessage(
862 peer, NetMsgType::VERACK, msg_verack_stream, time_received_dummy, interrupt_dummy);
863
864 // Ensure that peer_us_addr:bind_port is sent to the peer.
865 const CService expected{peer_us_addr, bind_port};
866 bool sent{false};
867
868 const auto CaptureMessageOrig = CaptureMessage;
869 CaptureMessage = [&sent, &expected](const CAddress& addr,
870 const std::string& msg_type,
872 bool is_incoming) -> void {
873 if (!is_incoming && msg_type == "addr") {
875 std::vector<CAddress> addresses;
876
877 s >> CAddress::V1_NETWORK(addresses);
878
879 for (const auto& addr : addresses) {
880 if (addr == expected) {
881 sent = true;
882 return;
883 }
884 }
885 }
886 };
887
888 m_node.peerman->SendMessages(&peer);
889
890 BOOST_CHECK(sent);
891
892 CaptureMessage = CaptureMessageOrig;
893 chainman.ResetIbd();
894 m_node.args->ForceSetArg("-capturemessages", "0");
895 m_node.args->ForceSetArg("-bind", "");
896}
897
898
899BOOST_AUTO_TEST_CASE(advertise_local_address)
900{
901 auto CreatePeer = [](const CAddress& addr) {
902 return std::make_unique<CNode>(/*id=*/0,
903 /*sock=*/nullptr,
904 addr,
905 /*nKeyedNetGroupIn=*/0,
906 /*nLocalHostNonceIn=*/0,
907 CAddress{},
908 /*pszDest=*/std::string{},
910 /*inbound_onion=*/false);
911 };
913
914 CAddress addr_ipv4{Lookup("1.2.3.4", 8333, false).value(), NODE_NONE};
915 BOOST_REQUIRE(addr_ipv4.IsValid());
916 BOOST_REQUIRE(addr_ipv4.IsIPv4());
917
918 CAddress addr_ipv6{Lookup("1122:3344:5566:7788:9900:aabb:ccdd:eeff", 8333, false).value(), NODE_NONE};
919 BOOST_REQUIRE(addr_ipv6.IsValid());
920 BOOST_REQUIRE(addr_ipv6.IsIPv6());
921
922 CAddress addr_ipv6_tunnel{Lookup("2002:3344:5566:7788:9900:aabb:ccdd:eeff", 8333, false).value(), NODE_NONE};
923 BOOST_REQUIRE(addr_ipv6_tunnel.IsValid());
924 BOOST_REQUIRE(addr_ipv6_tunnel.IsIPv6());
925 BOOST_REQUIRE(addr_ipv6_tunnel.IsRFC3964());
926
927 CAddress addr_teredo{Lookup("2001:0000:5566:7788:9900:aabb:ccdd:eeff", 8333, false).value(), NODE_NONE};
928 BOOST_REQUIRE(addr_teredo.IsValid());
929 BOOST_REQUIRE(addr_teredo.IsIPv6());
930 BOOST_REQUIRE(addr_teredo.IsRFC4380());
931
932 CAddress addr_onion;
933 BOOST_REQUIRE(addr_onion.SetSpecial("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion"));
934 BOOST_REQUIRE(addr_onion.IsValid());
935 BOOST_REQUIRE(addr_onion.IsTor());
936
937 CAddress addr_i2p;
938 BOOST_REQUIRE(addr_i2p.SetSpecial("udhdrtrcetjm5sxzskjyr5ztpeszydbh4dpl3pl4utgqqw2v4jna.b32.i2p"));
939 BOOST_REQUIRE(addr_i2p.IsValid());
940 BOOST_REQUIRE(addr_i2p.IsI2P());
941
942 CService service_cjdns{Lookup("fc00:3344:5566:7788:9900:aabb:ccdd:eeff", 8333, false).value(), NODE_NONE};
943 CAddress addr_cjdns{MaybeFlipIPv6toCJDNS(service_cjdns), NODE_NONE};
944 BOOST_REQUIRE(addr_cjdns.IsValid());
945 BOOST_REQUIRE(addr_cjdns.IsCJDNS());
946
947 const auto peer_ipv4{CreatePeer(addr_ipv4)};
948 const auto peer_ipv6{CreatePeer(addr_ipv6)};
949 const auto peer_ipv6_tunnel{CreatePeer(addr_ipv6_tunnel)};
950 const auto peer_teredo{CreatePeer(addr_teredo)};
951 const auto peer_onion{CreatePeer(addr_onion)};
952 const auto peer_i2p{CreatePeer(addr_i2p)};
953 const auto peer_cjdns{CreatePeer(addr_cjdns)};
954
955 // one local clearnet address - advertise to all but privacy peers
956 AddLocal(addr_ipv4);
957 BOOST_CHECK(GetLocalAddress(*peer_ipv4) == addr_ipv4);
958 BOOST_CHECK(GetLocalAddress(*peer_ipv6) == addr_ipv4);
959 BOOST_CHECK(GetLocalAddress(*peer_ipv6_tunnel) == addr_ipv4);
960 BOOST_CHECK(GetLocalAddress(*peer_teredo) == addr_ipv4);
961 BOOST_CHECK(GetLocalAddress(*peer_cjdns) == addr_ipv4);
962 BOOST_CHECK(!GetLocalAddress(*peer_onion).IsValid());
963 BOOST_CHECK(!GetLocalAddress(*peer_i2p).IsValid());
964 RemoveLocal(addr_ipv4);
965
966 // local privacy addresses - don't advertise to clearnet peers
967 AddLocal(addr_onion);
968 AddLocal(addr_i2p);
969 BOOST_CHECK(!GetLocalAddress(*peer_ipv4).IsValid());
970 BOOST_CHECK(!GetLocalAddress(*peer_ipv6).IsValid());
971 BOOST_CHECK(!GetLocalAddress(*peer_ipv6_tunnel).IsValid());
972 BOOST_CHECK(!GetLocalAddress(*peer_teredo).IsValid());
973 BOOST_CHECK(!GetLocalAddress(*peer_cjdns).IsValid());
974 BOOST_CHECK(GetLocalAddress(*peer_onion) == addr_onion);
975 BOOST_CHECK(GetLocalAddress(*peer_i2p) == addr_i2p);
976 RemoveLocal(addr_onion);
977 RemoveLocal(addr_i2p);
978
979 // local addresses from all networks
980 AddLocal(addr_ipv4);
981 AddLocal(addr_ipv6);
982 AddLocal(addr_ipv6_tunnel);
983 AddLocal(addr_teredo);
984 AddLocal(addr_onion);
985 AddLocal(addr_i2p);
986 AddLocal(addr_cjdns);
987 BOOST_CHECK(GetLocalAddress(*peer_ipv4) == addr_ipv4);
988 BOOST_CHECK(GetLocalAddress(*peer_ipv6) == addr_ipv6);
989 BOOST_CHECK(GetLocalAddress(*peer_ipv6_tunnel) == addr_ipv6);
990 BOOST_CHECK(GetLocalAddress(*peer_teredo) == addr_ipv4);
991 BOOST_CHECK(GetLocalAddress(*peer_onion) == addr_onion);
992 BOOST_CHECK(GetLocalAddress(*peer_i2p) == addr_i2p);
993 BOOST_CHECK(GetLocalAddress(*peer_cjdns) == addr_cjdns);
994 RemoveLocal(addr_ipv4);
995 RemoveLocal(addr_ipv6);
996 RemoveLocal(addr_ipv6_tunnel);
997 RemoveLocal(addr_teredo);
998 RemoveLocal(addr_onion);
999 RemoveLocal(addr_i2p);
1000 RemoveLocal(addr_cjdns);
1001}
1002
1003namespace {
1004
1005CKey GenerateRandomTestKey(FastRandomContext& rng) noexcept
1006{
1007 CKey key;
1008 uint256 key_data = rng.rand256();
1009 key.Set(key_data.begin(), key_data.end(), true);
1010 return key;
1011}
1012
1021class V2TransportTester
1022{
1023 FastRandomContext& m_rng;
1024 V2Transport m_transport;
1025 BIP324Cipher m_cipher;
1026 bool m_test_initiator;
1027
1028 std::vector<uint8_t> m_sent_garbage;
1029 std::vector<uint8_t> m_recv_garbage;
1030 std::vector<uint8_t> m_to_send;
1031 std::vector<uint8_t> m_received;
1032 std::deque<CSerializedNetMsg> m_msg_to_send;
1033 bool m_sent_aad{false};
1034
1035public:
1037 explicit V2TransportTester(FastRandomContext& rng, bool test_initiator)
1038 : m_rng{rng},
1039 m_transport{0, test_initiator},
1040 m_cipher{GenerateRandomTestKey(m_rng), MakeByteSpan(m_rng.rand256())},
1041 m_test_initiator(test_initiator) {}
1042
1050 using InteractResult = std::optional<std::vector<std::optional<CNetMessage>>>;
1051
1057 InteractResult Interact()
1058 {
1059 std::vector<std::optional<CNetMessage>> ret;
1060 while (true) {
1061 bool progress{false};
1062 // Send bytes from m_to_send to the transport.
1063 if (!m_to_send.empty()) {
1064 Span<const uint8_t> to_send = Span{m_to_send}.first(1 + m_rng.randrange(m_to_send.size()));
1065 size_t old_len = to_send.size();
1066 if (!m_transport.ReceivedBytes(to_send)) {
1067 return std::nullopt; // transport error occurred
1068 }
1069 if (old_len != to_send.size()) {
1070 progress = true;
1071 m_to_send.erase(m_to_send.begin(), m_to_send.begin() + (old_len - to_send.size()));
1072 }
1073 }
1074 // Retrieve messages received by the transport.
1075 if (m_transport.ReceivedMessageComplete() && (!progress || m_rng.randbool())) {
1076 bool reject{false};
1077 auto msg = m_transport.GetReceivedMessage({}, reject);
1078 if (reject) {
1079 ret.emplace_back(std::nullopt);
1080 } else {
1081 ret.emplace_back(std::move(msg));
1082 }
1083 progress = true;
1084 }
1085 // Enqueue a message to be sent by the transport to us.
1086 if (!m_msg_to_send.empty() && (!progress || m_rng.randbool())) {
1087 if (m_transport.SetMessageToSend(m_msg_to_send.front())) {
1088 m_msg_to_send.pop_front();
1089 progress = true;
1090 }
1091 }
1092 // Receive bytes from the transport.
1093 const auto& [recv_bytes, _more, _msg_type] = m_transport.GetBytesToSend(!m_msg_to_send.empty());
1094 if (!recv_bytes.empty() && (!progress || m_rng.randbool())) {
1095 size_t to_receive = 1 + m_rng.randrange(recv_bytes.size());
1096 m_received.insert(m_received.end(), recv_bytes.begin(), recv_bytes.begin() + to_receive);
1097 progress = true;
1098 m_transport.MarkBytesSent(to_receive);
1099 }
1100 if (!progress) break;
1101 }
1102 return ret;
1103 }
1104
1106 BIP324Cipher& GetCipher() { return m_cipher; }
1107
1109 void Send(Span<const uint8_t> data)
1110 {
1111 m_to_send.insert(m_to_send.end(), data.begin(), data.end());
1112 }
1113
1115 void SendV1Version(const MessageStartChars& magic)
1116 {
1117 CMessageHeader hdr(magic, "version", 126 + m_rng.randrange(11));
1118 DataStream ser{};
1119 ser << hdr;
1120 m_to_send.insert(m_to_send.end(), UCharCast(ser.data()), UCharCast(ser.data() + ser.size()));
1121 }
1122
1124 void Send(Span<const std::byte> data) { Send(MakeUCharSpan(data)); }
1125
1127 void SendKey() { Send(m_cipher.GetOurPubKey()); }
1128
1130 void SendGarbage(Span<const uint8_t> garbage)
1131 {
1132 // Remember the specified garbage (so we can use it as AAD).
1133 m_sent_garbage.assign(garbage.begin(), garbage.end());
1134 // Schedule it for sending.
1135 Send(m_sent_garbage);
1136 }
1137
1139 void SendGarbage(size_t garbage_len)
1140 {
1141 // Generate random garbage and send it.
1142 SendGarbage(m_rng.randbytes<uint8_t>(garbage_len));
1143 }
1144
1146 void SendGarbage()
1147 {
1148 SendGarbage(m_rng.randrange(V2Transport::MAX_GARBAGE_LEN + 1));
1149 }
1150
1152 void AddMessage(std::string m_type, std::vector<uint8_t> payload)
1153 {
1155 msg.m_type = std::move(m_type);
1156 msg.data = std::move(payload);
1157 m_msg_to_send.push_back(std::move(msg));
1158 }
1159
1165 void ReceiveKey()
1166 {
1167 // When processing a key, enough bytes need to have been received already.
1168 BOOST_REQUIRE(m_received.size() >= EllSwiftPubKey::size());
1169 // Initialize the cipher using it (acting as the opposite side of the tested transport).
1170 m_cipher.Initialize(MakeByteSpan(m_received).first(EllSwiftPubKey::size()), !m_test_initiator);
1171 // Strip the processed bytes off the front of the receive buffer.
1172 m_received.erase(m_received.begin(), m_received.begin() + EllSwiftPubKey::size());
1173 }
1174
1177 void SendPacket(Span<const uint8_t> content, Span<const uint8_t> aad = {}, bool ignore = false)
1178 {
1179 // Use cipher to construct ciphertext.
1180 std::vector<std::byte> ciphertext;
1181 ciphertext.resize(content.size() + BIP324Cipher::EXPANSION);
1182 m_cipher.Encrypt(
1183 /*contents=*/MakeByteSpan(content),
1184 /*aad=*/MakeByteSpan(aad),
1185 /*ignore=*/ignore,
1186 /*output=*/ciphertext);
1187 // Schedule it for sending.
1188 Send(ciphertext);
1189 }
1190
1192 void SendGarbageTerm()
1193 {
1194 // Schedule the garbage terminator to be sent.
1195 Send(m_cipher.GetSendGarbageTerminator());
1196 }
1197
1199 void SendVersion(Span<const uint8_t> version_data = {}, bool vers_ignore = false)
1200 {
1202 // Set AAD to garbage only for first packet.
1203 if (!m_sent_aad) aad = m_sent_garbage;
1204 SendPacket(/*content=*/version_data, /*aad=*/aad, /*ignore=*/vers_ignore);
1205 m_sent_aad = true;
1206 }
1207
1211 std::vector<uint8_t> ReceivePacket(Span<const std::byte> aad = {})
1212 {
1213 std::vector<uint8_t> contents;
1214 // Loop as long as there are ignored packets that are to be skipped.
1215 while (true) {
1216 // When processing a packet, at least enough bytes for its length descriptor must be received.
1217 BOOST_REQUIRE(m_received.size() >= BIP324Cipher::LENGTH_LEN);
1218 // Decrypt the content length.
1219 size_t size = m_cipher.DecryptLength(MakeByteSpan(Span{m_received}.first(BIP324Cipher::LENGTH_LEN)));
1220 // Check that the full packet is in the receive buffer.
1221 BOOST_REQUIRE(m_received.size() >= size + BIP324Cipher::EXPANSION);
1222 // Decrypt the packet contents.
1223 contents.resize(size);
1224 bool ignore{false};
1225 bool ret = m_cipher.Decrypt(
1226 /*input=*/MakeByteSpan(
1227 Span{m_received}.first(size + BIP324Cipher::EXPANSION).subspan(BIP324Cipher::LENGTH_LEN)),
1228 /*aad=*/aad,
1229 /*ignore=*/ignore,
1230 /*contents=*/MakeWritableByteSpan(contents));
1232 // Don't expect AAD in further packets.
1233 aad = {};
1234 // Strip the processed packet's bytes off the front of the receive buffer.
1235 m_received.erase(m_received.begin(), m_received.begin() + size + BIP324Cipher::EXPANSION);
1236 // Stop if the ignore bit is not set on this packet.
1237 if (!ignore) break;
1238 }
1239 return contents;
1240 }
1241
1244 void ReceiveGarbage()
1245 {
1246 // Figure out the garbage length.
1247 size_t garblen;
1248 for (garblen = 0; garblen <= V2Transport::MAX_GARBAGE_LEN; ++garblen) {
1249 BOOST_REQUIRE(m_received.size() >= garblen + BIP324Cipher::GARBAGE_TERMINATOR_LEN);
1250 auto term_span = MakeByteSpan(Span{m_received}.subspan(garblen, BIP324Cipher::GARBAGE_TERMINATOR_LEN));
1251 if (std::ranges::equal(term_span, m_cipher.GetReceiveGarbageTerminator())) break;
1252 }
1253 // Copy the garbage to a buffer.
1254 m_recv_garbage.assign(m_received.begin(), m_received.begin() + garblen);
1255 // Strip garbage + garbage terminator off the front of the receive buffer.
1256 m_received.erase(m_received.begin(), m_received.begin() + garblen + BIP324Cipher::GARBAGE_TERMINATOR_LEN);
1257 }
1258
1260 void ReceiveVersion()
1261 {
1262 auto contents = ReceivePacket(/*aad=*/MakeByteSpan(m_recv_garbage));
1263 // Version packets from real BIP324 peers are expected to be empty, despite the fact that
1264 // this class supports *sending* non-empty version packets (to test that BIP324 peers
1265 // correctly ignore version packet contents).
1266 BOOST_CHECK(contents.empty());
1267 }
1268
1271 void ReceiveMessage(uint8_t short_id, Span<const uint8_t> payload)
1272 {
1273 auto ret = ReceivePacket();
1274 BOOST_CHECK(ret.size() == payload.size() + 1);
1275 BOOST_CHECK(ret[0] == short_id);
1276 BOOST_CHECK(std::ranges::equal(Span{ret}.subspan(1), payload));
1277 }
1278
1281 void ReceiveMessage(const std::string& m_type, Span<const uint8_t> payload)
1282 {
1283 auto ret = ReceivePacket();
1284 BOOST_REQUIRE(ret.size() == payload.size() + 1 + CMessageHeader::MESSAGE_TYPE_SIZE);
1285 BOOST_CHECK(ret[0] == 0);
1286 for (unsigned i = 0; i < 12; ++i) {
1287 if (i < m_type.size()) {
1288 BOOST_CHECK(ret[1 + i] == m_type[i]);
1289 } else {
1290 BOOST_CHECK(ret[1 + i] == 0);
1291 }
1292 }
1293 BOOST_CHECK(std::ranges::equal(Span{ret}.subspan(1 + CMessageHeader::MESSAGE_TYPE_SIZE), payload));
1294 }
1295
1298 void SendMessage(std::string mtype, Span<const uint8_t> payload)
1299 {
1300 // Construct contents consisting of 0x00 + 12-byte message type + payload.
1301 std::vector<uint8_t> contents(1 + CMessageHeader::MESSAGE_TYPE_SIZE + payload.size());
1302 std::copy(mtype.begin(), mtype.end(), reinterpret_cast<char*>(contents.data() + 1));
1303 std::copy(payload.begin(), payload.end(), contents.begin() + 1 + CMessageHeader::MESSAGE_TYPE_SIZE);
1304 // Send a packet with that as contents.
1305 SendPacket(contents);
1306 }
1307
1310 void SendMessage(uint8_t short_id, Span<const uint8_t> payload)
1311 {
1312 // Construct contents consisting of short_id + payload.
1313 std::vector<uint8_t> contents(1 + payload.size());
1314 contents[0] = short_id;
1315 std::copy(payload.begin(), payload.end(), contents.begin() + 1);
1316 // Send a packet with that as contents.
1317 SendPacket(contents);
1318 }
1319
1321 void CompareSessionIDs() const
1322 {
1323 auto info = m_transport.GetInfo();
1324 BOOST_CHECK(info.session_id);
1325 BOOST_CHECK(uint256(MakeUCharSpan(m_cipher.GetSessionID())) == *info.session_id);
1326 }
1327
1329 void Damage()
1330 {
1331 m_to_send[m_rng.randrange(m_to_send.size())] ^= (uint8_t{1} << m_rng.randrange(8));
1332 }
1333};
1334
1335} // namespace
1336
1337BOOST_AUTO_TEST_CASE(v2transport_test)
1338{
1339 // A mostly normal scenario, testing a transport in initiator mode.
1340 for (int i = 0; i < 10; ++i) {
1341 V2TransportTester tester(m_rng, true);
1342 auto ret = tester.Interact();
1343 BOOST_REQUIRE(ret && ret->empty());
1344 tester.SendKey();
1345 tester.SendGarbage();
1346 tester.ReceiveKey();
1347 tester.SendGarbageTerm();
1348 tester.SendVersion();
1349 ret = tester.Interact();
1350 BOOST_REQUIRE(ret && ret->empty());
1351 tester.ReceiveGarbage();
1352 tester.ReceiveVersion();
1353 tester.CompareSessionIDs();
1354 auto msg_data_1 = m_rng.randbytes<uint8_t>(m_rng.randrange(100000));
1355 auto msg_data_2 = m_rng.randbytes<uint8_t>(m_rng.randrange(1000));
1356 tester.SendMessage(uint8_t(4), msg_data_1); // cmpctblock short id
1357 tester.SendMessage(0, {}); // Invalidly encoded message
1358 tester.SendMessage("tx", msg_data_2); // 12-character encoded message type
1359 ret = tester.Interact();
1360 BOOST_REQUIRE(ret && ret->size() == 3);
1361 BOOST_CHECK((*ret)[0] && (*ret)[0]->m_type == "cmpctblock" && std::ranges::equal((*ret)[0]->m_recv, MakeByteSpan(msg_data_1)));
1362 BOOST_CHECK(!(*ret)[1]);
1363 BOOST_CHECK((*ret)[2] && (*ret)[2]->m_type == "tx" && std::ranges::equal((*ret)[2]->m_recv, MakeByteSpan(msg_data_2)));
1364
1365 // Then send a message with a bit error, expecting failure. It's possible this failure does
1366 // not occur immediately (when the length descriptor was modified), but it should come
1367 // eventually, and no messages can be delivered anymore.
1368 tester.SendMessage("bad", msg_data_1);
1369 tester.Damage();
1370 while (true) {
1371 ret = tester.Interact();
1372 if (!ret) break; // failure
1373 BOOST_CHECK(ret->size() == 0); // no message can be delivered
1374 // Send another message.
1375 auto msg_data_3 = m_rng.randbytes<uint8_t>(m_rng.randrange(10000));
1376 tester.SendMessage(uint8_t(12), msg_data_3); // getheaders short id
1377 }
1378 }
1379
1380 // Normal scenario, with a transport in responder node.
1381 for (int i = 0; i < 10; ++i) {
1382 V2TransportTester tester(m_rng, false);
1383 tester.SendKey();
1384 tester.SendGarbage();
1385 auto ret = tester.Interact();
1386 BOOST_REQUIRE(ret && ret->empty());
1387 tester.ReceiveKey();
1388 tester.SendGarbageTerm();
1389 tester.SendVersion();
1390 ret = tester.Interact();
1391 BOOST_REQUIRE(ret && ret->empty());
1392 tester.ReceiveGarbage();
1393 tester.ReceiveVersion();
1394 tester.CompareSessionIDs();
1395 auto msg_data_1 = m_rng.randbytes<uint8_t>(m_rng.randrange(100000));
1396 auto msg_data_2 = m_rng.randbytes<uint8_t>(m_rng.randrange(1000));
1397 tester.SendMessage(uint8_t(14), msg_data_1); // inv short id
1398 tester.SendMessage(uint8_t(19), msg_data_2); // pong short id
1399 ret = tester.Interact();
1400 BOOST_REQUIRE(ret && ret->size() == 2);
1401 BOOST_CHECK((*ret)[0] && (*ret)[0]->m_type == "inv" && std::ranges::equal((*ret)[0]->m_recv, MakeByteSpan(msg_data_1)));
1402 BOOST_CHECK((*ret)[1] && (*ret)[1]->m_type == "pong" && std::ranges::equal((*ret)[1]->m_recv, MakeByteSpan(msg_data_2)));
1403
1404 // Then send a too-large message.
1405 auto msg_data_3 = m_rng.randbytes<uint8_t>(4005000);
1406 tester.SendMessage(uint8_t(11), msg_data_3); // getdata short id
1407 ret = tester.Interact();
1408 BOOST_CHECK(!ret);
1409 }
1410
1411 // Various valid but unusual scenarios.
1412 for (int i = 0; i < 50; ++i) {
1414 bool initiator = m_rng.randbool();
1416 size_t garb_len = m_rng.randbool() ? 0 : V2Transport::MAX_GARBAGE_LEN;
1418 unsigned num_ignore_version = m_rng.randrange(10);
1420 auto ver_data = m_rng.randbytes<uint8_t>(m_rng.randbool() ? 0 : m_rng.randrange(1000));
1422 bool send_immediately = !initiator || m_rng.randbool();
1424 unsigned num_decoys_1 = m_rng.randrange(1000), num_decoys_2 = m_rng.randrange(1000);
1425 V2TransportTester tester(m_rng, initiator);
1426 if (send_immediately) {
1427 tester.SendKey();
1428 tester.SendGarbage(garb_len);
1429 }
1430 auto ret = tester.Interact();
1431 BOOST_REQUIRE(ret && ret->empty());
1432 if (!send_immediately) {
1433 tester.SendKey();
1434 tester.SendGarbage(garb_len);
1435 }
1436 tester.ReceiveKey();
1437 tester.SendGarbageTerm();
1438 for (unsigned v = 0; v < num_ignore_version; ++v) {
1439 size_t ver_ign_data_len = m_rng.randbool() ? 0 : m_rng.randrange(1000);
1440 auto ver_ign_data = m_rng.randbytes<uint8_t>(ver_ign_data_len);
1441 tester.SendVersion(ver_ign_data, true);
1442 }
1443 tester.SendVersion(ver_data, false);
1444 ret = tester.Interact();
1445 BOOST_REQUIRE(ret && ret->empty());
1446 tester.ReceiveGarbage();
1447 tester.ReceiveVersion();
1448 tester.CompareSessionIDs();
1449 for (unsigned d = 0; d < num_decoys_1; ++d) {
1450 auto decoy_data = m_rng.randbytes<uint8_t>(m_rng.randrange(1000));
1451 tester.SendPacket(/*content=*/decoy_data, /*aad=*/{}, /*ignore=*/true);
1452 }
1453 auto msg_data_1 = m_rng.randbytes<uint8_t>(m_rng.randrange(4000000));
1454 tester.SendMessage(uint8_t(28), msg_data_1);
1455 for (unsigned d = 0; d < num_decoys_2; ++d) {
1456 auto decoy_data = m_rng.randbytes<uint8_t>(m_rng.randrange(1000));
1457 tester.SendPacket(/*content=*/decoy_data, /*aad=*/{}, /*ignore=*/true);
1458 }
1459 auto msg_data_2 = m_rng.randbytes<uint8_t>(m_rng.randrange(1000));
1460 tester.SendMessage(uint8_t(13), msg_data_2); // headers short id
1461 // Send invalidly-encoded message
1462 tester.SendMessage(std::string("blocktxn\x00\x00\x00a", CMessageHeader::MESSAGE_TYPE_SIZE), {});
1463 tester.SendMessage("foobar", {}); // test receiving unknown message type
1464 tester.AddMessage("barfoo", {}); // test sending unknown message type
1465 ret = tester.Interact();
1466 BOOST_REQUIRE(ret && ret->size() == 4);
1467 BOOST_CHECK((*ret)[0] && (*ret)[0]->m_type == "addrv2" && std::ranges::equal((*ret)[0]->m_recv, MakeByteSpan(msg_data_1)));
1468 BOOST_CHECK((*ret)[1] && (*ret)[1]->m_type == "headers" && std::ranges::equal((*ret)[1]->m_recv, MakeByteSpan(msg_data_2)));
1469 BOOST_CHECK(!(*ret)[2]);
1470 BOOST_CHECK((*ret)[3] && (*ret)[3]->m_type == "foobar" && (*ret)[3]->m_recv.empty());
1471 tester.ReceiveMessage("barfoo", {});
1472 }
1473
1474 // Too long garbage (initiator).
1475 {
1476 V2TransportTester tester(m_rng, true);
1477 auto ret = tester.Interact();
1478 BOOST_REQUIRE(ret && ret->empty());
1479 tester.SendKey();
1480 tester.SendGarbage(V2Transport::MAX_GARBAGE_LEN + 1);
1481 tester.ReceiveKey();
1482 tester.SendGarbageTerm();
1483 ret = tester.Interact();
1484 BOOST_CHECK(!ret);
1485 }
1486
1487 // Too long garbage (responder).
1488 {
1489 V2TransportTester tester(m_rng, false);
1490 tester.SendKey();
1491 tester.SendGarbage(V2Transport::MAX_GARBAGE_LEN + 1);
1492 auto ret = tester.Interact();
1493 BOOST_REQUIRE(ret && ret->empty());
1494 tester.ReceiveKey();
1495 tester.SendGarbageTerm();
1496 ret = tester.Interact();
1497 BOOST_CHECK(!ret);
1498 }
1499
1500 // Send garbage that includes the first 15 garbage terminator bytes somewhere.
1501 {
1502 V2TransportTester tester(m_rng, true);
1503 auto ret = tester.Interact();
1504 BOOST_REQUIRE(ret && ret->empty());
1505 tester.SendKey();
1506 tester.ReceiveKey();
1508 size_t len_before = m_rng.randrange(V2Transport::MAX_GARBAGE_LEN - 16 + 1);
1510 size_t len_after = m_rng.randrange(V2Transport::MAX_GARBAGE_LEN - 16 - len_before + 1);
1511 // Construct len_before + 16 + len_after random bytes.
1512 auto garbage = m_rng.randbytes<uint8_t>(len_before + 16 + len_after);
1513 // Replace the designed 16 bytes in the middle with the to-be-sent garbage terminator.
1514 auto garb_term = MakeUCharSpan(tester.GetCipher().GetSendGarbageTerminator());
1515 std::copy(garb_term.begin(), garb_term.begin() + 16, garbage.begin() + len_before);
1516 // Introduce a bit error in the last byte of that copied garbage terminator, making only
1517 // the first 15 of them match.
1518 garbage[len_before + 15] ^= (uint8_t(1) << m_rng.randrange(8));
1519 tester.SendGarbage(garbage);
1520 tester.SendGarbageTerm();
1521 tester.SendVersion();
1522 ret = tester.Interact();
1523 BOOST_REQUIRE(ret && ret->empty());
1524 tester.ReceiveGarbage();
1525 tester.ReceiveVersion();
1526 tester.CompareSessionIDs();
1527 auto msg_data_1 = m_rng.randbytes<uint8_t>(4000000); // test that receiving 4M payload works
1528 auto msg_data_2 = m_rng.randbytes<uint8_t>(4000000); // test that sending 4M payload works
1529 tester.SendMessage(uint8_t(m_rng.randrange(223) + 33), {}); // unknown short id
1530 tester.SendMessage(uint8_t(2), msg_data_1); // "block" short id
1531 tester.AddMessage("blocktxn", msg_data_2); // schedule blocktxn to be sent to us
1532 ret = tester.Interact();
1533 BOOST_REQUIRE(ret && ret->size() == 2);
1534 BOOST_CHECK(!(*ret)[0]);
1535 BOOST_CHECK((*ret)[1] && (*ret)[1]->m_type == "block" && std::ranges::equal((*ret)[1]->m_recv, MakeByteSpan(msg_data_1)));
1536 tester.ReceiveMessage(uint8_t(3), msg_data_2); // "blocktxn" short id
1537 }
1538
1539 // Send correct network's V1 header
1540 {
1541 V2TransportTester tester(m_rng, false);
1542 tester.SendV1Version(Params().MessageStart());
1543 auto ret = tester.Interact();
1545 }
1546
1547 // Send wrong network's V1 header
1548 {
1549 V2TransportTester tester(m_rng, false);
1550 tester.SendV1Version(CChainParams::Main()->MessageStart());
1551 auto ret = tester.Interact();
1552 BOOST_CHECK(!ret);
1553 }
1554}
1555
ArgsManager gArgs
Definition: args.cpp:42
int ret
node::NodeContext m_node
Definition: bitcoin-gui.cpp:42
const CChainParams & Params()
Return the currently selected parameters.
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: args.cpp:546
bool SoftSetArg(const std::string &strArg, const std::string &strValue)
Set an argument if it doesn't already have a value.
Definition: args.cpp:530
The BIP324 packet cipher, encapsulating its key derivation, stream cipher, and AEAD.
Definition: bip324.h:20
Span< const std::byte > GetReceiveGarbageTerminator() const noexcept
Get the expected Garbage Terminator to receive.
Definition: bip324.h:93
Span< const std::byte > GetSendGarbageTerminator() const noexcept
Get the Garbage Terminator to send.
Definition: bip324.h:90
static constexpr unsigned GARBAGE_TERMINATOR_LEN
Definition: bip324.h:23
unsigned DecryptLength(Span< const std::byte > input) noexcept
Decrypt the length of a packet.
Definition: bip324.cpp:89
const EllSwiftPubKey & GetOurPubKey() const noexcept
Retrieve our public key.
Definition: bip324.h:54
bool Decrypt(Span< const std::byte > input, Span< const std::byte > aad, bool &ignore, Span< std::byte > contents) noexcept
Decrypt a packet.
Definition: bip324.cpp:100
Span< const std::byte > GetSessionID() const noexcept
Get the Session ID.
Definition: bip324.h:87
void Encrypt(Span< const std::byte > contents, Span< const std::byte > aad, bool ignore, Span< std::byte > output) noexcept
Encrypt a packet.
Definition: bip324.cpp:73
static constexpr unsigned LENGTH_LEN
Definition: bip324.h:25
static constexpr unsigned EXPANSION
Definition: bip324.h:27
void Initialize(const EllSwiftPubKey &their_pubkey, bool initiator, bool self_decrypt=false) noexcept
Initialize when the other side's public key is received.
Definition: bip324.cpp:34
A CService with information about it as peer.
Definition: protocol.h:367
static constexpr SerParams V1_NETWORK
Definition: protocol.h:408
static constexpr SerParams V2_NETWORK
Definition: protocol.h:409
static std::unique_ptr< const CChainParams > Main()
An encapsulated private key.
Definition: key.h:35
void Set(const T pbegin, const T pend, bool fCompressedIn)
Initialize using begin and end iterators to byte data.
Definition: key.h:103
Message header.
Definition: protocol.h:29
static constexpr size_t MESSAGE_TYPE_SIZE
Definition: protocol.h:31
Network address.
Definition: netaddress.h:112
std::string ToStringAddr() const
Definition: netaddress.cpp:584
bool IsBindAny() const
Definition: netaddress.cpp:307
bool SetSpecial(const std::string &addr)
Parse a Tor or I2P address and set this object to it.
Definition: netaddress.cpp:211
bool IsCJDNS() const
Definition: netaddress.h:176
bool IsTor() const
Definition: netaddress.h:174
bool IsValid() const
Definition: netaddress.cpp:428
bool IsIPv4() const
Definition: netaddress.h:157
bool IsIPv6() const
Definition: netaddress.h:158
bool IsInternal() const
Definition: netaddress.cpp:476
bool SetInternal(const std::string &name)
Create an "internal" address that represents a name or FQDN.
Definition: netaddress.cpp:172
bool IsAddrV1Compatible() const
Check if the current object can be serialized in pre-ADDRv2/BIP155 format.
Definition: netaddress.cpp:481
bool IsI2P() const
Definition: netaddress.h:175
Information about a peer.
Definition: net.h:673
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:531
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:147
value_type * data()
Definition: streams.h:188
Fast randomness source.
Definition: random.h:377
BOOST_CHECK_EXCEPTION predicates to check the specific validation error.
Definition: setup_common.h:295
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition: net.h:995
I randrange(I range) noexcept
Generate a random integer in the range [0..range), with range > 0.
Definition: random.h:254
bool randbool() noexcept
Generate a random boolean.
Definition: random.h:316
std::vector< B > randbytes(size_t len) noexcept
Generate random bytes.
Definition: random.h:297
void Add(Network net) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Definition: netbase.h:103
bool Contains(Network net) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Definition: netbase.h:124
void Remove(Network net) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Definition: netbase.h:110
void RemoveAll() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Definition: netbase.h:117
constexpr std::size_t size() const noexcept
Definition: span.h:187
CONSTEXPR_IF_NOT_DEBUG Span< C > subspan(std::size_t offset) const noexcept
Definition: span.h:195
CONSTEXPR_IF_NOT_DEBUG Span< C > first(std::size_t count) const noexcept
Definition: span.h:205
constexpr C * begin() const noexcept
Definition: span.h:175
constexpr C * end() const noexcept
Definition: span.h:176
void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Report how many bytes returned by the last GetBytesToSend() have been sent.
Definition: net.cpp:1507
static constexpr uint32_t MAX_GARBAGE_LEN
Definition: net.h:634
bool ReceivedBytes(Span< const uint8_t > &msg_bytes) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex
Feed wire bytes to the transport.
Definition: net.cpp:1299
Info GetInfo() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Retrieve information about this transport.
Definition: net.cpp:1555
BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Get bytes to send on the wire, if any, along with other information about it.
Definition: net.cpp:1490
bool ReceivedMessageComplete() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Returns true if the current message is complete (so GetReceivedMessage can be called).
Definition: net.cpp:1047
CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool &reject_message) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Retrieve a completed message from transport.
Definition: net.cpp:1429
bool SetMessageToSend(CSerializedNetMsg &msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Set the next message to send.
Definition: net.cpp:1458
constexpr unsigned char * end()
Definition: uint256.h:105
constexpr unsigned char * begin()
Definition: uint256.h:104
256-bit opaque blob.
Definition: uint256.h:190
@ OUTBOUND_FULL_RELAY
These are the default connections that we use to connect with the network.
@ INBOUND
Inbound connections are those initiated by a peer.
BOOST_FIXTURE_TEST_SUITE(cuckoocache_tests, BasicTestingSetup)
Test Suite for CuckooCache.
BOOST_AUTO_TEST_SUITE_END()
static CService ip(uint32_t i)
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:29
std::array< uint8_t, 4 > MessageStartChars
CSerializedNetMsg Make(std::string msg_type, Args &&... args)
constexpr const char * VERACK
The verack message acknowledges a previously-received version message, informing the connecting node ...
Definition: protocol.h:70
constexpr const char * VERSION
The version message provides information about the transmitting node to the receiving node at the beg...
Definition: protocol.h:65
""_hex is a compile-time user-defined literal returning a std::array<std::byte>, equivalent to ParseH...
Definition: strencodings.h:427
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:233
uint16_t GetListenPort()
Definition: net.cpp:140
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:325
void RemoveLocal(const CService &addr)
Definition: net.cpp:306
bool AddLocal(const CService &addr_, int nScore)
Definition: net.cpp:273
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
Definition: net.cpp:242
CService GetLocalAddress(const CNode &peer)
Definition: net.cpp:222
GlobalMutex g_maplocalhost_mutex
Definition: net.cpp:120
std::function< void(const CAddress &addr, const std::string &msg_type, Span< const unsigned char > data, bool is_incoming)> CaptureMessage
Defaults to CaptureMessageToFile(), but can be overridden by unit tests.
Definition: net.cpp:3955
int64_t NodeId
Definition: net.h:97
BOOST_AUTO_TEST_CASE(cnode_listen_port)
Definition: net_tests.cpp:40
CNetAddr UtilBuildAddress(unsigned char p1, unsigned char p2, unsigned char p3, unsigned char p4)
Definition: net_tests.cpp:763
@ NET_I2P
I2P.
Definition: netaddress.h:46
@ NET_CJDNS
CJDNS.
Definition: netaddress.h:49
@ NET_ONION
TOR (v2 or v3)
Definition: netaddress.h:43
@ NET_IPV6
IPv6.
Definition: netaddress.h:40
@ NET_IPV4
IPv4.
Definition: netaddress.h:37
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
Definition: netaddress.h:34
@ NET_INTERNAL
A set of addresses that represent the hash of a string or FQDN.
Definition: netaddress.h:53
std::vector< CNetAddr > LookupHost(const std::string &name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
Resolve a host string to its corresponding network addresses.
Definition: netbase.cpp:177
std::vector< CService > Lookup(const std::string &name, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
Resolve a service string to its corresponding service.
Definition: netbase.cpp:195
CService MaybeFlipIPv6toCJDNS(const CService &service)
If an IPv6 address belongs to the address range used by the CJDNS network and the CJDNS network is re...
Definition: netbase.cpp:882
ReachableNets g_reachable_nets
Definition: netbase.cpp:43
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18
#define BOOST_CHECK(expr)
Definition: object.cpp:17
@ NODE_NONE
Definition: protocol.h:312
@ NODE_WITNESS
Definition: protocol.h:320
@ NODE_NETWORK
Definition: protocol.h:315
static const int PROTOCOL_VERSION
network protocol versioning
Span< const std::byte > MakeByteSpan(V &&v) noexcept
Definition: span.h:270
constexpr auto MakeUCharSpan(V &&v) -> decltype(UCharSpanCast(Span{std::forward< V >(v)}))
Like the Span constructor, but for (const) unsigned char member types only.
Definition: span.h:297
unsigned char * UCharCast(char *c)
Definition: span.h:281
Span< std::byte > MakeWritableByteSpan(V &&v) noexcept
Definition: span.h:275
static constexpr size_t size()
Definition: pubkey.h:327
uint16_t nPort
Definition: net.h:175
int nScore
Definition: net.h:174
Identical to TestingSetup, but chain set to regtest.
Definition: setup_common.h:127
void JumpOutOfIbd()
Toggle IsInitialBlockDownload from true to false.
Definition: validation.cpp:18
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:72
std::unique_ptr< PeerManager > peerman
Definition: context.h:71
ArgsManager * args
Definition: context.h:74
#define LOCK(cs)
Definition: sync.h:257
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1165
std::string ToLower(std::string_view str)
Returns the lowercase equivalent of the given string.