LCOV - code coverage report
Current view: top level - src/test/fuzz/util - net.h (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 92.6 % 94 87
Test Date: 2026-11-21 05:38:30 Functions: 76.5 % 17 13
Branches: 58.1 % 124 72

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2009-present The Bitcoin Core developers
       2                 :             : // Distributed under the MIT software license, see the accompanying
       3                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       4                 :             : 
       5                 :             : #ifndef BITCOIN_TEST_FUZZ_UTIL_NET_H
       6                 :             : #define BITCOIN_TEST_FUZZ_UTIL_NET_H
       7                 :             : 
       8                 :             : #include <addrman.h>
       9                 :             : #include <addrman_impl.h>
      10                 :             : #include <net.h>
      11                 :             : #include <net_permissions.h>
      12                 :             : #include <netaddress.h>
      13                 :             : #include <netgroup.h>
      14                 :             : #include <node/connection_types.h>
      15                 :             : #include <node/eviction.h>
      16                 :             : #include <protocol.h>
      17                 :             : #include <sync.h>
      18                 :             : #include <test/fuzz/FuzzedDataProvider.h>
      19                 :             : #include <test/fuzz/util.h>
      20                 :             : #include <test/util/net.h>
      21                 :             : #include <test/util/time.h>
      22                 :             : #include <util/asmap.h>
      23                 :             : #include <util/sock.h>
      24                 :             : 
      25                 :             : #include <chrono>
      26                 :             : #include <cstddef>
      27                 :             : #include <cstdint>
      28                 :             : #include <limits>
      29                 :             : #include <memory>
      30                 :             : #include <optional>
      31                 :             : #include <string>
      32                 :             : 
      33                 :             : /**
      34                 :             :  * Create a CNetAddr. It may have `addr.IsValid() == false`.
      35                 :             :  * @param[in,out] fuzzed_data_provider Take data for the address from this, if `rand` is `nullptr`.
      36                 :             :  * @param[in,out] rand If not nullptr, take data from it instead of from `fuzzed_data_provider`.
      37                 :             :  * Prefer generating addresses using `fuzzed_data_provider` because it is not uniform. Only use
      38                 :             :  * `rand` if `fuzzed_data_provider` is exhausted or its data is needed for other things.
      39                 :             :  * @return a "random" network address.
      40                 :             :  */
      41                 :             : CNetAddr ConsumeNetAddr(FuzzedDataProvider& fuzzed_data_provider, FastRandomContext* rand = nullptr) noexcept;
      42                 :             : 
      43                 :        9620 : class AddrManDeterministic : public AddrMan
      44                 :             : {
      45                 :             : public:
      46                 :       10892 :     explicit AddrManDeterministic(const NetGroupManager& netgroupman, FuzzedDataProvider& fuzzed_data_provider, int32_t check_ratio)
      47                 :       10892 :         : AddrMan(netgroupman, /*deterministic=*/true, check_ratio)
      48                 :             :     {
      49   [ +  -  +  - ]:       21784 :         WITH_LOCK(m_impl->cs, m_impl->insecure_rand.Reseed(ConsumeUInt256(fuzzed_data_provider)));
      50                 :       10892 :     }
      51                 :             : 
      52                 :             :     /**
      53                 :             :      * Compare with another AddrMan.
      54                 :             :      * This compares:
      55                 :             :      * - the values in `mapInfo` (the keys aka ids are ignored)
      56                 :             :      * - vvNew entries refer to the same addresses
      57                 :             :      * - vvTried entries refer to the same addresses
      58                 :             :      */
      59                 :        1272 :     bool operator==(const AddrManDeterministic& other) const
      60                 :             :     {
      61         [ +  - ]:        1272 :         LOCK2(m_impl->cs, other.m_impl->cs);
      62                 :             : 
      63   [ +  -  +  -  :        2544 :         if (m_impl->mapInfo.size() != other.m_impl->mapInfo.size() || m_impl->nNew != other.m_impl->nNew ||
                   -  + ]
      64         [ -  + ]:        1272 :             m_impl->nTried != other.m_impl->nTried) {
      65                 :           0 :             return false;
      66                 :             :         }
      67                 :             : 
      68                 :             :         // Check that all values in `mapInfo` are equal to all values in `other.mapInfo`.
      69                 :             :         // Keys may be different.
      70                 :             : 
      71                 :    13540762 :         auto addrinfo_hasher = [](const AddrInfo& a) {
      72                 :    13539490 :             CSipHasher hasher(0, 0);
      73                 :    13539490 :             auto addr_key = a.GetKey();
      74         [ +  - ]:    13539490 :             auto source_key = a.source.GetAddrBytes();
      75         [ +  - ]:    13539490 :             hasher.Write(TicksSinceEpoch<std::chrono::seconds>(a.m_last_success));
      76         [ +  - ]:    13539490 :             hasher.Write(a.nAttempts);
      77         [ +  - ]:    13539490 :             hasher.Write(a.nRefCount);
      78         [ +  - ]:    13539490 :             hasher.Write(a.fInTried);
      79   [ +  -  +  - ]:    13539490 :             hasher.Write(a.GetNetwork());
      80   [ +  -  +  - ]:    13539490 :             hasher.Write(a.source.GetNetwork());
      81   [ -  +  +  - ]:    13539490 :             hasher.Write(addr_key.size());
      82   [ -  +  +  - ]:    13539490 :             hasher.Write(source_key.size());
      83   [ -  +  +  - ]:    13539490 :             hasher.Write(addr_key);
      84   [ -  +  +  - ]:    13539490 :             hasher.Write(source_key);
      85         [ +  - ]:    13539490 :             return (size_t)hasher.Finalize();
      86                 :    13539490 :         };
      87                 :             : 
      88                 :        1272 :         auto addrinfo_eq = [](const AddrInfo& lhs, const AddrInfo& rhs) {
      89                 :           0 :             return std::tie(static_cast<const CService&>(lhs), lhs.source, lhs.m_last_success, lhs.nAttempts, lhs.nRefCount, lhs.fInTried) ==
      90                 :           0 :                    std::tie(static_cast<const CService&>(rhs), rhs.source, rhs.m_last_success, rhs.nAttempts, rhs.nRefCount, rhs.fInTried);
      91                 :             :         };
      92                 :             : 
      93                 :        1272 :         using Addresses = std::unordered_set<AddrInfo, decltype(addrinfo_hasher), decltype(addrinfo_eq)>;
      94                 :             : 
      95         [ +  - ]:        1272 :         const size_t num_addresses{m_impl->mapInfo.size()};
      96                 :             : 
      97         [ +  - ]:        2544 :         Addresses addresses{num_addresses, addrinfo_hasher, addrinfo_eq};
      98   [ +  +  +  - ]:     6771017 :         for (const auto& [id, addr] : m_impl->mapInfo) {
      99         [ +  - ]:     6769745 :             addresses.insert(addr);
     100                 :             :         }
     101                 :             : 
     102         [ +  - ]:        2544 :         Addresses other_addresses{num_addresses, addrinfo_hasher, addrinfo_eq};
     103   [ +  +  +  - ]:     6771017 :         for (const auto& [id, addr] : other.m_impl->mapInfo) {
     104         [ +  - ]:     6769745 :             other_addresses.insert(addr);
     105                 :             :         }
     106                 :             : 
     107   [ +  -  +  - ]:        1272 :         if (addresses != other_addresses) {
     108                 :             :             return false;
     109                 :             :         }
     110                 :             : 
     111                 :   104203512 :         auto IdsReferToSameAddress = [&](nid_type id, nid_type other_id) EXCLUSIVE_LOCKS_REQUIRED(m_impl->cs, other.m_impl->cs) {
     112   [ +  +  -  + ]:   104202240 :             if (id == -1 && other_id == -1) {
     113                 :             :                 return true;
     114                 :             :             }
     115   [ -  +  -  -  :     6913098 :             if ((id == -1 && other_id != -1) || (id != -1 && other_id == -1)) {
             +  -  +  - ]
     116                 :             :                 return false;
     117                 :             :             }
     118                 :     6913098 :             return m_impl->mapInfo.at(id) == other.m_impl->mapInfo.at(other_id);
     119                 :        1272 :         };
     120                 :             : 
     121                 :             :         // Check that `vvNew` contains the same addresses as `other.vvNew`. Notice - `vvNew[i][j]`
     122                 :             :         // contains just an id and the address is to be found in `mapInfo.at(id)`. The ids
     123                 :             :         // themselves may differ between `vvNew` and `other.vvNew`.
     124         [ +  + ]:     1303800 :         for (size_t i = 0; i < ADDRMAN_NEW_BUCKET_COUNT; ++i) {
     125         [ +  + ]:    84664320 :             for (size_t j = 0; j < ADDRMAN_BUCKET_SIZE; ++j) {
     126   [ +  -  +  - ]:    83361792 :                 if (!IdsReferToSameAddress(m_impl->vvNew[i][j], other.m_impl->vvNew[i][j])) {
     127                 :             :                     return false;
     128                 :             :                 }
     129                 :             :             }
     130                 :             :         }
     131                 :             : 
     132                 :             :         // Same for `vvTried`.
     133         [ +  + ]:      326904 :         for (size_t i = 0; i < ADDRMAN_TRIED_BUCKET_COUNT; ++i) {
     134         [ +  + ]:    21166080 :             for (size_t j = 0; j < ADDRMAN_BUCKET_SIZE; ++j) {
     135   [ +  -  +  - ]:    20840448 :                 if (!IdsReferToSameAddress(m_impl->vvTried[i][j], other.m_impl->vvTried[i][j])) {
     136                 :             :                     return false;
     137                 :             :                 }
     138                 :             :             }
     139                 :             :         }
     140                 :             : 
     141                 :             :         return true;
     142         [ +  - ]:        3816 :     }
     143                 :             : };
     144                 :             : 
     145                 :             : class FuzzedNetEvents : public NetEventsInterface
     146                 :             : {
     147                 :             : public:
     148                 :        4441 :     FuzzedNetEvents(FuzzedDataProvider& fdp) : m_fdp(fdp) {}
     149                 :             : 
     150                 :       57465 :     virtual void InitializeNode(const CNode&, ServiceFlags) override {}
     151                 :             : 
     152                 :           0 :     virtual void FinalizeNode(const CNode&) override {}
     153                 :             : 
     154                 :           0 :     virtual bool HasAllDesirableServiceFlags(ServiceFlags) const override { return m_fdp.ConsumeBool(); }
     155                 :             : 
     156                 :           0 :     virtual bool ProcessMessages(CNode&, std::atomic<bool>&) override { return m_fdp.ConsumeBool(); }
     157                 :             : 
     158                 :           0 :     virtual bool SendMessages(CNode&) override { return m_fdp.ConsumeBool(); }
     159                 :             : 
     160                 :             : private:
     161                 :             :     FuzzedDataProvider& m_fdp;
     162                 :             : };
     163                 :             : 
     164                 :             : class FuzzedSock : public Sock
     165                 :             : {
     166                 :             :     FuzzedDataProvider& m_fuzzed_data_provider;
     167                 :             : 
     168                 :             :     /**
     169                 :             :      * Data to return when `MSG_PEEK` is used as a `Recv()` flag.
     170                 :             :      * If `MSG_PEEK` is used, then our `Recv()` returns some random data as usual, but on the next
     171                 :             :      * `Recv()` call we must return the same data, thus we remember it here.
     172                 :             :      */
     173                 :             :     mutable std::vector<uint8_t> m_peek_data;
     174                 :             : 
     175                 :             :     /**
     176                 :             :      * Whether to pretend that the socket is select(2)-able. This is randomly set in the
     177                 :             :      * constructor. It should remain constant so that repeated calls to `IsSelectable()`
     178                 :             :      * return the same value.
     179                 :             :      */
     180                 :             :     const bool m_selectable;
     181                 :             : 
     182                 :             :     /**
     183                 :             :      * Externally-provided context used to mock the steady clock in methods
     184                 :             :      * waiting for a given duration. It is a reference (rather than an owned
     185                 :             :      * member) so that several FuzzedSock instances sharing a test case (e.g.
     186                 :             :      * one per peer, or one created from Accept()) advance a single mocked
     187                 :             :      * clock.
     188                 :             :      */
     189                 :             :     FakeSteadyClock& m_clock;
     190                 :             : 
     191                 :             : public:
     192                 :             :     explicit FuzzedSock(FuzzedDataProvider& fuzzed_data_provider, FakeSteadyClock& clock);
     193                 :             : 
     194                 :             :     ~FuzzedSock() override;
     195                 :             : 
     196                 :             :     FuzzedSock& operator=(Sock&& other) override;
     197                 :             : 
     198                 :             :     ssize_t Send(const void* data, size_t len, int flags) const override;
     199                 :             : 
     200                 :             :     ssize_t Recv(void* buf, size_t len, int flags) const override;
     201                 :             : 
     202                 :             :     int Connect(const sockaddr*, socklen_t) const override;
     203                 :             : 
     204                 :             :     int Bind(const sockaddr*, socklen_t) const override;
     205                 :             : 
     206                 :             :     int Listen(int backlog) const override;
     207                 :             : 
     208                 :             :     std::unique_ptr<Sock> Accept(sockaddr* addr, socklen_t* addr_len) const override;
     209                 :             : 
     210                 :             :     int GetSockOpt(int level, int opt_name, void* opt_val, socklen_t* opt_len) const override;
     211                 :             : 
     212                 :             :     int SetSockOpt(int level, int opt_name, const void* opt_val, socklen_t opt_len) const override;
     213                 :             : 
     214                 :             :     int GetSockName(sockaddr* name, socklen_t* name_len) const override;
     215                 :             : 
     216                 :             :     bool SetNonBlocking() const override;
     217                 :             : 
     218                 :             :     bool IsSelectable() const override;
     219                 :             : 
     220                 :             :     bool Wait(std::chrono::milliseconds timeout, Event requested, Event* occurred = nullptr) const override;
     221                 :             : 
     222                 :             :     bool WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per_sock) const override;
     223                 :             : 
     224                 :             :     bool IsConnected(std::string& errmsg) const override;
     225                 :             : };
     226                 :             : 
     227                 :        4441 : [[nodiscard]] inline FuzzedNetEvents ConsumeNetEvents(FuzzedDataProvider& fdp) noexcept
     228                 :             : {
     229         [ +  - ]:        4441 :     return FuzzedNetEvents{fdp};
     230                 :             : }
     231                 :             : 
     232                 :         159 : [[nodiscard]] inline FuzzedSock ConsumeSock(FuzzedDataProvider& fuzzed_data_provider, FakeSteadyClock& clock)
     233                 :             : {
     234         [ +  - ]:         159 :     return FuzzedSock{fuzzed_data_provider, clock};
     235                 :             : }
     236                 :             : 
     237                 :        8693 : [[nodiscard]] inline NetGroupManager ConsumeNetGroupManager(FuzzedDataProvider& fuzzed_data_provider) noexcept
     238                 :             : {
     239                 :        8693 :     std::vector<std::byte> asmap{ConsumeRandomLengthByteVector<std::byte>(fuzzed_data_provider)};
     240   [ -  +  +  + ]:        8693 :     if (!CheckStandardAsmap(asmap)) {
     241                 :        6797 :         return NetGroupManager::NoAsmap();
     242                 :             :     }
     243                 :        1896 :     return NetGroupManager::WithLoadedAsmap(std::move(asmap));
     244                 :        8693 : }
     245                 :             : 
     246                 :       26479 : inline CSubNet ConsumeSubNet(FuzzedDataProvider& fuzzed_data_provider) noexcept
     247                 :             : {
     248                 :       26479 :     return {ConsumeNetAddr(fuzzed_data_provider), fuzzed_data_provider.ConsumeIntegral<uint8_t>()};
     249                 :             : }
     250                 :             : 
     251                 :     3657588 : inline CService ConsumeService(FuzzedDataProvider& fuzzed_data_provider) noexcept
     252                 :             : {
     253                 :     3657588 :     return {ConsumeNetAddr(fuzzed_data_provider), fuzzed_data_provider.ConsumeIntegral<uint16_t>()};
     254                 :             : }
     255                 :             : 
     256                 :       52300 : inline std::vector<CService> ConsumeServiceVector(FuzzedDataProvider& fuzzed_data_provider,
     257                 :             :                                                   size_t max_vector_size = 5) noexcept
     258                 :             : {
     259                 :       52300 :     std::vector<CService> ret;
     260                 :       52300 :     const size_t size = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, max_vector_size);
     261                 :       52300 :     ret.reserve(size);
     262         [ +  + ]:      109682 :     for (size_t i = 0; i < size; ++i) {
     263                 :       57382 :         ret.emplace_back(ConsumeService(fuzzed_data_provider));
     264                 :             :     }
     265                 :       52300 :     return ret;
     266                 :             : }
     267                 :             : 
     268                 :             : CAddress ConsumeAddress(FuzzedDataProvider& fuzzed_data_provider) noexcept;
     269                 :             : 
     270                 :             : template <bool ReturnUniquePtr = false>
     271                 :      100630 : auto ConsumeNode(FuzzedDataProvider& fuzzed_data_provider, FakeSteadyClock& clock, const std::optional<NodeId>& node_id_in = std::nullopt) noexcept
     272                 :             : {
     273         [ +  + ]:      124442 :     const NodeId node_id = node_id_in.value_or(fuzzed_data_provider.ConsumeIntegralInRange<NodeId>(0, std::numeric_limits<NodeId>::max()));
     274                 :      100630 :     const auto sock = std::make_shared<FuzzedSock>(fuzzed_data_provider, clock);
     275                 :      100630 :     const CAddress address = ConsumeAddress(fuzzed_data_provider);
     276                 :      100630 :     const uint64_t keyed_net_group = fuzzed_data_provider.ConsumeIntegral<uint64_t>();
     277                 :      100630 :     const uint64_t local_host_nonce = fuzzed_data_provider.ConsumeIntegral<uint64_t>();
     278                 :      100630 :     const CAddress addr_bind = ConsumeAddress(fuzzed_data_provider);
     279                 :      100630 :     const std::string addr_name = fuzzed_data_provider.ConsumeRandomLengthString(64);
     280                 :      100630 :     const ConnectionType conn_type = fuzzed_data_provider.PickValueInArray(ALL_CONNECTION_TYPES);
     281   [ +  +  +  + ]:      139647 :     const bool inbound_onion{conn_type == ConnectionType::INBOUND ? fuzzed_data_provider.ConsumeBool() : false};
     282                 :      100630 :     const uint64_t network_id = fuzzed_data_provider.ConsumeIntegral<uint64_t>();
     283                 :             : 
     284                 :      100630 :     NetPermissionFlags permission_flags = ConsumeWeakEnum(fuzzed_data_provider, ALL_NET_PERMISSION_FLAGS);
     285                 :             :     if constexpr (ReturnUniquePtr) {
     286                 :             :         return std::make_unique<CNode>(node_id,
     287                 :             :                                        sock,
     288                 :             :                                        address,
     289                 :             :                                        keyed_net_group,
     290                 :             :                                        local_host_nonce,
     291                 :             :                                        addr_bind,
     292                 :             :                                        addr_name,
     293                 :             :                                        conn_type,
     294                 :             :                                        inbound_onion,
     295                 :             :                                        network_id,
     296                 :       93492 :                                        CNodeOptions{ .permission_flags = permission_flags });
     297                 :             :     } else {
     298                 :             :         return CNode{node_id,
     299                 :        7138 :                      sock,
     300                 :             :                      address,
     301                 :             :                      keyed_net_group,
     302                 :             :                      local_host_nonce,
     303                 :             :                      addr_bind,
     304                 :             :                      addr_name,
     305                 :             :                      conn_type,
     306                 :             :                      inbound_onion,
     307                 :             :                      network_id,
     308         [ +  - ]:       14276 :                      CNodeOptions{ .permission_flags = permission_flags }};
     309                 :             :     }
     310 [ +  - ][ #  # ]:      201260 : }
     311                 :       93492 : inline std::unique_ptr<CNode> ConsumeNodeAsUniquePtr(FuzzedDataProvider& fdp, FakeSteadyClock& clock, const std::optional<NodeId>& node_id_in = std::nullopt) { return ConsumeNode<true>(fdp, clock, node_id_in); }
     312                 :             : 
     313                 :             : void FillNode(FuzzedDataProvider& fuzzed_data_provider, ConnmanTestMsg& connman, CNode& node) noexcept EXCLUSIVE_LOCKS_REQUIRED(NetEventsInterface::g_msgproc_mutex);
     314                 :             : 
     315                 :             : #endif // BITCOIN_TEST_FUZZ_UTIL_NET_H
        

Generated by: LCOV version 2.5.0-full