LCOV - code coverage report
Current view: top level - src/test/util - net.h (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 61.1 % 36 22
Test Date: 2025-10-04 04:34:28 Functions: 57.1 % 7 4
Branches: 50.0 % 26 13

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2020-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_UTIL_NET_H
       6                 :             : #define BITCOIN_TEST_UTIL_NET_H
       7                 :             : 
       8                 :             : #include <compat/compat.h>
       9                 :             : #include <netmessagemaker.h>
      10                 :             : #include <net.h>
      11                 :             : #include <net_permissions.h>
      12                 :             : #include <net_processing.h>
      13                 :             : #include <netaddress.h>
      14                 :             : #include <node/connection_types.h>
      15                 :             : #include <node/eviction.h>
      16                 :             : #include <span.h>
      17                 :             : #include <sync.h>
      18                 :             : #include <util/sock.h>
      19                 :             : 
      20                 :             : #include <algorithm>
      21                 :             : #include <array>
      22                 :             : #include <cassert>
      23                 :             : #include <chrono>
      24                 :             : #include <condition_variable>
      25                 :             : #include <cstdint>
      26                 :             : #include <cstring>
      27                 :             : #include <memory>
      28                 :             : #include <optional>
      29                 :             : #include <string>
      30                 :             : #include <unordered_map>
      31                 :             : #include <vector>
      32                 :             : 
      33                 :             : class FastRandomContext;
      34                 :             : 
      35                 :           4 : struct ConnmanTestMsg : public CConnman {
      36         [ +  - ]:         177 :     using CConnman::CConnman;
      37                 :             : 
      38                 :             :     void SetMsgProc(NetEventsInterface* msgproc)
      39                 :             :     {
      40                 :             :         m_msgproc = msgproc;
      41                 :             :     }
      42                 :             : 
      43                 :           1 :     void SetPeerConnectTimeout(std::chrono::seconds timeout)
      44                 :             :     {
      45         [ +  - ]:           1 :         m_peer_connect_timeout = timeout;
      46                 :             :     }
      47                 :             : 
      48                 :             :     void ResetAddrCache();
      49                 :             :     void ResetMaxOutboundCycle();
      50                 :             : 
      51                 :           4 :     std::vector<CNode*> TestNodes()
      52                 :             :     {
      53                 :           4 :         LOCK(m_nodes_mutex);
      54         [ +  - ]:           4 :         return m_nodes;
      55                 :           4 :     }
      56                 :             : 
      57                 :          23 :     void AddTestNode(CNode& node)
      58                 :             :     {
      59                 :          23 :         LOCK(m_nodes_mutex);
      60         [ +  - ]:          23 :         m_nodes.push_back(&node);
      61                 :             : 
      62   [ +  +  +  - ]:          23 :         if (node.IsManualOrFullOutboundConn()) ++m_network_conn_counts[node.addr.GetNetwork()];
      63                 :          23 :     }
      64                 :             : 
      65                 :           4 :     void ClearTestNodes()
      66                 :             :     {
      67                 :           4 :         LOCK(m_nodes_mutex);
      68         [ +  + ]:          27 :         for (CNode* node : m_nodes) {
      69         [ +  - ]:          23 :             delete node;
      70                 :             :         }
      71   [ +  -  +  - ]:           8 :         m_nodes.clear();
      72                 :           4 :     }
      73                 :             : 
      74                 :             :     void CreateNodeFromAcceptedSocketPublic(std::unique_ptr<Sock> sock,
      75                 :             :                                             NetPermissionFlags permissions,
      76                 :             :                                             const CAddress& addr_bind,
      77                 :             :                                             const CAddress& addr_peer)
      78                 :             :     {
      79                 :             :         CreateNodeFromAcceptedSocket(std::move(sock), permissions, addr_bind, addr_peer);
      80                 :             :     }
      81                 :             : 
      82                 :             :     bool InitBindsPublic(const CConnman::Options& options)
      83                 :             :     {
      84                 :             :         return InitBinds(options);
      85                 :             :     }
      86                 :             : 
      87                 :             :     void SocketHandlerPublic()
      88                 :             :     {
      89                 :             :         SocketHandler();
      90                 :             :     }
      91                 :             : 
      92                 :             :     void Handshake(CNode& node,
      93                 :             :                    bool successfully_connected,
      94                 :             :                    ServiceFlags remote_services,
      95                 :             :                    ServiceFlags local_services,
      96                 :             :                    int32_t version,
      97                 :             :                    bool relay_txs)
      98                 :             :         EXCLUSIVE_LOCKS_REQUIRED(NetEventsInterface::g_msgproc_mutex);
      99                 :             : 
     100                 :           2 :     bool ProcessMessagesOnce(CNode& node) EXCLUSIVE_LOCKS_REQUIRED(NetEventsInterface::g_msgproc_mutex)
     101                 :             :     {
     102                 :           2 :         return m_msgproc->ProcessMessages(&node, flagInterruptMsgProc);
     103                 :             :     }
     104                 :             : 
     105                 :             :     void NodeReceiveMsgBytes(CNode& node, std::span<const uint8_t> msg_bytes, bool& complete) const;
     106                 :             : 
     107                 :             :     bool ReceiveMsgFrom(CNode& node, CSerializedNetMsg&& ser_msg) const;
     108                 :             :     void FlushSendBuffer(CNode& node) const;
     109                 :             : 
     110         [ +  - ]:           6 :     bool AlreadyConnectedToAddressPublic(const CNetAddr& addr) { return AlreadyConnectedToAddress(addr); };
     111                 :             : 
     112                 :             :     CNode* ConnectNodePublic(PeerManager& peerman, const char* pszDest, ConnectionType conn_type)
     113                 :             :         EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex);
     114                 :             : };
     115                 :             : 
     116                 :             : constexpr ServiceFlags ALL_SERVICE_FLAGS[]{
     117                 :             :     NODE_NONE,
     118                 :             :     NODE_NETWORK,
     119                 :             :     NODE_BLOOM,
     120                 :             :     NODE_WITNESS,
     121                 :             :     NODE_COMPACT_FILTERS,
     122                 :             :     NODE_NETWORK_LIMITED,
     123                 :             :     NODE_P2P_V2,
     124                 :             : };
     125                 :             : 
     126                 :             : constexpr NetPermissionFlags ALL_NET_PERMISSION_FLAGS[]{
     127                 :             :     NetPermissionFlags::None,
     128                 :             :     NetPermissionFlags::BloomFilter,
     129                 :             :     NetPermissionFlags::Relay,
     130                 :             :     NetPermissionFlags::ForceRelay,
     131                 :             :     NetPermissionFlags::NoBan,
     132                 :             :     NetPermissionFlags::Mempool,
     133                 :             :     NetPermissionFlags::Addr,
     134                 :             :     NetPermissionFlags::Download,
     135                 :             :     NetPermissionFlags::Implicit,
     136                 :             :     NetPermissionFlags::All,
     137                 :             : };
     138                 :             : 
     139                 :             : constexpr ConnectionType ALL_CONNECTION_TYPES[]{
     140                 :             :     ConnectionType::INBOUND,
     141                 :             :     ConnectionType::OUTBOUND_FULL_RELAY,
     142                 :             :     ConnectionType::MANUAL,
     143                 :             :     ConnectionType::FEELER,
     144                 :             :     ConnectionType::BLOCK_RELAY,
     145                 :             :     ConnectionType::ADDR_FETCH,
     146                 :             : };
     147                 :             : 
     148                 :             : constexpr auto ALL_NETWORKS = std::array{
     149                 :             :     Network::NET_UNROUTABLE,
     150                 :             :     Network::NET_IPV4,
     151                 :             :     Network::NET_IPV6,
     152                 :             :     Network::NET_ONION,
     153                 :             :     Network::NET_I2P,
     154                 :             :     Network::NET_CJDNS,
     155                 :             :     Network::NET_INTERNAL,
     156                 :             : };
     157                 :             : 
     158                 :             : /**
     159                 :             :  * A mocked Sock alternative that succeeds on all operations.
     160                 :             :  * Returns infinite amount of 0x0 bytes on reads.
     161                 :             :  */
     162                 :             : class ZeroSock : public Sock
     163                 :             : {
     164                 :             : public:
     165                 :             :     ZeroSock();
     166                 :             : 
     167                 :             :     ~ZeroSock() override;
     168                 :             : 
     169                 :             :     ssize_t Send(const void*, size_t len, int) const override;
     170                 :             : 
     171                 :             :     ssize_t Recv(void* buf, size_t len, int flags) const override;
     172                 :             : 
     173                 :             :     int Connect(const sockaddr*, socklen_t) const override;
     174                 :             : 
     175                 :             :     int Bind(const sockaddr*, socklen_t) const override;
     176                 :             : 
     177                 :             :     int Listen(int) const override;
     178                 :             : 
     179                 :             :     std::unique_ptr<Sock> Accept(sockaddr* addr, socklen_t* addr_len) const override;
     180                 :             : 
     181                 :             :     int GetSockOpt(int level, int opt_name, void* opt_val, socklen_t* opt_len) const override;
     182                 :             : 
     183                 :             :     int SetSockOpt(int, int, const void*, socklen_t) const override;
     184                 :             : 
     185                 :             :     int GetSockName(sockaddr* name, socklen_t* name_len) const override;
     186                 :             : 
     187                 :             :     bool SetNonBlocking() const override;
     188                 :             : 
     189                 :             :     bool IsSelectable() const override;
     190                 :             : 
     191                 :             :     bool Wait(std::chrono::milliseconds timeout,
     192                 :             :               Event requested,
     193                 :             :               Event* occurred = nullptr) const override;
     194                 :             : 
     195                 :             :     bool WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per_sock) const override;
     196                 :             : 
     197                 :             : private:
     198                 :             :     ZeroSock& operator=(Sock&& other) override;
     199                 :             : };
     200                 :             : 
     201                 :             : /**
     202                 :             :  * A mocked Sock alternative that returns a statically contained data upon read and succeeds
     203                 :             :  * and ignores all writes. The data to be returned is given to the constructor and when it is
     204                 :             :  * exhausted an EOF is returned by further reads.
     205                 :             :  */
     206                 :             : class StaticContentsSock : public ZeroSock
     207                 :             : {
     208                 :             : public:
     209                 :             :     explicit StaticContentsSock(const std::string& contents);
     210                 :             : 
     211                 :             :     /**
     212                 :             :      * Return parts of the contents that was provided at construction until it is exhausted
     213                 :             :      * and then return 0 (EOF).
     214                 :             :      */
     215                 :             :     ssize_t Recv(void* buf, size_t len, int flags) const override;
     216                 :             : 
     217                 :           0 :     bool IsConnected(std::string&) const override
     218                 :             :     {
     219                 :           0 :         return true;
     220                 :             :     }
     221                 :             : 
     222                 :             : private:
     223                 :             :     StaticContentsSock& operator=(Sock&& other) override;
     224                 :             : 
     225                 :             :     const std::string m_contents;
     226                 :             :     mutable size_t m_consumed{0};
     227                 :             : };
     228                 :             : 
     229                 :             : /**
     230                 :             :  * A mocked Sock alternative that allows providing the data to be returned by Recv()
     231                 :             :  * and inspecting the data that has been supplied to Send().
     232                 :             :  */
     233                 :             : class DynSock : public ZeroSock
     234                 :             : {
     235                 :             : public:
     236                 :             :     /**
     237                 :             :      * Unidirectional bytes or CNetMessage queue (FIFO).
     238                 :             :      */
     239                 :             :     class Pipe
     240                 :             :     {
     241                 :             :     public:
     242                 :             :         /**
     243                 :             :          * Get bytes and remove them from the pipe.
     244                 :             :          * @param[in] buf Destination to write bytes to.
     245                 :             :          * @param[in] len Write up to this number of bytes.
     246                 :             :          * @param[in] flags Same as the flags of `recv(2)`. Just `MSG_PEEK` is honored.
     247                 :             :          * @return The number of bytes written to `buf`. `0` if `Eof()` has been called.
     248                 :             :          * If no bytes are available then `-1` is returned and `errno` is set to `EAGAIN`.
     249                 :             :          */
     250                 :             :         ssize_t GetBytes(void* buf, size_t len, int flags = 0) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
     251                 :             : 
     252                 :             :         /**
     253                 :             :          * Deserialize a `CNetMessage` and remove it from the pipe.
     254                 :             :          * If not enough bytes are available then the function will wait. If parsing fails
     255                 :             :          * or EOF is signaled to the pipe, then `std::nullopt` is returned.
     256                 :             :          */
     257                 :             :         std::optional<CNetMessage> GetNetMsg() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
     258                 :             : 
     259                 :             :         /**
     260                 :             :          * Push bytes to the pipe.
     261                 :             :          */
     262                 :             :         void PushBytes(const void* buf, size_t len) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
     263                 :             : 
     264                 :             :         /**
     265                 :             :          * Construct and push CNetMessage to the pipe.
     266                 :             :          */
     267                 :             :         template <typename... Args>
     268                 :             :         void PushNetMsg(const std::string& type, Args&&... payload) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
     269                 :             : 
     270                 :             :         /**
     271                 :             :          * Signal end-of-file on the receiving end (`GetBytes()` or `GetNetMsg()`).
     272                 :             :          */
     273                 :             :         void Eof() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
     274                 :             : 
     275                 :             :     private:
     276                 :             :         /**
     277                 :             :          * Return when there is some data to read or EOF has been signaled.
     278                 :             :          * @param[in,out] lock Unique lock that must have been derived from `m_mutex` by `WAIT_LOCK(m_mutex, lock)`.
     279                 :             :          */
     280                 :             :         void WaitForDataOrEof(UniqueLock<Mutex>& lock) EXCLUSIVE_LOCKS_REQUIRED(m_mutex);
     281                 :             : 
     282                 :             :         Mutex m_mutex;
     283                 :             :         std::condition_variable m_cond;
     284                 :             :         std::vector<uint8_t> m_data GUARDED_BY(m_mutex);
     285                 :             :         bool m_eof GUARDED_BY(m_mutex){false};
     286                 :             :     };
     287                 :             : 
     288                 :             :     struct Pipes {
     289                 :             :         Pipe recv;
     290                 :             :         Pipe send;
     291                 :             :     };
     292                 :             : 
     293                 :             :     /**
     294                 :             :      * A basic thread-safe queue, used for queuing sockets to be returned by Accept().
     295                 :             :      */
     296                 :             :     class Queue
     297                 :             :     {
     298                 :             :     public:
     299                 :             :         using S = std::unique_ptr<DynSock>;
     300                 :             : 
     301                 :             :         void Push(S s) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
     302                 :             :         {
     303                 :             :             LOCK(m_mutex);
     304                 :             :             m_queue.push(std::move(s));
     305                 :             :         }
     306                 :             : 
     307                 :           0 :         std::optional<S> Pop() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
     308                 :             :         {
     309                 :           0 :             LOCK(m_mutex);
     310         [ #  # ]:           0 :             if (m_queue.empty()) {
     311                 :           0 :                 return std::nullopt;
     312                 :             :             }
     313                 :           0 :             S front{std::move(m_queue.front())};
     314                 :           0 :             m_queue.pop();
     315                 :           0 :             return front;
     316                 :           0 :         }
     317                 :             : 
     318                 :           0 :         bool Empty() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
     319                 :             :         {
     320                 :           0 :             LOCK(m_mutex);
     321         [ #  # ]:           0 :             return m_queue.empty();
     322                 :           0 :         }
     323                 :             : 
     324                 :             :     private:
     325                 :             :         mutable Mutex m_mutex;
     326                 :             :         std::queue<S> m_queue GUARDED_BY(m_mutex);
     327                 :             :     };
     328                 :             : 
     329                 :             :     /**
     330                 :             :      * Create a new mocked sock.
     331                 :             :      * @param[in] pipes Send/recv pipes used by the Send() and Recv() methods.
     332                 :             :      * @param[in] accept_sockets Sockets to return by the Accept() method.
     333                 :             :      */
     334                 :             :     explicit DynSock(std::shared_ptr<Pipes> pipes, std::shared_ptr<Queue> accept_sockets);
     335                 :             : 
     336                 :             :     ~DynSock();
     337                 :             : 
     338                 :             :     ssize_t Recv(void* buf, size_t len, int flags) const override;
     339                 :             : 
     340                 :             :     ssize_t Send(const void* buf, size_t len, int) const override;
     341                 :             : 
     342                 :             :     std::unique_ptr<Sock> Accept(sockaddr* addr, socklen_t* addr_len) const override;
     343                 :             : 
     344                 :             :     bool Wait(std::chrono::milliseconds timeout,
     345                 :             :               Event requested,
     346                 :             :               Event* occurred = nullptr) const override;
     347                 :             : 
     348                 :             :     bool WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per_sock) const override;
     349                 :             : 
     350                 :             : private:
     351                 :             :     DynSock& operator=(Sock&&) override;
     352                 :             : 
     353                 :             :     std::shared_ptr<Pipes> m_pipes;
     354                 :             :     std::shared_ptr<Queue> m_accept_sockets;
     355                 :             : };
     356                 :             : 
     357                 :             : template <typename... Args>
     358                 :             : void DynSock::Pipe::PushNetMsg(const std::string& type, Args&&... payload)
     359                 :             : {
     360                 :             :     auto msg = NetMsg::Make(type, std::forward<Args>(payload)...);
     361                 :             :     V1Transport transport{NodeId{0}};
     362                 :             : 
     363                 :             :     const bool queued{transport.SetMessageToSend(msg)};
     364                 :             :     assert(queued);
     365                 :             : 
     366                 :             :     LOCK(m_mutex);
     367                 :             : 
     368                 :             :     for (;;) {
     369                 :             :         const auto& [bytes, _more, _msg_type] = transport.GetBytesToSend(/*have_next_message=*/true);
     370                 :             :         if (bytes.empty()) {
     371                 :             :             break;
     372                 :             :         }
     373                 :             :         m_data.insert(m_data.end(), bytes.begin(), bytes.end());
     374                 :             :         transport.MarkBytesSent(bytes.size());
     375                 :             :     }
     376                 :             : 
     377                 :             :     m_cond.notify_all();
     378                 :             : }
     379                 :             : 
     380                 :             : std::vector<NodeEvictionCandidate> GetRandomNodeEvictionCandidates(int n_candidates, FastRandomContext& random_context);
     381                 :             : 
     382                 :             : #endif // BITCOIN_TEST_UTIL_NET_H
        

Generated by: LCOV version 2.0-1