Bitcoin Core  24.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 <compat/compat.h>
8 #include <cstdint>
9 #include <net.h>
10 #include <net_processing.h>
11 #include <netaddress.h>
12 #include <netbase.h>
13 #include <netmessagemaker.h>
14 #include <serialize.h>
15 #include <span.h>
16 #include <streams.h>
17 #include <test/util/setup_common.h>
18 #include <test/util/validation.h>
19 #include <timedata.h>
20 #include <util/strencodings.h>
21 #include <util/string.h>
22 #include <util/system.h>
23 #include <validation.h>
24 #include <version.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 
36 BOOST_FIXTURE_TEST_SUITE(net_tests, RegTestingSetup)
37 
38 BOOST_AUTO_TEST_CASE(cnode_listen_port)
39 {
40  // test default
41  uint16_t port{GetListenPort()};
42  BOOST_CHECK(port == Params().GetDefaultPort());
43  // test set port
44  uint16_t altPort = 12345;
45  BOOST_CHECK(gArgs.SoftSetArg("-port", ToString(altPort)));
46  port = GetListenPort();
47  BOOST_CHECK(port == altPort);
48 }
49 
50 BOOST_AUTO_TEST_CASE(cnode_simple_test)
51 {
52  NodeId id = 0;
53 
54  in_addr ipv4Addr;
55  ipv4Addr.s_addr = 0xa0b0c001;
56 
57  CAddress addr = CAddress(CService(ipv4Addr, 7777), NODE_NETWORK);
58  std::string pszDest;
59 
60  std::unique_ptr<CNode> pnode1 = std::make_unique<CNode>(id++,
61  /*sock=*/nullptr,
62  addr,
63  /*nKeyedNetGroupIn=*/0,
64  /*nLocalHostNonceIn=*/0,
65  CAddress(),
66  pszDest,
68  /*inbound_onion=*/false);
69  BOOST_CHECK(pnode1->IsFullOutboundConn() == true);
70  BOOST_CHECK(pnode1->IsManualConn() == false);
71  BOOST_CHECK(pnode1->IsBlockOnlyConn() == false);
72  BOOST_CHECK(pnode1->IsFeelerConn() == false);
73  BOOST_CHECK(pnode1->IsAddrFetchConn() == false);
74  BOOST_CHECK(pnode1->IsInboundConn() == false);
75  BOOST_CHECK(pnode1->m_inbound_onion == false);
76  BOOST_CHECK_EQUAL(pnode1->ConnectedThroughNetwork(), Network::NET_IPV4);
77 
78  std::unique_ptr<CNode> pnode2 = std::make_unique<CNode>(id++,
79  /*sock=*/nullptr,
80  addr,
81  /*nKeyedNetGroupIn=*/1,
82  /*nLocalHostNonceIn=*/1,
83  CAddress(),
84  pszDest,
86  /*inbound_onion=*/false);
87  BOOST_CHECK(pnode2->IsFullOutboundConn() == false);
88  BOOST_CHECK(pnode2->IsManualConn() == false);
89  BOOST_CHECK(pnode2->IsBlockOnlyConn() == false);
90  BOOST_CHECK(pnode2->IsFeelerConn() == false);
91  BOOST_CHECK(pnode2->IsAddrFetchConn() == false);
92  BOOST_CHECK(pnode2->IsInboundConn() == true);
93  BOOST_CHECK(pnode2->m_inbound_onion == false);
94  BOOST_CHECK_EQUAL(pnode2->ConnectedThroughNetwork(), Network::NET_IPV4);
95 
96  std::unique_ptr<CNode> pnode3 = std::make_unique<CNode>(id++,
97  /*sock=*/nullptr,
98  addr,
99  /*nKeyedNetGroupIn=*/0,
100  /*nLocalHostNonceIn=*/0,
101  CAddress(),
102  pszDest,
104  /*inbound_onion=*/false);
105  BOOST_CHECK(pnode3->IsFullOutboundConn() == true);
106  BOOST_CHECK(pnode3->IsManualConn() == false);
107  BOOST_CHECK(pnode3->IsBlockOnlyConn() == false);
108  BOOST_CHECK(pnode3->IsFeelerConn() == false);
109  BOOST_CHECK(pnode3->IsAddrFetchConn() == false);
110  BOOST_CHECK(pnode3->IsInboundConn() == false);
111  BOOST_CHECK(pnode3->m_inbound_onion == false);
112  BOOST_CHECK_EQUAL(pnode3->ConnectedThroughNetwork(), Network::NET_IPV4);
113 
114  std::unique_ptr<CNode> pnode4 = std::make_unique<CNode>(id++,
115  /*sock=*/nullptr,
116  addr,
117  /*nKeyedNetGroupIn=*/1,
118  /*nLocalHostNonceIn=*/1,
119  CAddress(),
120  pszDest,
122  /*inbound_onion=*/true);
123  BOOST_CHECK(pnode4->IsFullOutboundConn() == false);
124  BOOST_CHECK(pnode4->IsManualConn() == false);
125  BOOST_CHECK(pnode4->IsBlockOnlyConn() == false);
126  BOOST_CHECK(pnode4->IsFeelerConn() == false);
127  BOOST_CHECK(pnode4->IsAddrFetchConn() == false);
128  BOOST_CHECK(pnode4->IsInboundConn() == true);
129  BOOST_CHECK(pnode4->m_inbound_onion == true);
130  BOOST_CHECK_EQUAL(pnode4->ConnectedThroughNetwork(), Network::NET_ONION);
131 }
132 
133 BOOST_AUTO_TEST_CASE(cnetaddr_basic)
134 {
135  CNetAddr addr;
136 
137  // IPv4, INADDR_ANY
138  BOOST_REQUIRE(LookupHost("0.0.0.0", addr, false));
139  BOOST_REQUIRE(!addr.IsValid());
140  BOOST_REQUIRE(addr.IsIPv4());
141 
142  BOOST_CHECK(addr.IsBindAny());
144  BOOST_CHECK_EQUAL(addr.ToStringAddr(), "0.0.0.0");
145 
146  // IPv4, INADDR_NONE
147  BOOST_REQUIRE(LookupHost("255.255.255.255", addr, false));
148  BOOST_REQUIRE(!addr.IsValid());
149  BOOST_REQUIRE(addr.IsIPv4());
150 
151  BOOST_CHECK(!addr.IsBindAny());
153  BOOST_CHECK_EQUAL(addr.ToStringAddr(), "255.255.255.255");
154 
155  // IPv4, casual
156  BOOST_REQUIRE(LookupHost("12.34.56.78", addr, false));
157  BOOST_REQUIRE(addr.IsValid());
158  BOOST_REQUIRE(addr.IsIPv4());
159 
160  BOOST_CHECK(!addr.IsBindAny());
162  BOOST_CHECK_EQUAL(addr.ToStringAddr(), "12.34.56.78");
163 
164  // IPv6, in6addr_any
165  BOOST_REQUIRE(LookupHost("::", addr, false));
166  BOOST_REQUIRE(!addr.IsValid());
167  BOOST_REQUIRE(addr.IsIPv6());
168 
169  BOOST_CHECK(addr.IsBindAny());
171  BOOST_CHECK_EQUAL(addr.ToStringAddr(), "::");
172 
173  // IPv6, casual
174  BOOST_REQUIRE(LookupHost("1122:3344:5566:7788:9900:aabb:ccdd:eeff", addr, false));
175  BOOST_REQUIRE(addr.IsValid());
176  BOOST_REQUIRE(addr.IsIPv6());
177 
178  BOOST_CHECK(!addr.IsBindAny());
180  BOOST_CHECK_EQUAL(addr.ToStringAddr(), "1122:3344:5566:7788:9900:aabb:ccdd:eeff");
181 
182  // IPv6, scoped/link-local. See https://tools.ietf.org/html/rfc4007
183  // We support non-negative decimal integers (uint32_t) as zone id indices.
184  // Normal link-local scoped address functionality is to append "%" plus the
185  // zone id, for example, given a link-local address of "fe80::1" and a zone
186  // id of "32", return the address as "fe80::1%32".
187  const std::string link_local{"fe80::1"};
188  const std::string scoped_addr{link_local + "%32"};
189  BOOST_REQUIRE(LookupHost(scoped_addr, addr, false));
190  BOOST_REQUIRE(addr.IsValid());
191  BOOST_REQUIRE(addr.IsIPv6());
192  BOOST_CHECK(!addr.IsBindAny());
193  BOOST_CHECK_EQUAL(addr.ToStringAddr(), scoped_addr);
194 
195  // Test that the delimiter "%" and default zone id of 0 can be omitted for the default scope.
196  BOOST_REQUIRE(LookupHost(link_local + "%0", addr, false));
197  BOOST_REQUIRE(addr.IsValid());
198  BOOST_REQUIRE(addr.IsIPv6());
199  BOOST_CHECK(!addr.IsBindAny());
200  BOOST_CHECK_EQUAL(addr.ToStringAddr(), link_local);
201 
202  // TORv2, no longer supported
203  BOOST_CHECK(!addr.SetSpecial("6hzph5hv6337r6p2.onion"));
204 
205  // TORv3
206  const char* torv3_addr = "pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion";
207  BOOST_REQUIRE(addr.SetSpecial(torv3_addr));
208  BOOST_REQUIRE(addr.IsValid());
209  BOOST_REQUIRE(addr.IsTor());
210 
211  BOOST_CHECK(!addr.IsI2P());
212  BOOST_CHECK(!addr.IsBindAny());
214  BOOST_CHECK_EQUAL(addr.ToStringAddr(), torv3_addr);
215 
216  // TORv3, broken, with wrong checksum
217  BOOST_CHECK(!addr.SetSpecial("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscsad.onion"));
218 
219  // TORv3, broken, with wrong version
220  BOOST_CHECK(!addr.SetSpecial("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscrye.onion"));
221 
222  // TORv3, malicious
223  BOOST_CHECK(!addr.SetSpecial(std::string{
224  "pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd\0wtf.onion", 66}));
225 
226  // TOR, bogus length
227  BOOST_CHECK(!addr.SetSpecial(std::string{"mfrggzak.onion"}));
228 
229  // TOR, invalid base32
230  BOOST_CHECK(!addr.SetSpecial(std::string{"mf*g zak.onion"}));
231 
232  // I2P
233  const char* i2p_addr = "UDHDrtrcetjm5sxzskjyr5ztpeszydbh4dpl3pl4utgqqw2v4jna.b32.I2P";
234  BOOST_REQUIRE(addr.SetSpecial(i2p_addr));
235  BOOST_REQUIRE(addr.IsValid());
236  BOOST_REQUIRE(addr.IsI2P());
237 
238  BOOST_CHECK(!addr.IsTor());
239  BOOST_CHECK(!addr.IsBindAny());
241  BOOST_CHECK_EQUAL(addr.ToStringAddr(), ToLower(i2p_addr));
242 
243  // I2P, correct length, but decodes to less than the expected number of bytes.
244  BOOST_CHECK(!addr.SetSpecial("udhdrtrcetjm5sxzskjyr5ztpeszydbh4dpl3pl4utgqqw2v4jn=.b32.i2p"));
245 
246  // I2P, extra unnecessary padding
247  BOOST_CHECK(!addr.SetSpecial("udhdrtrcetjm5sxzskjyr5ztpeszydbh4dpl3pl4utgqqw2v4jna=.b32.i2p"));
248 
249  // I2P, malicious
250  BOOST_CHECK(!addr.SetSpecial("udhdrtrcetjm5sxzskjyr5ztpeszydbh4dpl3pl4utgqqw2v\0wtf.b32.i2p"s));
251 
252  // I2P, valid but unsupported (56 Base32 characters)
253  // See "Encrypted LS with Base 32 Addresses" in
254  // https://geti2p.net/spec/encryptedleaseset.txt
255  BOOST_CHECK(
256  !addr.SetSpecial("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscsad.b32.i2p"));
257 
258  // I2P, invalid base32
259  BOOST_CHECK(!addr.SetSpecial(std::string{"tp*szydbh4dp.b32.i2p"}));
260 
261  // Internal
262  addr.SetInternal("esffpp");
263  BOOST_REQUIRE(!addr.IsValid()); // "internal" is considered invalid
264  BOOST_REQUIRE(addr.IsInternal());
265 
266  BOOST_CHECK(!addr.IsBindAny());
268  BOOST_CHECK_EQUAL(addr.ToStringAddr(), "esffpvrt3wpeaygy.internal");
269 
270  // Totally bogus
271  BOOST_CHECK(!addr.SetSpecial("totally bogus"));
272 }
273 
274 BOOST_AUTO_TEST_CASE(cnetaddr_tostring_canonical_ipv6)
275 {
276  // Test that CNetAddr::ToString formats IPv6 addresses with zero compression as described in
277  // RFC 5952 ("A Recommendation for IPv6 Address Text Representation").
278  const std::map<std::string, std::string> canonical_representations_ipv6{
279  {"0000:0000:0000:0000:0000:0000:0000:0000", "::"},
280  {"000:0000:000:00:0:00:000:0000", "::"},
281  {"000:000:000:000:000:000:000:000", "::"},
282  {"00:00:00:00:00:00:00:00", "::"},
283  {"0:0:0:0:0:0:0:0", "::"},
284  {"0:0:0:0:0:0:0:1", "::1"},
285  {"2001:0:0:1:0:0:0:1", "2001:0:0:1::1"},
286  {"2001:0db8:0:0:1:0:0:1", "2001:db8::1:0:0:1"},
287  {"2001:0db8:85a3:0000:0000:8a2e:0370:7334", "2001:db8:85a3::8a2e:370:7334"},
288  {"2001:0db8::0001", "2001:db8::1"},
289  {"2001:0db8::0001:0000", "2001:db8::1:0"},
290  {"2001:0db8::1:0:0:1", "2001:db8::1:0:0:1"},
291  {"2001:db8:0000:0:1::1", "2001:db8::1:0:0:1"},
292  {"2001:db8:0000:1:1:1:1:1", "2001:db8:0:1:1:1:1:1"},
293  {"2001:db8:0:0:0:0:2:1", "2001:db8::2:1"},
294  {"2001:db8:0:0:0::1", "2001:db8::1"},
295  {"2001:db8:0:0:1:0:0: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::1", "2001:db8::1:0:0:1"},
298  {"2001:db8:0:0::1", "2001:db8::1"},
299  {"2001:db8:0:0:aaaa::1", "2001:db8::aaaa:0:0:1"},
300  {"2001:db8:0:1:1:1:1:1", "2001:db8:0:1:1:1:1:1"},
301  {"2001:db8:0::1", "2001:db8::1"},
302  {"2001:db8:85a3:0:0:8a2e:370:7334", "2001:db8:85a3::8a2e:370:7334"},
303  {"2001:db8::0:1", "2001:db8::1"},
304  {"2001:db8::0:1:0:0:1", "2001:db8::1:0:0:1"},
305  {"2001:DB8::1", "2001:db8::1"},
306  {"2001:db8::1", "2001:db8::1"},
307  {"2001:db8::1:0:0:1", "2001:db8::1:0:0:1"},
308  {"2001:db8::1:1:1:1:1", "2001:db8:0:1:1:1:1:1"},
309  {"2001:db8::aaaa:0:0:1", "2001:db8::aaaa:0:0:1"},
310  {"2001:db8:aaaa:bbbb:cccc:dddd:0:1", "2001:db8:aaaa:bbbb:cccc:dddd:0:1"},
311  {"2001:db8:aaaa:bbbb:cccc:dddd::1", "2001:db8:aaaa:bbbb:cccc:dddd:0:1"},
312  {"2001:db8:aaaa:bbbb:cccc:dddd:eeee:0001", "2001:db8:aaaa:bbbb:cccc:dddd:eeee:1"},
313  {"2001:db8:aaaa:bbbb:cccc:dddd:eeee:001", "2001:db8:aaaa:bbbb:cccc:dddd:eeee:1"},
314  {"2001:db8:aaaa:bbbb:cccc:dddd:eeee:01", "2001:db8:aaaa:bbbb:cccc:dddd:eeee:1"},
315  {"2001:db8:aaaa:bbbb:cccc:dddd:eeee:1", "2001:db8:aaaa:bbbb:cccc:dddd:eeee:1"},
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  {"2001:db8:aaaa:bbbb:cccc:dddd:eeee:AaAa", "2001:db8:aaaa:bbbb:cccc:dddd:eeee:aaaa"},
319  };
320  for (const auto& [input_address, expected_canonical_representation_output] : canonical_representations_ipv6) {
321  CNetAddr net_addr;
322  BOOST_REQUIRE(LookupHost(input_address, net_addr, false));
323  BOOST_REQUIRE(net_addr.IsIPv6());
324  BOOST_CHECK_EQUAL(net_addr.ToStringAddr(), expected_canonical_representation_output);
325  }
326 }
327 
328 BOOST_AUTO_TEST_CASE(cnetaddr_serialize_v1)
329 {
330  CNetAddr addr;
332 
333  s << addr;
334  BOOST_CHECK_EQUAL(HexStr(s), "00000000000000000000000000000000");
335  s.clear();
336 
337  BOOST_REQUIRE(LookupHost("1.2.3.4", addr, false));
338  s << addr;
339  BOOST_CHECK_EQUAL(HexStr(s), "00000000000000000000ffff01020304");
340  s.clear();
341 
342  BOOST_REQUIRE(LookupHost("1a1b:2a2b:3a3b:4a4b:5a5b:6a6b:7a7b:8a8b", addr, false));
343  s << addr;
344  BOOST_CHECK_EQUAL(HexStr(s), "1a1b2a2b3a3b4a4b5a5b6a6b7a7b8a8b");
345  s.clear();
346 
347  // TORv2, no longer supported
348  BOOST_CHECK(!addr.SetSpecial("6hzph5hv6337r6p2.onion"));
349 
350  BOOST_REQUIRE(addr.SetSpecial("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion"));
351  s << addr;
352  BOOST_CHECK_EQUAL(HexStr(s), "00000000000000000000000000000000");
353  s.clear();
354 
355  addr.SetInternal("a");
356  s << addr;
357  BOOST_CHECK_EQUAL(HexStr(s), "fd6b88c08724ca978112ca1bbdcafac2");
358  s.clear();
359 }
360 
361 BOOST_AUTO_TEST_CASE(cnetaddr_serialize_v2)
362 {
363  CNetAddr addr;
365  // Add ADDRV2_FORMAT to the version so that the CNetAddr
366  // serialize method produces an address in v2 format.
368 
369  s << addr;
370  BOOST_CHECK_EQUAL(HexStr(s), "021000000000000000000000000000000000");
371  s.clear();
372 
373  BOOST_REQUIRE(LookupHost("1.2.3.4", addr, false));
374  s << addr;
375  BOOST_CHECK_EQUAL(HexStr(s), "010401020304");
376  s.clear();
377 
378  BOOST_REQUIRE(LookupHost("1a1b:2a2b:3a3b:4a4b:5a5b:6a6b:7a7b:8a8b", addr, false));
379  s << 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 << addr;
388  BOOST_CHECK_EQUAL(HexStr(s), "042053cd5648488c4707914182655b7664034e09e66f7e8cbf1084e654eb56c5bd88");
389  s.clear();
390 
391  BOOST_REQUIRE(addr.SetInternal("a"));
392  s << addr;
393  BOOST_CHECK_EQUAL(HexStr(s), "0210fd6b88c08724ca978112ca1bbdcafac2");
394  s.clear();
395 }
396 
397 BOOST_AUTO_TEST_CASE(cnetaddr_unserialize_v2)
398 {
399  CNetAddr addr;
401  // Add ADDRV2_FORMAT to the version so that the CNetAddr
402  // unserialize method expects an address in v2 format.
404 
405  // Valid IPv4.
406  s << Span{ParseHex("01" // network type (IPv4)
407  "04" // address length
408  "01020304")}; // address
409  s >> addr;
410  BOOST_CHECK(addr.IsValid());
411  BOOST_CHECK(addr.IsIPv4());
413  BOOST_CHECK_EQUAL(addr.ToStringAddr(), "1.2.3.4");
414  BOOST_REQUIRE(s.empty());
415 
416  // Invalid IPv4, valid length but address itself is shorter.
417  s << Span{ParseHex("01" // network type (IPv4)
418  "04" // address length
419  "0102")}; // address
420  BOOST_CHECK_EXCEPTION(s >> addr, std::ios_base::failure, HasReason("end of data"));
421  BOOST_REQUIRE(!s.empty()); // The stream is not consumed on invalid input.
422  s.clear();
423 
424  // Invalid IPv4, with bogus length.
425  s << Span{ParseHex("01" // network type (IPv4)
426  "05" // address length
427  "01020304")}; // address
428  BOOST_CHECK_EXCEPTION(s >> addr, std::ios_base::failure,
429  HasReason("BIP155 IPv4 address with length 5 (should be 4)"));
430  BOOST_REQUIRE(!s.empty()); // The stream is not consumed on invalid input.
431  s.clear();
432 
433  // Invalid IPv4, with extreme length.
434  s << Span{ParseHex("01" // network type (IPv4)
435  "fd0102" // address length (513 as CompactSize)
436  "01020304")}; // address
437  BOOST_CHECK_EXCEPTION(s >> addr, std::ios_base::failure,
438  HasReason("Address too long: 513 > 512"));
439  BOOST_REQUIRE(!s.empty()); // The stream is not consumed on invalid input.
440  s.clear();
441 
442  // Valid IPv6.
443  s << Span{ParseHex("02" // network type (IPv6)
444  "10" // address length
445  "0102030405060708090a0b0c0d0e0f10")}; // address
446  s >> addr;
447  BOOST_CHECK(addr.IsValid());
448  BOOST_CHECK(addr.IsIPv6());
450  BOOST_CHECK_EQUAL(addr.ToStringAddr(), "102:304:506:708:90a:b0c:d0e:f10");
451  BOOST_REQUIRE(s.empty());
452 
453  // Valid IPv6, contains embedded "internal".
454  s << Span{ParseHex(
455  "02" // network type (IPv6)
456  "10" // address length
457  "fd6b88c08724ca978112ca1bbdcafac2")}; // address: 0xfd + sha256("bitcoin")[0:5] +
458  // sha256(name)[0:10]
459  s >> addr;
460  BOOST_CHECK(addr.IsInternal());
462  BOOST_CHECK_EQUAL(addr.ToStringAddr(), "zklycewkdo64v6wc.internal");
463  BOOST_REQUIRE(s.empty());
464 
465  // Invalid IPv6, with bogus length.
466  s << Span{ParseHex("02" // network type (IPv6)
467  "04" // address length
468  "00")}; // address
469  BOOST_CHECK_EXCEPTION(s >> addr, std::ios_base::failure,
470  HasReason("BIP155 IPv6 address with length 4 (should be 16)"));
471  BOOST_REQUIRE(!s.empty()); // The stream is not consumed on invalid input.
472  s.clear();
473 
474  // Invalid IPv6, contains embedded IPv4.
475  s << Span{ParseHex("02" // network type (IPv6)
476  "10" // address length
477  "00000000000000000000ffff01020304")}; // address
478  s >> addr;
479  BOOST_CHECK(!addr.IsValid());
480  BOOST_REQUIRE(s.empty());
481 
482  // Invalid IPv6, contains embedded TORv2.
483  s << Span{ParseHex("02" // network type (IPv6)
484  "10" // address length
485  "fd87d87eeb430102030405060708090a")}; // address
486  s >> addr;
487  BOOST_CHECK(!addr.IsValid());
488  BOOST_REQUIRE(s.empty());
489 
490  // TORv2, no longer supported.
491  s << Span{ParseHex("03" // network type (TORv2)
492  "0a" // address length
493  "f1f2f3f4f5f6f7f8f9fa")}; // address
494  s >> addr;
495  BOOST_CHECK(!addr.IsValid());
496  BOOST_REQUIRE(s.empty());
497 
498  // Valid TORv3.
499  s << Span{ParseHex("04" // network type (TORv3)
500  "20" // address length
501  "79bcc625184b05194975c28b66b66b04" // address
502  "69f7f6556fb1ac3189a79b40dda32f1f"
503  )};
504  s >> addr;
505  BOOST_CHECK(addr.IsValid());
506  BOOST_CHECK(addr.IsTor());
509  "pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion");
510  BOOST_REQUIRE(s.empty());
511 
512  // Invalid TORv3, with bogus length.
513  s << Span{ParseHex("04" // network type (TORv3)
514  "00" // address length
515  "00" // address
516  )};
517  BOOST_CHECK_EXCEPTION(s >> addr, std::ios_base::failure,
518  HasReason("BIP155 TORv3 address with length 0 (should be 32)"));
519  BOOST_REQUIRE(!s.empty()); // The stream is not consumed on invalid input.
520  s.clear();
521 
522  // Valid I2P.
523  s << Span{ParseHex("05" // network type (I2P)
524  "20" // address length
525  "a2894dabaec08c0051a481a6dac88b64" // address
526  "f98232ae42d4b6fd2fa81952dfe36a87")};
527  s >> addr;
528  BOOST_CHECK(addr.IsValid());
529  BOOST_CHECK(addr.IsI2P());
532  "ukeu3k5oycgaauneqgtnvselmt4yemvoilkln7jpvamvfx7dnkdq.b32.i2p");
533  BOOST_REQUIRE(s.empty());
534 
535  // Invalid I2P, with bogus length.
536  s << Span{ParseHex("05" // network type (I2P)
537  "03" // address length
538  "00" // address
539  )};
540  BOOST_CHECK_EXCEPTION(s >> addr, std::ios_base::failure,
541  HasReason("BIP155 I2P address with length 3 (should be 32)"));
542  BOOST_REQUIRE(!s.empty()); // The stream is not consumed on invalid input.
543  s.clear();
544 
545  // Valid CJDNS.
546  s << Span{ParseHex("06" // network type (CJDNS)
547  "10" // address length
548  "fc000001000200030004000500060007" // address
549  )};
550  s >> addr;
551  BOOST_CHECK(addr.IsValid());
552  BOOST_CHECK(addr.IsCJDNS());
554  BOOST_CHECK_EQUAL(addr.ToStringAddr(), "fc00:1:2:3:4:5:6:7");
555  BOOST_REQUIRE(s.empty());
556 
557  // Invalid CJDNS, wrong prefix.
558  s << Span{ParseHex("06" // network type (CJDNS)
559  "10" // address length
560  "aa000001000200030004000500060007" // address
561  )};
562  s >> addr;
563  BOOST_CHECK(addr.IsCJDNS());
564  BOOST_CHECK(!addr.IsValid());
565  BOOST_REQUIRE(s.empty());
566 
567  // Invalid CJDNS, with bogus length.
568  s << Span{ParseHex("06" // network type (CJDNS)
569  "01" // address length
570  "00" // address
571  )};
572  BOOST_CHECK_EXCEPTION(s >> addr, std::ios_base::failure,
573  HasReason("BIP155 CJDNS address with length 1 (should be 16)"));
574  BOOST_REQUIRE(!s.empty()); // The stream is not consumed on invalid input.
575  s.clear();
576 
577  // Unknown, with extreme length.
578  s << Span{ParseHex("aa" // network type (unknown)
579  "fe00000002" // address length (CompactSize's MAX_SIZE)
580  "01020304050607" // address
581  )};
582  BOOST_CHECK_EXCEPTION(s >> addr, std::ios_base::failure,
583  HasReason("Address too long: 33554432 > 512"));
584  BOOST_REQUIRE(!s.empty()); // The stream is not consumed on invalid input.
585  s.clear();
586 
587  // Unknown, with reasonable length.
588  s << Span{ParseHex("aa" // network type (unknown)
589  "04" // address length
590  "01020304" // address
591  )};
592  s >> addr;
593  BOOST_CHECK(!addr.IsValid());
594  BOOST_REQUIRE(s.empty());
595 
596  // Unknown, with zero length.
597  s << Span{ParseHex("aa" // network type (unknown)
598  "00" // address length
599  "" // address
600  )};
601  s >> addr;
602  BOOST_CHECK(!addr.IsValid());
603  BOOST_REQUIRE(s.empty());
604 }
605 
606 // prior to PR #14728, this test triggers an undefined behavior
607 BOOST_AUTO_TEST_CASE(ipv4_peer_with_ipv6_addrMe_test)
608 {
609  // set up local addresses; all that's necessary to reproduce the bug is
610  // that a normal IPv4 address is among the entries, but if this address is
611  // !IsRoutable the undefined behavior is easier to trigger deterministically
612  in_addr raw_addr;
613  raw_addr.s_addr = htonl(0x7f000001);
614  const CNetAddr mapLocalHost_entry = CNetAddr(raw_addr);
615  {
617  LocalServiceInfo lsi;
618  lsi.nScore = 23;
619  lsi.nPort = 42;
620  mapLocalHost[mapLocalHost_entry] = lsi;
621  }
622 
623  // create a peer with an IPv4 address
624  in_addr ipv4AddrPeer;
625  ipv4AddrPeer.s_addr = 0xa0b0c001;
626  CAddress addr = CAddress(CService(ipv4AddrPeer, 7777), NODE_NETWORK);
627  std::unique_ptr<CNode> pnode = std::make_unique<CNode>(/*id=*/0,
628  /*sock=*/nullptr,
629  addr,
630  /*nKeyedNetGroupIn=*/0,
631  /*nLocalHostNonceIn=*/0,
632  CAddress{},
633  /*pszDest=*/std::string{},
635  /*inbound_onion=*/false);
636  pnode->fSuccessfullyConnected.store(true);
637 
638  // the peer claims to be reaching us via IPv6
639  in6_addr ipv6AddrLocal;
640  memset(ipv6AddrLocal.s6_addr, 0, 16);
641  ipv6AddrLocal.s6_addr[0] = 0xcc;
642  CAddress addrLocal = CAddress(CService(ipv6AddrLocal, 7777), NODE_NETWORK);
643  pnode->SetAddrLocal(addrLocal);
644 
645  // before patch, this causes undefined behavior detectable with clang's -fsanitize=memory
646  GetLocalAddrForPeer(*pnode);
647 
648  // suppress no-checks-run warning; if this test fails, it's by triggering a sanitizer
649  BOOST_CHECK(1);
650 
651  // Cleanup, so that we don't confuse other tests.
652  {
654  mapLocalHost.erase(mapLocalHost_entry);
655  }
656 }
657 
658 BOOST_AUTO_TEST_CASE(get_local_addr_for_peer_port)
659 {
660  // Test that GetLocalAddrForPeer() properly selects the address to self-advertise:
661  //
662  // 1. GetLocalAddrForPeer() calls GetLocalAddress() which returns an address that is
663  // not routable.
664  // 2. GetLocalAddrForPeer() overrides the address with whatever the peer has told us
665  // he sees us as.
666  // 2.1. For inbound connections we must override both the address and the port.
667  // 2.2. For outbound connections we must override only the address.
668 
669  // Pretend that we bound to this port.
670  const uint16_t bind_port = 20001;
671  m_node.args->ForceSetArg("-bind", strprintf("3.4.5.6:%u", bind_port));
672 
673  // Our address:port as seen from the peer, completely different from the above.
674  in_addr peer_us_addr;
675  peer_us_addr.s_addr = htonl(0x02030405);
676  const CService peer_us{peer_us_addr, 20002};
677 
678  // Create a peer with a routable IPv4 address (outbound).
679  in_addr peer_out_in_addr;
680  peer_out_in_addr.s_addr = htonl(0x01020304);
681  CNode peer_out{/*id=*/0,
682  /*sock=*/nullptr,
683  /*addrIn=*/CAddress{CService{peer_out_in_addr, 8333}, NODE_NETWORK},
684  /*nKeyedNetGroupIn=*/0,
685  /*nLocalHostNonceIn=*/0,
686  /*addrBindIn=*/CAddress{},
687  /*addrNameIn=*/std::string{},
688  /*conn_type_in=*/ConnectionType::OUTBOUND_FULL_RELAY,
689  /*inbound_onion=*/false};
690  peer_out.fSuccessfullyConnected = true;
691  peer_out.SetAddrLocal(peer_us);
692 
693  // Without the fix peer_us:8333 is chosen instead of the proper peer_us:bind_port.
694  auto chosen_local_addr = GetLocalAddrForPeer(peer_out);
695  BOOST_REQUIRE(chosen_local_addr);
696  const CService expected{peer_us_addr, bind_port};
697  BOOST_CHECK(*chosen_local_addr == expected);
698 
699  // Create a peer with a routable IPv4 address (inbound).
700  in_addr peer_in_in_addr;
701  peer_in_in_addr.s_addr = htonl(0x05060708);
702  CNode peer_in{/*id=*/0,
703  /*sock=*/nullptr,
704  /*addrIn=*/CAddress{CService{peer_in_in_addr, 8333}, NODE_NETWORK},
705  /*nKeyedNetGroupIn=*/0,
706  /*nLocalHostNonceIn=*/0,
707  /*addrBindIn=*/CAddress{},
708  /*addrNameIn=*/std::string{},
709  /*conn_type_in=*/ConnectionType::INBOUND,
710  /*inbound_onion=*/false};
711  peer_in.fSuccessfullyConnected = true;
712  peer_in.SetAddrLocal(peer_us);
713 
714  // Without the fix peer_us:8333 is chosen instead of the proper peer_us:peer_us.GetPort().
715  chosen_local_addr = GetLocalAddrForPeer(peer_in);
716  BOOST_REQUIRE(chosen_local_addr);
717  BOOST_CHECK(*chosen_local_addr == peer_us);
718 
719  m_node.args->ForceSetArg("-bind", "");
720 }
721 
722 BOOST_AUTO_TEST_CASE(LimitedAndReachable_Network)
723 {
729 
730  SetReachable(NET_IPV4, false);
731  SetReachable(NET_IPV6, false);
732  SetReachable(NET_ONION, false);
733  SetReachable(NET_I2P, false);
734  SetReachable(NET_CJDNS, false);
735 
741 
742  SetReachable(NET_IPV4, true);
743  SetReachable(NET_IPV6, true);
744  SetReachable(NET_ONION, true);
745  SetReachable(NET_I2P, true);
746  SetReachable(NET_CJDNS, true);
747 
753 }
754 
755 BOOST_AUTO_TEST_CASE(LimitedAndReachable_NetworkCaseUnroutableAndInternal)
756 {
759 
761  SetReachable(NET_INTERNAL, false);
762 
763  BOOST_CHECK(IsReachable(NET_UNROUTABLE)); // Ignored for both networks
765 }
766 
767 CNetAddr UtilBuildAddress(unsigned char p1, unsigned char p2, unsigned char p3, unsigned char p4)
768 {
769  unsigned char ip[] = {p1, p2, p3, p4};
770 
771  struct sockaddr_in sa;
772  memset(&sa, 0, sizeof(sockaddr_in)); // initialize the memory block
773  memcpy(&(sa.sin_addr), &ip, sizeof(ip));
774  return CNetAddr(sa.sin_addr);
775 }
776 
777 
778 BOOST_AUTO_TEST_CASE(LimitedAndReachable_CNetAddr)
779 {
780  CNetAddr addr = UtilBuildAddress(0x001, 0x001, 0x001, 0x001); // 1.1.1.1
781 
782  SetReachable(NET_IPV4, true);
783  BOOST_CHECK(IsReachable(addr));
784 
785  SetReachable(NET_IPV4, false);
786  BOOST_CHECK(!IsReachable(addr));
787 
788  SetReachable(NET_IPV4, true); // have to reset this, because this is stateful.
789 }
790 
791 
792 BOOST_AUTO_TEST_CASE(LocalAddress_BasicLifecycle)
793 {
794  CService addr = CService(UtilBuildAddress(0x002, 0x001, 0x001, 0x001), 1000); // 2.1.1.1:1000
795 
796  SetReachable(NET_IPV4, true);
797 
798  BOOST_CHECK(!IsLocal(addr));
799  BOOST_CHECK(AddLocal(addr, 1000));
800  BOOST_CHECK(IsLocal(addr));
801 
802  RemoveLocal(addr);
803  BOOST_CHECK(!IsLocal(addr));
804 }
805 
806 BOOST_AUTO_TEST_CASE(initial_advertise_from_version_message)
807 {
809 
810  // Tests the following scenario:
811  // * -bind=3.4.5.6:20001 is specified
812  // * we make an outbound connection to a peer
813  // * the peer reports he sees us as 2.3.4.5:20002 in the version message
814  // (20002 is a random port assigned by our OS for the outgoing TCP connection,
815  // we cannot accept connections to it)
816  // * we should self-advertise to that peer as 2.3.4.5:20001
817 
818  // Pretend that we bound to this port.
819  const uint16_t bind_port = 20001;
820  m_node.args->ForceSetArg("-bind", strprintf("3.4.5.6:%u", bind_port));
821  m_node.args->ForceSetArg("-capturemessages", "1");
822 
823  // Our address:port as seen from the peer - 2.3.4.5:20002 (different from the above).
824  in_addr peer_us_addr;
825  peer_us_addr.s_addr = htonl(0x02030405);
826  const CService peer_us{peer_us_addr, 20002};
827 
828  // Create a peer with a routable IPv4 address.
829  in_addr peer_in_addr;
830  peer_in_addr.s_addr = htonl(0x01020304);
831  CNode peer{/*id=*/0,
832  /*sock=*/nullptr,
833  /*addrIn=*/CAddress{CService{peer_in_addr, 8333}, NODE_NETWORK},
834  /*nKeyedNetGroupIn=*/0,
835  /*nLocalHostNonceIn=*/0,
836  /*addrBindIn=*/CAddress{},
837  /*addrNameIn=*/std::string{},
838  /*conn_type_in=*/ConnectionType::OUTBOUND_FULL_RELAY,
839  /*inbound_onion=*/false};
840 
841  const uint64_t services{NODE_NETWORK | NODE_WITNESS};
842  const int64_t time{0};
843  const CNetMsgMaker msg_maker{PROTOCOL_VERSION};
844 
845  // Force Chainstate::IsInitialBlockDownload() to return false.
846  // Otherwise PushAddress() isn't called by PeerManager::ProcessMessage().
847  TestChainState& chainstate =
848  *static_cast<TestChainState*>(&m_node.chainman->ActiveChainstate());
849  chainstate.JumpOutOfIbd();
850 
851  m_node.peerman->InitializeNode(peer, NODE_NETWORK);
852 
853  std::atomic<bool> interrupt_dummy{false};
854  std::chrono::microseconds time_received_dummy{0};
855 
856  const auto msg_version =
857  msg_maker.Make(NetMsgType::VERSION, PROTOCOL_VERSION, services, time, services, peer_us);
858  CDataStream msg_version_stream{msg_version.data, SER_NETWORK, PROTOCOL_VERSION};
859 
860  m_node.peerman->ProcessMessage(
861  peer, NetMsgType::VERSION, msg_version_stream, time_received_dummy, interrupt_dummy);
862 
863  const auto msg_verack = msg_maker.Make(NetMsgType::VERACK);
864  CDataStream msg_verack_stream{msg_verack.data, SER_NETWORK, PROTOCOL_VERSION};
865 
866  // Will set peer.fSuccessfullyConnected to true (necessary in SendMessages()).
867  m_node.peerman->ProcessMessage(
868  peer, NetMsgType::VERACK, msg_verack_stream, time_received_dummy, interrupt_dummy);
869 
870  // Ensure that peer_us_addr:bind_port is sent to the peer.
871  const CService expected{peer_us_addr, bind_port};
872  bool sent{false};
873 
874  const auto CaptureMessageOrig = CaptureMessage;
875  CaptureMessage = [&sent, &expected](const CAddress& addr,
876  const std::string& msg_type,
878  bool is_incoming) -> void {
879  if (!is_incoming && msg_type == "addr") {
881  std::vector<CAddress> addresses;
882 
883  s >> addresses;
884 
885  for (const auto& addr : addresses) {
886  if (addr == expected) {
887  sent = true;
888  return;
889  }
890  }
891  }
892  };
893 
894  m_node.peerman->SendMessages(&peer);
895 
896  BOOST_CHECK(sent);
897 
898  CaptureMessage = CaptureMessageOrig;
899  chainstate.ResetIbd();
900  m_node.args->ForceSetArg("-capturemessages", "0");
901  m_node.args->ForceSetArg("-bind", "");
902  // PeerManager::ProcessMessage() calls AddTimeData() which changes the internal state
903  // in timedata.cpp and later confuses the test "timedata_tests/addtimedata". Thus reset
904  // that state as it was before our test was run.
906 }
907 
node::NodeContext m_node
Definition: bitcoin-gui.cpp:37
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:94
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: system.cpp:654
bool SoftSetArg(const std::string &strArg, const std::string &strValue)
Set an argument if it doesn't already have a value.
Definition: system.cpp:638
A CService with information about it as peer.
Definition: protocol.h:361
void SetVersion(int n)
Definition: streams.h:362
int GetVersion() const
Definition: streams.h:363
Network address.
Definition: netaddress.h:120
std::string ToStringAddr() const
Definition: netaddress.cpp:602
bool IsBindAny() const
Definition: netaddress.cpp:304
bool SetSpecial(const std::string &addr)
Parse a Tor or I2P address and set this object to it.
Definition: netaddress.cpp:208
bool IsCJDNS() const
Check whether this object represents a CJDNS address.
Definition: netaddress.cpp:417
bool IsTor() const
Check whether this object represents a TOR address.
Definition: netaddress.cpp:407
bool IsValid() const
Definition: netaddress.cpp:445
bool IsIPv4() const
Definition: netaddress.cpp:312
bool IsIPv6() const
Definition: netaddress.cpp:314
bool IsInternal() const
Definition: netaddress.cpp:494
bool SetInternal(const std::string &name)
Create an "internal" address that represents a name or FQDN.
Definition: netaddress.cpp:169
bool IsAddrV1Compatible() const
Check if the current object can be serialized in pre-ADDRv2/BIP155 format.
Definition: netaddress.cpp:499
bool IsI2P() const
Check whether this object represents an I2P address.
Definition: netaddress.cpp:412
Information about a peer.
Definition: net.h:349
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:520
bool empty() const
Definition: streams.h:221
value_type * data()
Definition: streams.h:227
void clear()
Definition: streams.h:226
BOOST_CHECK_EXCEPTION predicates to check the specific validation error.
Definition: setup_common.h:220
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition: net.h:653
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:97
@ 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_AUTO_TEST_SUITE_END()
static CService ip(uint32_t i)
const char * VERSION
The version message provides information about the transmitting node to the receiving node at the beg...
Definition: protocol.cpp:13
const char * VERACK
The verack message acknowledges a previously-received version message, informing the connecting node ...
Definition: protocol.cpp:14
uint16_t GetListenPort()
Definition: net.cpp:129
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:357
void RemoveLocal(const CService &addr)
Definition: net.cpp:319
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
Definition: net.cpp:234
bool AddLocal(const CService &addr_, int nScore)
Definition: net.cpp:286
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:326
GlobalMutex g_maplocalhost_mutex
Definition: net.cpp:118
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:2936
bool IsReachable(enum Network net)
Definition: net.cpp:334
int64_t NodeId
Definition: net.h:94
BOOST_AUTO_TEST_CASE(cnode_listen_port)
Definition: net_tests.cpp:38
CNetAddr UtilBuildAddress(unsigned char p1, unsigned char p2, unsigned char p3, unsigned char p4)
Definition: net_tests.cpp:767
static constexpr int ADDRV2_FORMAT
A flag that is ORed into the protocol version to designate that addresses should be serialized in (un...
Definition: netaddress.h:33
@ NET_I2P
I2P.
Definition: netaddress.h:58
@ NET_CJDNS
CJDNS.
Definition: netaddress.h:61
@ NET_ONION
TOR (v2 or v3)
Definition: netaddress.h:55
@ NET_IPV6
IPv6.
Definition: netaddress.h:52
@ NET_IPV4
IPv4.
Definition: netaddress.h:49
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
Definition: netaddress.h:46
@ NET_INTERNAL
A set of addresses that represent the hash of a string or FQDN.
Definition: netaddress.h:65
bool LookupHost(const std::string &name, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
Resolve a host string to its corresponding network addresses.
Definition: netbase.cpp:170
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18
#define BOOST_CHECK(expr)
Definition: object.cpp:17
@ NODE_WITNESS
Definition: protocol.h:286
@ NODE_NETWORK
Definition: protocol.h:279
@ SER_NETWORK
Definition: serialize.h:131
std::vector< Byte > ParseHex(std::string_view hex_str)
Like TryParseHex, but returns an empty vector on invalid input.
Definition: strencodings.h:65
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:109
uint16_t nPort
Definition: net.h:180
int nScore
Definition: net.h:179
Identical to TestingSetup, but chain set to regtest.
Definition: setup_common.h:116
void ResetIbd()
Reset the ibd cache to its initial state.
Definition: validation.cpp:12
void JumpOutOfIbd()
Toggle IsInitialBlockDownload from true to false.
Definition: validation.cpp:18
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:54
std::unique_ptr< PeerManager > peerman
Definition: context.h:53
ArgsManager * args
Definition: context.h:56
#define LOCK(cs)
Definition: sync.h:258
void TestOnlyResetTimeData()
Reset the internal state of GetTimeOffset(), GetAdjustedTime() and AddTimeData().
Definition: timedata.cpp:113
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1162
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
std::string ToLower(std::string_view str)
Returns the lowercase equivalent of the given string.
ArgsManager gArgs
Definition: system.cpp:73
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12