LCOV - code coverage report
Current view: top level - src/test - net_tests.cpp (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 0 964 0.0 %
Date: 2023-10-05 12:38:51 Functions: 0 116 0.0 %
Branches: 0 0 -

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

Generated by: LCOV version 1.14