LCOV - code coverage report
Current view: top level - src - net.h (source / functions) Hit Total Coverage
Test: total_coverage.info Lines: 105 123 85.4 %
Date: 2025-02-23 09:33:43 Functions: 27 32 84.4 %

          Line data    Source code
       1             : // Copyright (c) 2009-2010 Satoshi Nakamoto
       2             : // Copyright (c) 2009-2015 The Bitcoin developers
       3             : // Copyright (c) 2015-2022 The PIVX Core developers
       4             : // Distributed under the MIT/X11 software license, see the accompanying
       5             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       6             : 
       7             : #ifndef PIVX_NET_H
       8             : #define PIVX_NET_H
       9             : 
      10             : #include "addrdb.h"
      11             : #include "addrman.h"
      12             : #include "bloom.h"
      13             : #include "compat.h"
      14             : #include "crypto/siphash.h"
      15             : #include "fs.h"
      16             : #include "hash.h"
      17             : #include "limitedmap.h"
      18             : #include "netaddress.h"
      19             : #include "protocol.h"
      20             : #include "random.h"
      21             : #include "streams.h"
      22             : #include "sync.h"
      23             : #include "uint256.h"
      24             : #include "utilstrencodings.h"
      25             : #include "threadinterrupt.h"
      26             : #include "validation.h"
      27             : 
      28             : #include <atomic>
      29             : #include <cstdint>
      30             : #include <deque>
      31             : #include <thread>
      32             : #include <memory>
      33             : #include <condition_variable>
      34             : 
      35             : #ifndef WIN32
      36             : #include <arpa/inet.h>
      37             : #endif
      38             : 
      39             : // "Optimistic send" was introduced in the beginning of the Bitcoin project. I assume this was done because it was
      40             : // thought that "send" would be very cheap when the send buffer is empty. This is not true, as shown by profiling.
      41             : // When a lot of load is seen on the network, the "send" call done in the message handler thread can easily use up 20%
      42             : // of time, effectively blocking things that could be done in parallel. We have introduced a way to wake up the select()
      43             : // call in the network thread, which allows us to disable optimistic send without introducing an artificial latency/delay
      44             : // when sending data. This however only works on non-WIN32 platforms for now. When we add support for WIN32 platforms,
      45             : // we can completely remove optimistic send.
      46             : #ifdef WIN32
      47             : #define DEFAULT_ALLOW_OPTIMISTIC_SEND true
      48             : #else
      49             : #define DEFAULT_ALLOW_OPTIMISTIC_SEND false
      50             : #define USE_WAKEUP_PIPE
      51             : #endif
      52             : 
      53             : class CAddrMan;
      54             : class CBlockIndex;
      55             : class CScheduler;
      56             : class CNode;
      57             : class TierTwoConnMan;
      58             : 
      59             : /** Time between pings automatically sent out for latency probing and keepalive (in seconds). */
      60             : static const int PING_INTERVAL = 2 * 60;
      61             : /** Time after which to disconnect, after waiting for a ping response (or inactivity). */
      62             : static const int TIMEOUT_INTERVAL = 20 * 60;
      63             : /** Run the feeler connection loop once every 2 minutes or 120 seconds. **/
      64             : static const int FEELER_INTERVAL = 120;
      65             : /** The maximum number of entries in an 'inv' protocol message */
      66             : static const unsigned int MAX_INV_SZ = 50000;
      67             : /** The maximum number of entries in a locator */
      68             : static const unsigned int MAX_LOCATOR_SZ = 101;
      69             : /** The maximum number of addresses from our addrman to return in response to a getaddr message. */
      70             : static constexpr size_t MAX_ADDR_TO_SEND = 1000;
      71             : /** The maximum rate of address records we're willing to process on average. */
      72             : static constexpr double MAX_ADDR_RATE_PER_SECOND{0.1};
      73             : /** The soft limit of the address processing token bucket (the regular MAX_ADDR_RATE_PER_SECOND
      74             :  *  based increments won't go above this, but the MAX_ADDR_TO_SEND increment following GETADDR
      75             :  *  is exempt from this limit. */
      76             : static constexpr size_t MAX_ADDR_PROCESSING_TOKEN_BUCKET{MAX_ADDR_TO_SEND};
      77             : /** Maximum length of incoming protocol messages (no message over 2 MiB is currently acceptable). */
      78             : static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 2 * 1024 * 1024;
      79             : /** Maximum length of strSubVer in `version` message */
      80             : static const unsigned int MAX_SUBVERSION_LENGTH = 256;
      81             : /** Maximum number of automatic outgoing nodes */
      82             : static const int MAX_OUTBOUND_CONNECTIONS = 16;
      83             : /** Maximum number of addnode outgoing nodes */
      84             : static const int MAX_ADDNODE_CONNECTIONS = 16;
      85             : /** Eviction protection time for incoming connections  */
      86             : static const int INBOUND_EVICTION_PROTECTION_TIME = 1;
      87             : /** -listen default */
      88             : static const bool DEFAULT_LISTEN = true;
      89             : /** The maximum number of entries in mapAskFor */
      90             : static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ;
      91             : /** The maximum number of entries in setAskFor (larger due to getdata latency)*/
      92             : static const size_t SETASKFOR_MAX_SZ = 2 * MAX_INV_SZ;
      93             : /** The maximum number of peer connections to maintain. */
      94             : static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
      95             : /** Disconnected peers are added to setOffsetDisconnectedPeers only if node has less than ENOUGH_CONNECTIONS */
      96             : #define ENOUGH_CONNECTIONS 2
      97             : /** Maximum number of peers added to setOffsetDisconnectedPeers before triggering a warning */
      98             : #define MAX_TIMEOFFSET_DISCONNECTIONS 16
      99             : 
     100             : static const ServiceFlags REQUIRED_SERVICES = NODE_NETWORK;
     101             : 
     102             : static const bool DEFAULT_FORCEDNSSEED = false;
     103             : static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
     104             : static const size_t DEFAULT_MAXSENDBUFFER    = 1 * 1000;
     105             : 
     106             : // NOTE: When adjusting this, update rpcnet:setban's help ("24h")
     107             : static const unsigned int DEFAULT_MISBEHAVING_BANTIME = 60 * 60 * 24;  // Default 24-hour ban
     108             : 
     109             : typedef int NodeId;
     110             : 
     111             : struct AddedNodeInfo
     112             : {
     113             :     std::string strAddedNode;
     114             :     CService resolvedAddress;
     115             :     bool fConnected;
     116             :     bool fInbound;
     117             : 
     118           3 :     AddedNodeInfo(const std::string& _strAddedNode, const CService& _resolvedAddress, bool _fConnected, bool _fInbound):
     119             :         strAddedNode(_strAddedNode),
     120             :         resolvedAddress(_resolvedAddress),
     121             :         fConnected(_fConnected),
     122           3 :         fInbound(_fInbound)
     123           3 :     {}
     124             : };
     125             : 
     126             : class CTransaction;
     127             : class CNodeStats;
     128             : class CClientUIInterface;
     129             : 
     130             : struct CSerializedNetMsg
     131             : {
     132      329466 :     CSerializedNetMsg() = default;
     133             :     CSerializedNetMsg(CSerializedNetMsg&&) = default;
     134             :     CSerializedNetMsg& operator=(CSerializedNetMsg&&) = default;
     135             :     // No copying, only moves.
     136             :     CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
     137             :     CSerializedNetMsg& operator=(const CSerializedNetMsg&) = delete;
     138             : 
     139             :     std::vector<unsigned char> data;
     140             :     std::string command;
     141             : };
     142             : 
     143             : class NetEventsInterface;
     144             : class CConnman
     145             : {
     146             : public:
     147             : 
     148             :     enum NumConnections {
     149             :         CONNECTIONS_NONE = 0,
     150             :         CONNECTIONS_IN = (1U << 0),
     151             :         CONNECTIONS_OUT = (1U << 1),
     152             :         CONNECTIONS_ALL = (CONNECTIONS_IN | CONNECTIONS_OUT),
     153             :     };
     154             : 
     155             :     struct Options
     156             :     {
     157             :         ServiceFlags nLocalServices = NODE_NONE;
     158             :         ServiceFlags nRelevantServices = NODE_NONE;
     159             :         int nMaxConnections = 0;
     160             :         int nMaxOutbound = 0;
     161             :         int nMaxAddnode = 0;
     162             :         int nMaxFeeler = 0;
     163             :         int nBestHeight = 0;
     164             :         CClientUIInterface* uiInterface = nullptr;
     165             :         NetEventsInterface* m_msgproc = nullptr;
     166             :         unsigned int nSendBufferMaxSize = 0;
     167             :         unsigned int nReceiveFloodSize = 0;
     168             :         std::vector<bool> m_asmap;
     169             :         std::vector<std::string> vSeedNodes;
     170             :         std::vector<CSubNet> vWhitelistedRange;
     171             :         std::vector<CService> vBinds, vWhiteBinds;
     172             :         bool m_use_addrman_outgoing = true;
     173             :         std::vector<std::string> m_specified_outgoing;
     174             :         std::vector<std::string> m_added_nodes;
     175             :     };
     176             : 
     177         839 :     void Init(const Options& connOptions) {
     178         839 :         nLocalServices = connOptions.nLocalServices;
     179         839 :         nRelevantServices = connOptions.nRelevantServices;
     180         839 :         nMaxConnections = connOptions.nMaxConnections;
     181         839 :         nMaxOutbound = std::min(connOptions.nMaxOutbound, connOptions.nMaxConnections);
     182         839 :         nMaxAddnode = connOptions.nMaxAddnode;
     183         839 :         nMaxFeeler = connOptions.nMaxFeeler;
     184         839 :         nBestHeight = connOptions.nBestHeight;
     185         839 :         clientInterface = connOptions.uiInterface;
     186         839 :         nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
     187         839 :         nReceiveFloodSize = connOptions.nReceiveFloodSize;
     188         839 :         vWhitelistedRange = connOptions.vWhitelistedRange;
     189         839 :         {
     190         839 :             LOCK(cs_vAddedNodes);
     191         839 :             vAddedNodes = connOptions.m_added_nodes;
     192             :         }
     193         839 :     }
     194             : 
     195             :     CConnman(uint64_t seed0, uint64_t seed1);
     196             :     ~CConnman();
     197             :     bool Start(CScheduler& scheduler, const Options& options);
     198             :     void Stop();
     199             :     void Interrupt();
     200       24343 :     bool GetNetworkActive() const { return fNetworkActive; };
     201             :     void SetNetworkActive(bool active);
     202             :     void OpenNetworkConnection(const CAddress& addrConnect,
     203             :                                bool fCountFailure,
     204             :                                CSemaphoreGrant* grantOutbound = nullptr,
     205             :                                const char* strDest = nullptr,
     206             :                                bool fOneShot = false,
     207             :                                bool fFeeler = false,
     208             :                                bool fAddnode = false,
     209             :                                bool masternode_connection = false,
     210             :                                bool masternode_probe_connection = false);
     211             :     bool CheckIncomingNonce(uint64_t nonce);
     212             : 
     213             :     struct CFullyConnectedOnly {
     214      444036 :         bool operator() (const CNode* pnode) const {
     215      444036 :             return NodeFullyConnected(pnode);
     216             :         }
     217             :     };
     218             :     struct CAllNodes {
     219    10318400 :         bool operator() (const CNode*) const {return true;}
     220             :     };
     221             :     constexpr static const CFullyConnectedOnly FullyConnectedOnly{};
     222             :     constexpr static const CAllNodes AllNodes{};
     223             : 
     224             :     bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
     225             :     bool ForNode(const CService& addr, const std::function<bool(const CNode* pnode)>& cond, const std::function<bool(CNode* pnode)>& func);
     226             : 
     227             :     void PushMessage(CNode* pnode, CSerializedNetMsg&& msg, bool allowOptimisticSend = DEFAULT_ALLOW_OPTIMISTIC_SEND);
     228             : 
     229             :     template<typename Callable>
     230           0 :     bool ForEachNodeContinueIf(Callable&& func)
     231             :     {
     232           0 :         LOCK(cs_vNodes);
     233           0 :         for (auto&& node : vNodes)
     234           0 :             if (NodeFullyConnected(node)) {
     235           0 :                 if (!func(node))
     236           0 :                     return false;
     237             :             }
     238           0 :         return true;
     239             :     };
     240             : 
     241             :     template<typename Callable>
     242           0 :     bool ForEachNodeInRandomOrderContinueIf(Callable&& func)
     243             :     {
     244           0 :         FastRandomContext ctx;
     245           0 :         LOCK(cs_vNodes);
     246           0 :         std::vector<CNode*> nodesCopy = vNodes;
     247           0 :         std::shuffle(nodesCopy.begin(), nodesCopy.end(), ctx);
     248           0 :         for (auto&& node : nodesCopy)
     249           0 :             if (NodeFullyConnected(node)) {
     250           0 :                 if (!func(node))
     251           0 :                     return false;
     252             :             }
     253           0 :         return true;
     254             :     };
     255             : 
     256             :     template<typename Callable>
     257      193505 :     void ForEachNode(Callable&& func)
     258             :     {
     259      193505 :         LOCK(cs_vNodes);
     260      708769 :         for (auto&& node : vNodes) {
     261      515264 :             if (NodeFullyConnected(node))
     262      548703 :                 func(node);
     263             :         }
     264      193505 :     };
     265             : 
     266             :     template<typename Callable>
     267             :     void ForEachNode(Callable&& func) const
     268             :     {
     269             :         LOCK(cs_vNodes);
     270             :         for (auto&& node : vNodes) {
     271             :             if (NodeFullyConnected(node))
     272             :                 func(node);
     273             :         }
     274             :     };
     275             : 
     276             :     template<typename Callable, typename CallableAfter>
     277          21 :     void ForEachNodeThen(Callable&& pre, CallableAfter&& post)
     278             :     {
     279          21 :         LOCK(cs_vNodes);
     280          62 :         for (auto&& node : vNodes) {
     281          41 :             if (NodeFullyConnected(node))
     282          41 :                 pre(node);
     283             :         }
     284          21 :         post();
     285          21 :     };
     286             : 
     287             :     template<typename Callable, typename CallableAfter>
     288             :     void ForEachNodeThen(Callable&& pre, CallableAfter&& post) const
     289             :     {
     290             :         LOCK(cs_vNodes);
     291             :         for (auto&& node : vNodes) {
     292             :             if (NodeFullyConnected(node))
     293             :                 pre(node);
     294             :         }
     295             :         post();
     296             :     };
     297             : 
     298             :     std::vector<CNode*> CopyNodeVector(std::function<bool(const CNode* pnode)> cond);
     299             :     std::vector<CNode*> CopyNodeVector();
     300             :     void ReleaseNodeVector(const std::vector<CNode*>& vecNodes);
     301             : 
     302             :     // Clears AskFor requests for every known peer
     303             :     void RemoveAskFor(const uint256& invHash, int invType);
     304             : 
     305             :     void RelayInv(CInv& inv, int minProtoVersion = ActiveProtocol());
     306             :     bool IsNodeConnected(const CAddress& addr);
     307             :     // Retrieves a connected peer (if connection success). Used only to check peer address availability for now.
     308             :     CNode* ConnectNode(const CAddress& addrConnect);
     309             : 
     310             :     // Addrman functions
     311             :     void SetServices(const CService &addr, ServiceFlags nServices);
     312             :     void MarkAddressGood(const CAddress& addr);
     313             :     void AddNewAddress(const CAddress& addr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
     314             :     bool AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
     315             :     /**
     316             :      * Return all or many randomly selected addresses, optionally by network.
     317             :      *
     318             :      * @param[in] max_addresses  Maximum number of addresses to return (0 = all).
     319             :      * @param[in] max_pct        Maximum percentage of addresses to return (0 = all).
     320             :      * @param[in] network        Select only addresses of this network (nullopt = all).
     321             :      */
     322             :     std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct, Optional<Network> network);
     323             : 
     324             :     // Denial-of-service detection/prevention
     325             :     // The idea is to detect peers that are behaving
     326             :     // badly and disconnect/ban them, but do it in a
     327             :     // one-coding-mistake-won't-shatter-the-entire-network
     328             :     // way.
     329             :     // IMPORTANT:  There should be nothing I can give a
     330             :     // node that it will forward on that will make that
     331             :     // node's peers drop it. If there is, an attacker
     332             :     // can isolate a node and/or try to split the network.
     333             :     // Dropping a node for sending stuff that is invalid
     334             :     // now but might be valid in a later version is also
     335             :     // dangerous, because it can cause a network split
     336             :     // between nodes running old code and nodes running
     337             :     // new code.
     338             :     void Ban(const CNetAddr& netAddr, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
     339             :     void Ban(const CSubNet& subNet, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
     340             :     void ClearBanned(); // needed for unit testing
     341             :     bool IsBanned(CNetAddr ip);
     342             :     bool IsBanned(CSubNet subnet);
     343             :     bool Unban(const CNetAddr &ip);
     344             :     bool Unban(const CSubNet &ip);
     345             :     void GetBanned(banmap_t &banmap);
     346             :     void SetBanned(const banmap_t &banmap);
     347             : 
     348             :     bool AddNode(const std::string& node);
     349             :     bool RemoveAddedNode(const std::string& node);
     350             :     std::vector<AddedNodeInfo> GetAddedNodeInfo();
     351             : 
     352             :     size_t GetNodeCount(NumConnections num);
     353             :     size_t GetMaxOutboundNodeCount();
     354             :     void GetNodeStats(std::vector<CNodeStats>& vstats);
     355             :     bool DisconnectNode(const std::string& node);
     356             :     bool DisconnectNode(NodeId id);
     357             : 
     358             :     unsigned int GetSendBufferSize() const;
     359             : 
     360             :     ServiceFlags GetLocalServices() const;
     361             : 
     362             :     uint64_t GetTotalBytesRecv();
     363             :     uint64_t GetTotalBytesSent();
     364             : 
     365             :     void SetBestHeight(int height);
     366             :     int GetBestHeight() const;
     367             : 
     368             :     /** Get a unique deterministic randomizer. */
     369             :     CSipHasher GetDeterministicRandomizer(uint64_t id);
     370             : 
     371             :     unsigned int GetReceiveFloodSize() const;
     372             : 
     373           4 :     void SetAsmap(std::vector<bool> asmap) { addrman.m_asmap = std::move(asmap); }
     374             :     /** Unique tier two connections manager */
     375       10763 :     TierTwoConnMan* GetTierTwoConnMan() { return m_tiertwo_conn_man.get(); };
     376             :     /** Update the node to be a iqr member if needed */
     377             :     void UpdateQuorumRelayMemberIfNeeded(CNode* pnode);
     378             :     /** Interrupt the select/poll system call **/
     379             :     void WakeSelect();
     380             : 
     381             : private:
     382             :     struct ListenSocket {
     383             :         SOCKET socket;
     384             :         bool whitelisted;
     385             : 
     386         346 :         ListenSocket(SOCKET socket_, bool whitelisted_) : socket(socket_), whitelisted(whitelisted_) {}
     387             :     };
     388             : 
     389             :     bool BindListenPort(const CService& bindAddr, std::string& strError, bool fWhitelisted = false);
     390             :     bool Bind(const CService& addr, unsigned int flags);
     391             :     bool InitBinds(const std::vector<CService>& binds, const std::vector<CService>& whiteBinds);
     392             :     void ThreadOpenAddedConnections();
     393             :     void AddOneShot(const std::string& strDest);
     394             :     void ProcessOneShot();
     395             :     void ThreadOpenConnections(const std::vector<std::string> connect);
     396             :     void ThreadMessageHandler();
     397             :     void AcceptConnection(const ListenSocket& hListenSocket);
     398             :     void DisconnectNodes();
     399             :     void NotifyNumConnectionsChanged();
     400             :     void InactivityCheck(CNode* pnode);
     401             :     bool GenerateSelectSet(std::set<SOCKET>& recv_set, std::set<SOCKET>& send_set, std::set<SOCKET>& error_set);
     402             :     void SocketEvents(std::set<SOCKET>& recv_set, std::set<SOCKET>& send_set, std::set<SOCKET>& error_set);
     403             :     void SocketHandler();
     404             :     void ThreadSocketHandler();
     405             :     void ThreadDNSAddressSeed();
     406             : 
     407             :     void WakeMessageHandler();
     408             : 
     409             :     uint64_t CalculateKeyedNetGroup(const CAddress& ad);
     410             : 
     411             :     CNode* FindNode(const CNetAddr& ip);
     412             :     CNode* FindNode(const CSubNet& subNet);
     413             :     CNode* FindNode(const std::string& addrName);
     414             :     CNode* FindNode(const CService& addr);
     415             : 
     416             :     bool AttemptToEvictConnection(bool fPreferNewConnection);
     417             :     CNode* ConnectNode(CAddress addrConnect, const char* pszDest, bool fCountFailure, bool manual_connection);
     418             :     bool IsWhitelistedRange(const CNetAddr &addr);
     419             : 
     420             :     void DeleteNode(CNode* pnode);
     421             : 
     422             :     NodeId GetNewNodeId();
     423             : 
     424             :     size_t SocketSendData(CNode *pnode);
     425             :     //!check is the banlist has unwritten changes
     426             :     bool BannedSetIsDirty();
     427             :     //!set the "dirty" flag for the banlist
     428             :     void SetBannedSetDirty(bool dirty=true);
     429             :     //!clean unused entries (if bantime has expired)
     430             :     void SweepBanned();
     431             :     void DumpAddresses();
     432             :     void DumpData();
     433             :     void DumpBanlist();
     434             : 
     435             :     // Network stats
     436             :     void RecordBytesRecv(uint64_t bytes);
     437             :     void RecordBytesSent(uint64_t bytes);
     438             : 
     439             :     // Whether the node should be passed out in ForEach* callbacks
     440             :     static bool NodeFullyConnected(const CNode* pnode);
     441             : 
     442             :     // Network usage totals
     443             :     RecursiveMutex cs_totalBytesRecv;
     444             :     RecursiveMutex cs_totalBytesSent;
     445             :     uint64_t nTotalBytesRecv GUARDED_BY(cs_totalBytesRecv) = 0;
     446             :     uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent) = 0;
     447             : 
     448             :     // Whitelisted ranges. Any node connecting from these is automatically
     449             :     // whitelisted (as well as those connecting to whitelisted binds).
     450             :     std::vector<CSubNet> vWhitelistedRange;
     451             : 
     452             :     unsigned int nSendBufferMaxSize{0};
     453             :     unsigned int nReceiveFloodSize{0};
     454             : 
     455             :     std::vector<ListenSocket> vhListenSocket;
     456             :     std::atomic<bool> fNetworkActive{true};
     457             :     banmap_t setBanned;
     458             :     RecursiveMutex cs_setBanned;
     459             :     bool setBannedIsDirty{false};
     460             :     bool fAddressesInitialized{false};
     461             :     CAddrMan addrman;
     462             :     std::deque<std::string> vOneShots;
     463             :     RecursiveMutex cs_vOneShots;
     464             :     std::vector<std::string> vAddedNodes GUARDED_BY(cs_vAddedNodes);
     465             :     RecursiveMutex cs_vAddedNodes;
     466             :     std::vector<CNode*> vNodes;
     467             :     std::list<CNode*> vNodesDisconnected;
     468             :     mutable RecursiveMutex cs_vNodes;
     469             :     std::atomic<NodeId> nLastNodeId;
     470             :     unsigned int nPrevNodeCount;
     471             : 
     472             :     /** Services this instance offers */
     473             :     ServiceFlags nLocalServices{NODE_NONE};
     474             : 
     475             :     /** Services this instance cares about */
     476             :     ServiceFlags nRelevantServices{NODE_NONE};
     477             : 
     478             :     std::unique_ptr<CSemaphore> semOutbound;
     479             :     std::unique_ptr<CSemaphore> semAddnode;
     480             :     int nMaxConnections{0};
     481             :     int nMaxOutbound{0};
     482             :     int nMaxAddnode;
     483             :     int nMaxFeeler{0};
     484             :     std::atomic<int> nBestHeight;
     485             :     CClientUIInterface* clientInterface{nullptr};
     486             :     NetEventsInterface* m_msgproc{nullptr};
     487             : 
     488             :     /** SipHasher seeds for deterministic randomness */
     489             :     const uint64_t nSeed0{0}, nSeed1{0};
     490             : 
     491             :     /** flag for waking the message processor. */
     492             :     bool fMsgProcWake{false};
     493             : 
     494             :     std::condition_variable condMsgProc;
     495             :     std::mutex mutexMsgProc;
     496             :     std::atomic<bool> flagInterruptMsgProc;
     497             : 
     498             :     CThreadInterrupt interruptNet;
     499             : 
     500             : #ifdef USE_WAKEUP_PIPE
     501             :     /** a pipe which is added to select() calls to wakeup before the timeout */
     502             :     int wakeupPipe[2]{-1, -1};
     503             : #endif
     504             :     std::atomic<bool> wakeupSelectNeeded{false};
     505             : 
     506             :     std::thread threadDNSAddressSeed;
     507             :     std::thread threadSocketHandler;
     508             :     std::thread threadOpenAddedConnections;
     509             :     std::thread threadOpenConnections;
     510             :     std::thread threadMessageHandler;
     511             : 
     512             :     std::unique_ptr<TierTwoConnMan> m_tiertwo_conn_man;
     513             : };
     514             : extern std::unique_ptr<CConnman> g_connman;
     515             : void Discover();
     516             : uint16_t GetListenPort();
     517             : bool BindListenPort(const CService& bindAddr, std::string& strError, bool fWhitelisted = false);
     518             : void CheckOffsetDisconnectedPeers(const CNetAddr& ip);
     519             : 
     520             : struct CombinerAll {
     521             :     typedef bool result_type;
     522             : 
     523             :     template <typename I>
     524           5 :     bool operator()(I first, I last) const
     525             :     {
     526           6 :         while (first != last) {
     527           3 :             if (!(*first)) return false;
     528           6 :             ++first;
     529             :         }
     530             :         return true;
     531             :     }
     532             : };
     533             : 
     534             : enum {
     535             :     LOCAL_NONE,   // unknown
     536             :     LOCAL_IF,     // address a local interface listens on
     537             :     LOCAL_BIND,   // address explicit bound to
     538             :     LOCAL_MAPPED, // address reported by UPnP or NAT-PMP
     539             :     LOCAL_MANUAL, // address explicitly specified (-externalip=)
     540             : 
     541             :     LOCAL_MAX
     542             : };
     543             : 
     544             : bool IsPeerAddrLocalGood(CNode* pnode);
     545             : void AdvertiseLocal(CNode* pnode);
     546             : 
     547             : /**
     548             :  * Mark a network as reachable or unreachable (no automatic connects to it)
     549             :  * @note Networks are reachable by default
     550             :  */
     551             : void SetReachable(enum Network net, bool reachable);
     552             : /** @returns true if the network is reachable, false otherwise */
     553             : bool IsReachable(enum Network net);
     554             : /** @returns true if the address is in a reachable network, false otherwise */
     555             : bool IsReachable(const CNetAddr& addr);
     556             : 
     557             : bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
     558             : bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
     559             : bool RemoveLocal(const CService& addr);
     560             : bool SeenLocal(const CService& addr);
     561             : bool IsLocal(const CService& addr);
     562             : bool GetLocal(CService& addr, const CNetAddr* paddrPeer = nullptr);
     563             : CAddress GetLocalAddress(const CNetAddr* paddrPeer, ServiceFlags nLocalServices);
     564             : 
     565             : bool validateMasternodeIP(const std::string& addrStr);          // valid, reachable and routable address
     566             : 
     567             : 
     568             : extern bool fDiscover;
     569             : extern bool fListen;
     570             : 
     571             : extern limitedmap<CInv, int64_t> mapAlreadyAskedFor;
     572             : 
     573             : /** Subversion as sent to the P2P network in `version` messages */
     574             : extern std::string strSubVersion;
     575             : 
     576             : struct LocalServiceInfo {
     577             :     int nScore;
     578             :     int nPort;
     579             : };
     580             : 
     581             : extern RecursiveMutex cs_mapLocalHost;
     582             : extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
     583             : typedef std::map<std::string, uint64_t> mapMsgCmdSize; //command, total bytes
     584             : 
     585             : class CNodeStats
     586             : {
     587             : public:
     588             :     NodeId nodeid;
     589             :     ServiceFlags nServices;
     590             :     int64_t nLastSend;
     591             :     int64_t nLastRecv;
     592             :     int64_t nTimeConnected;
     593             :     int64_t nTimeOffset;
     594             :     std::string addrName;
     595             :     int nVersion;
     596             :     std::string cleanSubVer;
     597             :     bool fInbound;
     598             :     bool fAddnode;
     599             :     int nStartingHeight;
     600             :     uint64_t nSendBytes;
     601             :     mapMsgCmdSize mapSendBytesPerMsgCmd;
     602             :     uint64_t nRecvBytes;
     603             :     mapMsgCmdSize mapRecvBytesPerMsgCmd;
     604             :     bool fWhitelisted;
     605             :     double dPingTime;
     606             :     double dPingWait;
     607             :     std::string addrLocal;
     608             :     uint32_t m_mapped_as;
     609             :     // In case this is a MN-only connection.
     610             :     bool m_masternode_connection{false};
     611             :     // If 'true' this node will be disconnected after MNAUTH
     612             :     bool m_masternode_probe_connection{false};
     613             :     // If 'true', we identified it as an intra-quorum relay connection
     614             :     bool m_masternode_iqr_connection{false};
     615             :     // In case this is a verified MN, this value is the proTx of the MN
     616             :     uint256 verifiedProRegTxHash;
     617             :     // In case this is a verified MN, this value is the hashed operator pubkey of the MN
     618             :     uint256 verifiedPubKeyHash;
     619             : };
     620             : 
     621             : 
     622      379156 : class CNetMessage
     623             : {
     624             : private:
     625             :     mutable CHash256 hasher;
     626             :     mutable uint256 data_hash;
     627             : public:
     628             :     bool in_data; // parsing header (false) or data (true)
     629             : 
     630             :     CDataStream hdrbuf; // partially received header
     631             :     CMessageHeader hdr; // complete header
     632             :     unsigned int nHdrPos;
     633             : 
     634             :     CDataStream vRecv; // received message data
     635             :     unsigned int nDataPos;
     636             : 
     637             :     int64_t nTime; // time (in microseconds) of message receipt.
     638             : 
     639      758312 :     CNetMessage(const CMessageHeader::MessageStartChars& pchMessageStartIn, int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), hdr(pchMessageStartIn), vRecv(nTypeIn, nVersionIn) {
     640      379156 :         hdrbuf.resize(24);
     641      379156 :         in_data = false;
     642      379156 :         nHdrPos = 0;
     643      379156 :         nDataPos = 0;
     644      379156 :         nTime = 0;
     645      379156 :     }
     646             : 
     647     2029360 :     bool complete() const
     648             :     {
     649     2029360 :         if (!in_data)
     650             :             return false;
     651     2029360 :         return (hdr.nMessageSize == nDataPos);
     652             :     }
     653             : 
     654             :     const uint256& GetMessageHash() const;
     655             : 
     656      378830 :     void SetVersion(int nVersionIn)
     657             :     {
     658      378830 :         hdrbuf.SetVersion(nVersionIn);
     659      378830 :         vRecv.SetVersion(nVersionIn);
     660             :     }
     661             : 
     662             :     int readHeader(const char* pch, unsigned int nBytes);
     663             :     int readData(const char* pch, unsigned int nBytes);
     664             : };
     665             : 
     666             : 
     667             : /** Information about a peer */
     668             : class CNode
     669             : {
     670             :     friend class CConnman;
     671             : public:
     672             :     // socket
     673             :     std::atomic<ServiceFlags> nServices;
     674             :     ServiceFlags nServicesExpected;
     675             :     SOCKET hSocket;
     676             :     size_t nSendSize;   // total size of all vSendMsg entries
     677             :     size_t nSendOffset; // offset inside the first vSendMsg already sent
     678             :     uint64_t nSendBytes;
     679             :     std::deque<std::vector<unsigned char>> vSendMsg;
     680             :     RecursiveMutex cs_vSend;
     681             :     RecursiveMutex cs_hSocket;
     682             :     RecursiveMutex cs_vRecv;
     683             : 
     684             :     RecursiveMutex cs_vProcessMsg;
     685             :     std::list<CNetMessage> vProcessMsg;
     686             :     size_t nProcessQueueSize;
     687             : 
     688             :     RecursiveMutex cs_sendProcessing;
     689             : 
     690             :     std::deque<CInv> vRecvGetData;
     691             :     uint64_t nRecvBytes;
     692             :     std::atomic<int> nRecvVersion;
     693             : 
     694             :     std::atomic<int64_t> nLastSend;
     695             :     std::atomic<int64_t> nLastRecv;
     696             :     const int64_t nTimeConnected;
     697             :     std::atomic<int64_t> nTimeOffset;
     698             :     const CAddress addr;
     699             :     std::atomic<int> nVersion;
     700             :     // strSubVer is whatever byte array we read from the wire. However, this field is intended
     701             :     // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
     702             :     // store the sanitized version in cleanSubVer. The original should be used when dealing with
     703             :     // the network or wire types and the cleaned string used when displayed or logged.
     704             :     std::string strSubVer, cleanSubVer;
     705             :     RecursiveMutex cs_SubVer; // used for both cleanSubVer and strSubVer
     706             :     bool fWhitelisted; // This peer can bypass DoS banning.
     707             :     bool fFeeler;      // If true this node is being used as a short lived feeler.
     708             :     bool fOneShot;
     709             :     bool fAddnode;
     710             :     std::atomic<bool> m_masternode_connection{false}; // If true this node is only used for quorum related messages.
     711             :     std::atomic<bool> m_masternode_probe_connection{false}; // If true this will be disconnected right after the verack.
     712             :     std::atomic<bool> m_masternode_iqr_connection{false}; // If 'true', we identified it as an intra-quorum relay connection.
     713             :     std::atomic<int64_t> m_last_wants_recsigs_recv{0}; // the last time that a recsigs msg was received, used to avoid spam.
     714             :     bool fClient;
     715             :     const bool fInbound;
     716             :     /**
     717             :      * Whether the peer has signaled support for receiving ADDRv2 (BIP155)
     718             :      * messages, implying a preference to receive ADDRv2 instead of ADDR ones.
     719             :      */
     720             :     std::atomic_bool m_wants_addrv2{false};
     721             :     std::atomic_bool fSuccessfullyConnected;
     722             :     std::atomic_bool fDisconnect;
     723             :     // We use fRelayTxes for two purposes -
     724             :     // a) it allows us to not relay tx invs before receiving the peer's version message
     725             :     // b) the peer may tell us in their version message that we should not relay tx invs
     726             :     //    until they have initialized their bloom filter.
     727             :     bool fRelayTxes; //protected by cs_filter
     728             :     CSemaphoreGrant grantOutbound;
     729             :     RecursiveMutex cs_filter;
     730             :     std::unique_ptr<CBloomFilter> pfilter;
     731             :     std::atomic<int> nRefCount;
     732             : 
     733             :     const uint64_t nKeyedNetGroup;
     734             :     std::atomic_bool fPauseRecv;
     735             :     std::atomic_bool fPauseSend;
     736             : 
     737             :     // If true, we will announce/send him plain recovered sigs (usually true for full nodes)
     738             :     std::atomic<bool> m_wants_recsigs{false};
     739             :     // True when the first message after the verack is received
     740             :     std::atomic<bool> fFirstMessageReceived{false};
     741             :     // True only if the first message received after verack is a mnauth
     742             :     std::atomic<bool> fFirstMessageIsMNAUTH{false};
     743             : protected:
     744             :     mapMsgCmdSize mapSendBytesPerMsgCmd;
     745             :     mapMsgCmdSize mapRecvBytesPerMsgCmd;
     746             : 
     747             : public:
     748             :     uint256 hashContinue;
     749             :     std::atomic<int> nStartingHeight;
     750             : 
     751             :     // flood relay
     752             :     std::vector<CAddress> vAddrToSend;
     753             :     CRollingBloomFilter addrKnown;
     754             :     bool fGetAddr;
     755             :     std::set<uint256> setKnown;
     756             :     std::chrono::microseconds m_next_addr_send GUARDED_BY(cs_sendProcessing){0};
     757             :     std::chrono::microseconds m_next_local_addr_send GUARDED_BY(cs_sendProcessing){0};
     758             :     /** Number of addresses that can be processed from this peer. Start at 10 to
     759             :      *  permit self-announcement and starting peer propagation */
     760             :     double m_addr_token_bucket{10.0};
     761             :     /** When m_addr_token_bucket was last updated */
     762             :     std::chrono::microseconds m_addr_token_timestamp{GetTime<std::chrono::microseconds>()};
     763             : 
     764             :     // inventory based relay
     765             :     CRollingBloomFilter filterInventoryKnown;
     766             :     // Set of transaction ids we still have to announce.
     767             :     // They are sorted by the mempool before relay, so the order is not important.
     768             :     std::set<uint256> setInventoryTxToSend;
     769             :     // List of block ids we still have announce.
     770             :     // There is no final sorting before sending, as they are always sent immediately
     771             :     // and in the order requested.
     772             :     std::vector<uint256> vInventoryBlockToSend;
     773             :     // Set of tier two messages ids we still have to announce.
     774             :     std::vector<CInv> vInventoryTierTwoToSend;
     775             :     RecursiveMutex cs_inventory;
     776             :     std::multimap<int64_t, CInv> mapAskFor;
     777             :     std::set<uint256> setAskFor;
     778             :     std::vector<uint256> vBlockRequested;
     779             :     std::chrono::microseconds nNextInvSend{0};
     780             :     // Used for BIP35 mempool sending, also protected by cs_inventory
     781             :     bool fSendMempool;
     782             : 
     783             :     // Last time a "MEMPOOL" request was serviced.
     784             :     std::atomic<int64_t> timeLastMempoolReq{0};
     785             : 
     786             :     // Ping time measurement:
     787             :     // The pong reply we're expecting, or 0 if no pong expected.
     788             :     std::atomic<uint64_t> nPingNonceSent;
     789             :     // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
     790             :     std::atomic<int64_t> nPingUsecStart;
     791             :     // Last measured round-trip time.
     792             :     std::atomic<int64_t> nPingUsecTime;
     793             :     // Best measured round-trip time.
     794             :     std::atomic<int64_t> nMinPingUsecTime;
     795             :     // Whether a ping is requested.
     796             :     std::atomic<bool> fPingQueued;
     797             : 
     798             :     // Challenge sent in VERSION to be answered with MNAUTH (only happens between MNs)
     799             :     mutable Mutex cs_mnauth;
     800             :     uint256 sentMNAuthChallenge;
     801             :     uint256 receivedMNAuthChallenge;
     802             :     uint256 verifiedProRegTxHash; // MN provider register tx hash
     803             :     uint256 verifiedPubKeyHash; // MN operator pubkey hash
     804             : 
     805             :     CNode(NodeId id, ServiceFlags nLocalServicesIn, int nMyStartingHeightIn, SOCKET hSocketIn, const CAddress& addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const std::string& addrNameIn = "", bool fInboundIn = false);
     806             :     ~CNode();
     807             :     CNode(const CNode&) = delete;
     808             :     CNode& operator=(const CNode&) = delete;
     809             : 
     810             : private:
     811             :     const NodeId id;
     812             :     const uint64_t nLocalHostNonce;
     813             :     // Services offered to this peer
     814             :     const ServiceFlags nLocalServices;
     815             :     const int nMyStartingHeight;
     816             :     int nSendVersion;
     817             :     std::list<CNetMessage> vRecvMsg;  // Used only by SocketHandler thread
     818             : 
     819             :     mutable RecursiveMutex cs_addrName;
     820             :     std::string addrName;
     821             : 
     822             :     CService addrLocal;
     823             :     mutable RecursiveMutex cs_addrLocal;
     824             : public:
     825     9105380 :     NodeId GetId() const
     826             :     {
     827     9105380 :         return id;
     828             :     }
     829             : 
     830        1417 :     uint64_t GetLocalNonce() const {
     831        1417 :       return nLocalHostNonce;
     832             :     }
     833             : 
     834        1407 :     int GetMyStartingHeight() const {
     835        1407 :       return nMyStartingHeight;
     836             :     }
     837             : 
     838        1175 :     int GetRefCount()
     839             :     {
     840        1175 :         assert(nRefCount >= 0);
     841        1175 :         return nRefCount;
     842             :     }
     843             : 
     844             :     unsigned int GetTotalRecvSize()
     845             :     {
     846             :         unsigned int total = 0;
     847             :         for (const CNetMessage& msg : vRecvMsg)
     848             :             total += msg.vRecv.size() + 24;
     849             :         return total;
     850             :     }
     851             : 
     852             :     bool ReceiveMsgBytes(const char* pch, unsigned int nBytes, bool& complete);
     853             : 
     854        1358 :     void SetRecvVersion(int nVersionIn)
     855             :     {
     856        1358 :         nRecvVersion = nVersionIn;
     857             :     }
     858      378830 :     int GetRecvVersion()
     859             :     {
     860      378830 :         return nRecvVersion;
     861             :     }
     862             :     void SetSendVersion(int nVersionIn);
     863             :     int GetSendVersion() const;
     864             : 
     865             :     CService GetAddrLocal() const;
     866             :     //! May not be called more than once
     867             :     void SetAddrLocal(const CService& addrLocalIn);
     868             : 
     869    10762600 :     CNode* AddRef()
     870             :     {
     871    10762600 :         nRefCount++;
     872    10762600 :         return this;
     873             :     }
     874             : 
     875    10761800 :     void Release()
     876             :     {
     877    10761800 :         nRefCount--;
     878             :     }
     879             : 
     880             : 
     881         142 :     void AddAddressKnown(const CAddress& _addr)
     882             :     {
     883         142 :         addrKnown.insert(_addr.GetKey());
     884         142 :     }
     885             : 
     886          42 :     void PushAddress(const CAddress& _addr, FastRandomContext &insecure_rand)
     887             :     {
     888             :         // Whether the peer supports the address in `_addr`. For example,
     889             :         // nodes that do not implement BIP155 cannot receive Tor v3 addresses
     890             :         // because they require ADDRv2 (BIP155) encoding.
     891          42 :         const bool addr_format_supported = m_wants_addrv2 || _addr.IsAddrV1Compatible();
     892             : 
     893             :         // Known checking here is only to save space from duplicates.
     894             :         // SendMessages will filter it again for knowns that were added
     895             :         // after addresses were pushed.
     896          84 :         if (_addr.IsValid() && !addrKnown.contains(_addr.GetKey()) && addr_format_supported) {
     897          21 :             if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
     898           0 :                 vAddrToSend[insecure_rand.randrange(vAddrToSend.size())] = _addr;
     899             :             } else {
     900          21 :                 vAddrToSend.push_back(_addr);
     901             :             }
     902             :         }
     903          42 :     }
     904             : 
     905             : 
     906      349912 :     void AddInventoryKnown(const CInv& inv)
     907             :     {
     908      349912 :         {
     909      349912 :             LOCK(cs_inventory);
     910      349912 :             filterInventoryKnown.insert(inv.hash);
     911             :         }
     912      349912 :     }
     913             : 
     914      257875 :     void PushInventory(const CInv& inv)
     915             :     {
     916      257875 :         LOCK(cs_inventory);
     917      257875 :         if (inv.type == MSG_TX) {
     918       31079 :             if (!filterInventoryKnown.contains(inv.hash)) {
     919      279367 :                 setInventoryTxToSend.insert(inv.hash);
     920             :             }
     921      226796 :         } else if (inv.type == MSG_BLOCK) {
     922      188045 :             vInventoryBlockToSend.push_back(inv.hash);
     923             :         } else {
     924       38751 :             vInventoryTierTwoToSend.emplace_back(inv);
     925             :         }
     926      257875 :     }
     927             : 
     928             :     void AskFor(const CInv& inv, int64_t doubleRequestDelay = 2 * 60 * 1000000);
     929             :     // inv response received, clear it from the waiting inv set.
     930             :     void AskForInvReceived(const uint256& invHash);
     931             : 
     932             :     void CloseSocketDisconnect();
     933             :     bool DisconnectOldProtocol(int nVersionIn, int nVersionRequired);
     934             : 
     935             :     void copyStats(CNodeStats& stats, const std::vector<bool>& m_asmap);
     936             : 
     937       91725 :     ServiceFlags GetLocalServices() const
     938             :     {
     939       91725 :         return nLocalServices;
     940             :     }
     941             : 
     942             :     std::string GetAddrName() const;
     943             :     //! Sets the addrName only if it was not previously set
     944             :     void MaybeSetAddrName(const std::string& addrNameIn);
     945             : 
     946     2287376 :     bool CanRelay() const { return !m_masternode_connection || m_masternode_iqr_connection; }
     947             : };
     948             : 
     949             : class CExplicitNetCleanup
     950             : {
     951             : public:
     952             :     static void callCleanup();
     953             : };
     954             : 
     955             : /**
     956             :  * Interface for message handling
     957             :  */
     958         484 : class NetEventsInterface
     959             : {
     960             : public:
     961             :     virtual bool ProcessMessages(CNode* pnode, std::atomic<bool>& interrupt) = 0;
     962             :     virtual bool SendMessages(CNode* pnode, std::atomic<bool>& interrupt) EXCLUSIVE_LOCKS_REQUIRED(pnode->cs_sendProcessing) = 0;
     963             :     virtual void InitializeNode(CNode* pnode) = 0;
     964             :     virtual void FinalizeNode(NodeId id, bool& update_connection_time) = 0;
     965             : };
     966             : 
     967             : /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
     968             : int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds);
     969             : 
     970             : /** Wrapper to return mockable type */
     971       56639 : inline std::chrono::microseconds PoissonNextSend(std::chrono::microseconds now, std::chrono::seconds average_interval)
     972             : {
     973       56639 :     return std::chrono::microseconds{PoissonNextSend(now.count(), average_interval.count())};
     974             : }
     975             : 
     976             : #endif // PIVX_NET_H

Generated by: LCOV version 1.14