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