Branch data Line data Source code
# 1 : : // Copyright (c) 2009-2010 Satoshi Nakamoto
# 2 : : // Copyright (c) 2009-2020 The Bitcoin Core developers
# 3 : : // Distributed under the MIT software license, see the accompanying
# 4 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
# 5 : :
# 6 : : #ifndef BITCOIN_NET_H
# 7 : : #define BITCOIN_NET_H
# 8 : :
# 9 : : #include <addrdb.h>
# 10 : : #include <addrman.h>
# 11 : : #include <amount.h>
# 12 : : #include <bloom.h>
# 13 : : #include <chainparams.h>
# 14 : : #include <compat.h>
# 15 : : #include <crypto/siphash.h>
# 16 : : #include <hash.h>
# 17 : : #include <net_permissions.h>
# 18 : : #include <netaddress.h>
# 19 : : #include <optional.h>
# 20 : : #include <policy/feerate.h>
# 21 : : #include <protocol.h>
# 22 : : #include <random.h>
# 23 : : #include <streams.h>
# 24 : : #include <sync.h>
# 25 : : #include <threadinterrupt.h>
# 26 : : #include <uint256.h>
# 27 : :
# 28 : : #include <atomic>
# 29 : : #include <cstdint>
# 30 : : #include <deque>
# 31 : : #include <map>
# 32 : : #include <thread>
# 33 : : #include <memory>
# 34 : : #include <condition_variable>
# 35 : :
# 36 : : #ifndef WIN32
# 37 : : #include <arpa/inet.h>
# 38 : : #endif
# 39 : :
# 40 : :
# 41 : : class CScheduler;
# 42 : : class CNode;
# 43 : : class BanMan;
# 44 : : struct bilingual_str;
# 45 : :
# 46 : : /** Default for -whitelistrelay. */
# 47 : : static const bool DEFAULT_WHITELISTRELAY = true;
# 48 : : /** Default for -whitelistforcerelay. */
# 49 : : static const bool DEFAULT_WHITELISTFORCERELAY = false;
# 50 : :
# 51 : : /** Time after which to disconnect, after waiting for a ping response (or inactivity). */
# 52 : : static const int TIMEOUT_INTERVAL = 20 * 60;
# 53 : : /** Run the feeler connection loop once every 2 minutes or 120 seconds. **/
# 54 : : static const int FEELER_INTERVAL = 120;
# 55 : : /** The maximum number of addresses from our addrman to return in response to a getaddr message. */
# 56 : : static constexpr size_t MAX_ADDR_TO_SEND = 1000;
# 57 : : /** Maximum length of incoming protocol messages (no message over 4 MB is currently acceptable). */
# 58 : : static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
# 59 : : /** Maximum length of the user agent string in `version` message */
# 60 : : static const unsigned int MAX_SUBVERSION_LENGTH = 256;
# 61 : : /** Maximum number of automatic outgoing nodes over which we'll relay everything (blocks, tx, addrs, etc) */
# 62 : : static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS = 8;
# 63 : : /** Maximum number of addnode outgoing nodes */
# 64 : : static const int MAX_ADDNODE_CONNECTIONS = 8;
# 65 : : /** Maximum number of block-relay-only outgoing connections */
# 66 : : static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS = 2;
# 67 : : /** Maximum number of feeler connections */
# 68 : : static const int MAX_FEELER_CONNECTIONS = 1;
# 69 : : /** -listen default */
# 70 : : static const bool DEFAULT_LISTEN = true;
# 71 : : /** -upnp default */
# 72 : : #ifdef USE_UPNP
# 73 : : static const bool DEFAULT_UPNP = USE_UPNP;
# 74 : : #else
# 75 : : static const bool DEFAULT_UPNP = false;
# 76 : : #endif
# 77 : : /** The maximum number of peer connections to maintain. */
# 78 : : static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
# 79 : : /** The default for -maxuploadtarget. 0 = Unlimited */
# 80 : : static const uint64_t DEFAULT_MAX_UPLOAD_TARGET = 0;
# 81 : : /** The default timeframe for -maxuploadtarget. 1 day. */
# 82 : : static const uint64_t MAX_UPLOAD_TIMEFRAME = 60 * 60 * 24;
# 83 : : /** Default for blocks only*/
# 84 : : static const bool DEFAULT_BLOCKSONLY = false;
# 85 : : /** -peertimeout default */
# 86 : : static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
# 87 : :
# 88 : : static const bool DEFAULT_FORCEDNSSEED = false;
# 89 : : static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
# 90 : : static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
# 91 : :
# 92 : : typedef int64_t NodeId;
# 93 : :
# 94 : : struct AddedNodeInfo
# 95 : : {
# 96 : : std::string strAddedNode;
# 97 : : CService resolvedAddress;
# 98 : : bool fConnected;
# 99 : : bool fInbound;
# 100 : : };
# 101 : :
# 102 : : class CNodeStats;
# 103 : : class CClientUIInterface;
# 104 : :
# 105 : : struct CSerializedNetMsg
# 106 : : {
# 107 : 88624 : CSerializedNetMsg() = default;
# 108 : : CSerializedNetMsg(CSerializedNetMsg&&) = default;
# 109 : : CSerializedNetMsg& operator=(CSerializedNetMsg&&) = default;
# 110 : : // No copying, only moves.
# 111 : : CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
# 112 : : CSerializedNetMsg& operator=(const CSerializedNetMsg&) = delete;
# 113 : :
# 114 : : std::vector<unsigned char> data;
# 115 : : std::string m_type;
# 116 : : };
# 117 : :
# 118 : : const std::vector<std::string> CONNECTION_TYPE_DOC{
# 119 : : "outbound-full-relay (default automatic connections)",
# 120 : : "block-relay-only (does not relay transactions or addresses)",
# 121 : : "inbound (initiated by the peer)",
# 122 : : "manual (added via addnode RPC or -addnode/-connect configuration options)",
# 123 : : "addr-fetch (short-lived automatic connection for soliciting addresses)",
# 124 : : "feeler (short-lived automatic connection for testing addresses)"};
# 125 : :
# 126 : : /** Different types of connections to a peer. This enum encapsulates the
# 127 : : * information we have available at the time of opening or accepting the
# 128 : : * connection. Aside from INBOUND, all types are initiated by us. */
# 129 : : enum class ConnectionType {
# 130 : : /**
# 131 : : * Inbound connections are those initiated by a peer. This is the only
# 132 : : * property we know at the time of connection, until P2P messages are
# 133 : : * exchanged.
# 134 : : */
# 135 : : INBOUND,
# 136 : :
# 137 : : /**
# 138 : : * These are the default connections that we use to connect with the
# 139 : : * network. There is no restriction on what is relayed- by default we relay
# 140 : : * blocks, addresses & transactions. We automatically attempt to open
# 141 : : * MAX_OUTBOUND_FULL_RELAY_CONNECTIONS using addresses from our AddrMan.
# 142 : : */
# 143 : : OUTBOUND_FULL_RELAY,
# 144 : :
# 145 : :
# 146 : : /**
# 147 : : * We open manual connections to addresses that users explicitly inputted
# 148 : : * via the addnode RPC, or the -connect command line argument. Even if a
# 149 : : * manual connection is misbehaving, we do not automatically disconnect or
# 150 : : * add it to our discouragement filter.
# 151 : : */
# 152 : : MANUAL,
# 153 : :
# 154 : : /**
# 155 : : * Feeler connections are short-lived connections made to check that a node
# 156 : : * is alive. They can be useful for:
# 157 : : * - test-before-evict: if one of the peers is considered for eviction from
# 158 : : * our AddrMan because another peer is mapped to the same slot in the tried table,
# 159 : : * evict only if this longer-known peer is offline.
# 160 : : * - move node addresses from New to Tried table, so that we have more
# 161 : : * connectable addresses in our AddrMan.
# 162 : : * Note that in the literature ("Eclipse Attacks on Bitcoin’s Peer-to-Peer Network")
# 163 : : * only the latter feature is referred to as "feeler connections",
# 164 : : * although in our codebase feeler connections encompass test-before-evict as well.
# 165 : : * We make these connections approximately every FEELER_INTERVAL:
# 166 : : * first we resolve previously found collisions if they exist (test-before-evict),
# 167 : : * otherwise connect to a node from the new table.
# 168 : : */
# 169 : : FEELER,
# 170 : :
# 171 : : /**
# 172 : : * We use block-relay-only connections to help prevent against partition
# 173 : : * attacks. By not relaying transactions or addresses, these connections
# 174 : : * are harder to detect by a third party, thus helping obfuscate the
# 175 : : * network topology. We automatically attempt to open
# 176 : : * MAX_BLOCK_RELAY_ONLY_CONNECTIONS using addresses from our AddrMan.
# 177 : : */
# 178 : : BLOCK_RELAY,
# 179 : :
# 180 : : /**
# 181 : : * AddrFetch connections are short lived connections used to solicit
# 182 : : * addresses from peers. These are initiated to addresses submitted via the
# 183 : : * -seednode command line argument, or under certain conditions when the
# 184 : : * AddrMan is empty.
# 185 : : */
# 186 : : ADDR_FETCH,
# 187 : : };
# 188 : :
# 189 : : class NetEventsInterface;
# 190 : : class CConnman
# 191 : : {
# 192 : : public:
# 193 : :
# 194 : : enum NumConnections {
# 195 : : CONNECTIONS_NONE = 0,
# 196 : : CONNECTIONS_IN = (1U << 0),
# 197 : : CONNECTIONS_OUT = (1U << 1),
# 198 : : CONNECTIONS_ALL = (CONNECTIONS_IN | CONNECTIONS_OUT),
# 199 : : };
# 200 : :
# 201 : : struct Options
# 202 : : {
# 203 : : ServiceFlags nLocalServices = NODE_NONE;
# 204 : : int nMaxConnections = 0;
# 205 : : int m_max_outbound_full_relay = 0;
# 206 : : int m_max_outbound_block_relay = 0;
# 207 : : int nMaxAddnode = 0;
# 208 : : int nMaxFeeler = 0;
# 209 : : int nBestHeight = 0;
# 210 : : CClientUIInterface* uiInterface = nullptr;
# 211 : : NetEventsInterface* m_msgproc = nullptr;
# 212 : : BanMan* m_banman = nullptr;
# 213 : : unsigned int nSendBufferMaxSize = 0;
# 214 : : unsigned int nReceiveFloodSize = 0;
# 215 : : uint64_t nMaxOutboundTimeframe = 0;
# 216 : : uint64_t nMaxOutboundLimit = 0;
# 217 : : int64_t m_peer_connect_timeout = DEFAULT_PEER_CONNECT_TIMEOUT;
# 218 : : std::vector<std::string> vSeedNodes;
# 219 : : std::vector<NetWhitelistPermissions> vWhitelistedRange;
# 220 : : std::vector<NetWhitebindPermissions> vWhiteBinds;
# 221 : : std::vector<CService> vBinds;
# 222 : : std::vector<CService> onion_binds;
# 223 : : bool m_use_addrman_outgoing = true;
# 224 : : std::vector<std::string> m_specified_outgoing;
# 225 : : std::vector<std::string> m_added_nodes;
# 226 : : std::vector<bool> m_asmap;
# 227 : : };
# 228 : :
# 229 : 1339 : void Init(const Options& connOptions) {
# 230 : 1339 : nLocalServices = connOptions.nLocalServices;
# 231 : 1339 : nMaxConnections = connOptions.nMaxConnections;
# 232 : 1339 : m_max_outbound_full_relay = std::min(connOptions.m_max_outbound_full_relay, connOptions.nMaxConnections);
# 233 : 1339 : m_max_outbound_block_relay = connOptions.m_max_outbound_block_relay;
# 234 : 1339 : m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
# 235 : 1339 : nMaxAddnode = connOptions.nMaxAddnode;
# 236 : 1339 : nMaxFeeler = connOptions.nMaxFeeler;
# 237 : 1339 : m_max_outbound = m_max_outbound_full_relay + m_max_outbound_block_relay + nMaxFeeler;
# 238 : 1339 : nBestHeight = connOptions.nBestHeight;
# 239 : 1339 : clientInterface = connOptions.uiInterface;
# 240 : 1339 : m_banman = connOptions.m_banman;
# 241 : 1339 : m_msgproc = connOptions.m_msgproc;
# 242 : 1339 : nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
# 243 : 1339 : nReceiveFloodSize = connOptions.nReceiveFloodSize;
# 244 : 1339 : m_peer_connect_timeout = connOptions.m_peer_connect_timeout;
# 245 : 1339 : {
# 246 : 1339 : LOCK(cs_totalBytesSent);
# 247 : 1339 : nMaxOutboundTimeframe = connOptions.nMaxOutboundTimeframe;
# 248 : 1339 : nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
# 249 : 1339 : }
# 250 : 1339 : vWhitelistedRange = connOptions.vWhitelistedRange;
# 251 : 1339 : {
# 252 : 1339 : LOCK(cs_vAddedNodes);
# 253 : 1339 : vAddedNodes = connOptions.m_added_nodes;
# 254 : 1339 : }
# 255 : 1339 : }
# 256 : :
# 257 : : CConnman(uint64_t seed0, uint64_t seed1, bool network_active = true);
# 258 : : ~CConnman();
# 259 : : bool Start(CScheduler& scheduler, const Options& options);
# 260 : :
# 261 : : void StopThreads();
# 262 : : void StopNodes();
# 263 : : void Stop()
# 264 : 680 : {
# 265 : 680 : StopThreads();
# 266 : 680 : StopNodes();
# 267 : 680 : };
# 268 : :
# 269 : : void Interrupt();
# 270 : 100 : bool GetNetworkActive() const { return fNetworkActive; };
# 271 : 46 : bool GetUseAddrmanOutgoing() const { return m_use_addrman_outgoing; };
# 272 : : void SetNetworkActive(bool active);
# 273 : : void OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant* grantOutbound, const char* strDest, ConnectionType conn_type);
# 274 : : bool CheckIncomingNonce(uint64_t nonce);
# 275 : :
# 276 : : bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
# 277 : :
# 278 : : void PushMessage(CNode* pnode, CSerializedNetMsg&& msg);
# 279 : :
# 280 : : using NodeFn = std::function<void(CNode*)>;
# 281 : : void ForEachNode(const NodeFn& func)
# 282 : 69039 : {
# 283 : 69039 : LOCK(cs_vNodes);
# 284 : 95391 : for (auto&& node : vNodes) {
# 285 : 95391 : if (NodeFullyConnected(node))
# 286 : 95353 : func(node);
# 287 : 95391 : }
# 288 : 69039 : };
# 289 : :
# 290 : : void ForEachNode(const NodeFn& func) const
# 291 : 17036 : {
# 292 : 17036 : LOCK(cs_vNodes);
# 293 : 28509 : for (auto&& node : vNodes) {
# 294 : 28509 : if (NodeFullyConnected(node))
# 295 : 28508 : func(node);
# 296 : 28509 : }
# 297 : 17036 : };
# 298 : :
# 299 : : template<typename Callable, typename CallableAfter>
# 300 : : void ForEachNodeThen(Callable&& pre, CallableAfter&& post)
# 301 : : {
# 302 : : LOCK(cs_vNodes);
# 303 : : for (auto&& node : vNodes) {
# 304 : : if (NodeFullyConnected(node))
# 305 : : pre(node);
# 306 : : }
# 307 : : post();
# 308 : : };
# 309 : :
# 310 : : template<typename Callable, typename CallableAfter>
# 311 : : void ForEachNodeThen(Callable&& pre, CallableAfter&& post) const
# 312 : 10 : {
# 313 : 10 : LOCK(cs_vNodes);
# 314 : 20 : for (auto&& node : vNodes) {
# 315 : 20 : if (NodeFullyConnected(node))
# 316 : 20 : pre(node);
# 317 : 20 : }
# 318 : 10 : post();
# 319 : 10 : };
# 320 : :
# 321 : : // Addrman functions
# 322 : : void SetServices(const CService &addr, ServiceFlags nServices);
# 323 : : void MarkAddressGood(const CAddress& addr);
# 324 : : bool AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
# 325 : : std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct);
# 326 : : /**
# 327 : : * Cache is used to minimize topology leaks, so it should
# 328 : : * be used for all non-trusted calls, for example, p2p.
# 329 : : * A non-malicious call (from RPC or a peer with addr permission) should
# 330 : : * call the function without a parameter to avoid using the cache.
# 331 : : */
# 332 : : std::vector<CAddress> GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct);
# 333 : :
# 334 : : // This allows temporarily exceeding m_max_outbound_full_relay, with the goal of finding
# 335 : : // a peer that is better than all our current peers.
# 336 : : void SetTryNewOutboundPeer(bool flag);
# 337 : : bool GetTryNewOutboundPeer();
# 338 : :
# 339 : : // Return the number of outbound peers we have in excess of our target (eg,
# 340 : : // if we previously called SetTryNewOutboundPeer(true), and have since set
# 341 : : // to false, we may have extra peers that we wish to disconnect). This may
# 342 : : // return a value less than (num_outbound_connections - num_outbound_slots)
# 343 : : // in cases where some outbound connections are not yet fully connected, or
# 344 : : // not yet fully disconnected.
# 345 : : int GetExtraOutboundCount();
# 346 : :
# 347 : : bool AddNode(const std::string& node);
# 348 : : bool RemoveAddedNode(const std::string& node);
# 349 : : std::vector<AddedNodeInfo> GetAddedNodeInfo();
# 350 : :
# 351 : : size_t GetNodeCount(NumConnections num);
# 352 : : void GetNodeStats(std::vector<CNodeStats>& vstats);
# 353 : : bool DisconnectNode(const std::string& node);
# 354 : : bool DisconnectNode(const CSubNet& subnet);
# 355 : : bool DisconnectNode(const CNetAddr& addr);
# 356 : : bool DisconnectNode(NodeId id);
# 357 : :
# 358 : : //! Used to convey which local services we are offering peers during node
# 359 : : //! connection.
# 360 : : //!
# 361 : : //! The data returned by this is used in CNode construction,
# 362 : : //! which is used to advertise which services we are offering
# 363 : : //! that peer during `net_processing.cpp:PushNodeVersion()`.
# 364 : : ServiceFlags GetLocalServices() const;
# 365 : :
# 366 : : //!set the max outbound target in bytes
# 367 : : void SetMaxOutboundTarget(uint64_t limit);
# 368 : : uint64_t GetMaxOutboundTarget();
# 369 : :
# 370 : : //!set the timeframe for the max outbound target
# 371 : : void SetMaxOutboundTimeframe(uint64_t timeframe);
# 372 : : uint64_t GetMaxOutboundTimeframe();
# 373 : :
# 374 : : //! check if the outbound target is reached
# 375 : : //! if param historicalBlockServingLimit is set true, the function will
# 376 : : //! response true if the limit for serving historical blocks has been reached
# 377 : : bool OutboundTargetReached(bool historicalBlockServingLimit);
# 378 : :
# 379 : : //! response the bytes left in the current max outbound cycle
# 380 : : //! in case of no limit, it will always response 0
# 381 : : uint64_t GetOutboundTargetBytesLeft();
# 382 : :
# 383 : : //! response the time in second left in the current max outbound cycle
# 384 : : //! in case of no limit, it will always response 0
# 385 : : uint64_t GetMaxOutboundTimeLeftInCycle();
# 386 : :
# 387 : : uint64_t GetTotalBytesRecv();
# 388 : : uint64_t GetTotalBytesSent();
# 389 : :
# 390 : : void SetBestHeight(int height);
# 391 : : int GetBestHeight() const;
# 392 : :
# 393 : : /** Get a unique deterministic randomizer. */
# 394 : : CSipHasher GetDeterministicRandomizer(uint64_t id) const;
# 395 : :
# 396 : : unsigned int GetReceiveFloodSize() const;
# 397 : :
# 398 : : void WakeMessageHandler();
# 399 : :
# 400 : : /** Attempts to obfuscate tx time through exponentially distributed emitting.
# 401 : : Works assuming that a single interval is used.
# 402 : : Variable intervals will result in privacy decrease.
# 403 : : */
# 404 : : int64_t PoissonNextSendInbound(int64_t now, int average_interval_seconds);
# 405 : :
# 406 : 4 : void SetAsmap(std::vector<bool> asmap) { addrman.m_asmap = std::move(asmap); }
# 407 : :
# 408 : : private:
# 409 : : struct ListenSocket {
# 410 : : public:
# 411 : : SOCKET socket;
# 412 : 535 : inline void AddSocketPermissionFlags(NetPermissionFlags& flags) const { NetPermissions::AddFlag(flags, m_permissions); }
# 413 : 584 : ListenSocket(SOCKET socket_, NetPermissionFlags permissions_) : socket(socket_), m_permissions(permissions_) {}
# 414 : : private:
# 415 : : NetPermissionFlags m_permissions;
# 416 : : };
# 417 : :
# 418 : : bool BindListenPort(const CService& bindAddr, bilingual_str& strError, NetPermissionFlags permissions);
# 419 : : bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions);
# 420 : : bool InitBinds(
# 421 : : const std::vector<CService>& binds,
# 422 : : const std::vector<NetWhitebindPermissions>& whiteBinds,
# 423 : : const std::vector<CService>& onion_binds);
# 424 : :
# 425 : : void ThreadOpenAddedConnections();
# 426 : : void AddAddrFetch(const std::string& strDest);
# 427 : : void ProcessAddrFetch();
# 428 : : void ThreadOpenConnections(std::vector<std::string> connect);
# 429 : : void ThreadMessageHandler();
# 430 : : void AcceptConnection(const ListenSocket& hListenSocket);
# 431 : : void DisconnectNodes();
# 432 : : void NotifyNumConnectionsChanged();
# 433 : : void InactivityCheck(CNode *pnode);
# 434 : : bool GenerateSelectSet(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set);
# 435 : : void SocketEvents(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set);
# 436 : : void SocketHandler();
# 437 : : void ThreadSocketHandler();
# 438 : : void ThreadDNSAddressSeed();
# 439 : :
# 440 : : uint64_t CalculateKeyedNetGroup(const CAddress& ad) const;
# 441 : :
# 442 : : CNode* FindNode(const CNetAddr& ip);
# 443 : : CNode* FindNode(const CSubNet& subNet);
# 444 : : CNode* FindNode(const std::string& addrName);
# 445 : : CNode* FindNode(const CService& addr);
# 446 : :
# 447 : : bool AttemptToEvictConnection();
# 448 : : CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type);
# 449 : : void AddWhitelistPermissionFlags(NetPermissionFlags& flags, const CNetAddr &addr) const;
# 450 : :
# 451 : : void DeleteNode(CNode* pnode);
# 452 : :
# 453 : : NodeId GetNewNodeId();
# 454 : :
# 455 : : size_t SocketSendData(CNode *pnode) const;
# 456 : : void DumpAddresses();
# 457 : :
# 458 : : // Network stats
# 459 : : void RecordBytesRecv(uint64_t bytes);
# 460 : : void RecordBytesSent(uint64_t bytes);
# 461 : :
# 462 : : // Whether the node should be passed out in ForEach* callbacks
# 463 : : static bool NodeFullyConnected(const CNode* pnode);
# 464 : :
# 465 : : // Network usage totals
# 466 : : RecursiveMutex cs_totalBytesRecv;
# 467 : : RecursiveMutex cs_totalBytesSent;
# 468 : : uint64_t nTotalBytesRecv GUARDED_BY(cs_totalBytesRecv) {0};
# 469 : : uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent) {0};
# 470 : :
# 471 : : // outbound limit & stats
# 472 : : uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent);
# 473 : : uint64_t nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent);
# 474 : : uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent);
# 475 : : uint64_t nMaxOutboundTimeframe GUARDED_BY(cs_totalBytesSent);
# 476 : :
# 477 : : // P2P timeout in seconds
# 478 : : int64_t m_peer_connect_timeout;
# 479 : :
# 480 : : // Whitelisted ranges. Any node connecting from these is automatically
# 481 : : // whitelisted (as well as those connecting to whitelisted binds).
# 482 : : std::vector<NetWhitelistPermissions> vWhitelistedRange;
# 483 : :
# 484 : : unsigned int nSendBufferMaxSize{0};
# 485 : : unsigned int nReceiveFloodSize{0};
# 486 : :
# 487 : : std::vector<ListenSocket> vhListenSocket;
# 488 : : std::atomic<bool> fNetworkActive{true};
# 489 : : bool fAddressesInitialized{false};
# 490 : : CAddrMan addrman;
# 491 : : std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
# 492 : : RecursiveMutex m_addr_fetches_mutex;
# 493 : : std::vector<std::string> vAddedNodes GUARDED_BY(cs_vAddedNodes);
# 494 : : RecursiveMutex cs_vAddedNodes;
# 495 : : std::vector<CNode*> vNodes GUARDED_BY(cs_vNodes);
# 496 : : std::list<CNode*> vNodesDisconnected;
# 497 : : mutable RecursiveMutex cs_vNodes;
# 498 : : std::atomic<NodeId> nLastNodeId{0};
# 499 : : unsigned int nPrevNodeCount{0};
# 500 : :
# 501 : : /**
# 502 : : * Cache responses to addr requests to minimize privacy leak.
# 503 : : * Attack example: scraping addrs in real-time may allow an attacker
# 504 : : * to infer new connections of the victim by detecting new records
# 505 : : * with fresh timestamps (per self-announcement).
# 506 : : */
# 507 : : struct CachedAddrResponse {
# 508 : : std::vector<CAddress> m_addrs_response_cache;
# 509 : : std::chrono::microseconds m_cache_entry_expiration{0};
# 510 : : };
# 511 : :
# 512 : : /**
# 513 : : * Addr responses stored in different caches
# 514 : : * per (network, local socket) prevent cross-network node identification.
# 515 : : * If a node for example is multi-homed under Tor and IPv6,
# 516 : : * a single cache (or no cache at all) would let an attacker
# 517 : : * to easily detect that it is the same node by comparing responses.
# 518 : : * Indexing by local socket prevents leakage when a node has multiple
# 519 : : * listening addresses on the same network.
# 520 : : *
# 521 : : * The used memory equals to 1000 CAddress records (or around 40 bytes) per
# 522 : : * distinct Network (up to 5) we have/had an inbound peer from,
# 523 : : * resulting in at most ~196 KB. Every separate local socket may
# 524 : : * add up to ~196 KB extra.
# 525 : : */
# 526 : : std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
# 527 : :
# 528 : : /**
# 529 : : * Services this instance offers.
# 530 : : *
# 531 : : * This data is replicated in each CNode instance we create during peer
# 532 : : * connection (in ConnectNode()) under a member also called
# 533 : : * nLocalServices.
# 534 : : *
# 535 : : * This data is not marked const, but after being set it should not
# 536 : : * change. See the note in CNode::nLocalServices documentation.
# 537 : : *
# 538 : : * \sa CNode::nLocalServices
# 539 : : */
# 540 : : ServiceFlags nLocalServices;
# 541 : :
# 542 : : std::unique_ptr<CSemaphore> semOutbound;
# 543 : : std::unique_ptr<CSemaphore> semAddnode;
# 544 : : int nMaxConnections;
# 545 : :
# 546 : : // How many full-relay (tx, block, addr) outbound peers we want
# 547 : : int m_max_outbound_full_relay;
# 548 : :
# 549 : : // How many block-relay only outbound peers we want
# 550 : : // We do not relay tx or addr messages with these peers
# 551 : : int m_max_outbound_block_relay;
# 552 : :
# 553 : : int nMaxAddnode;
# 554 : : int nMaxFeeler;
# 555 : : int m_max_outbound;
# 556 : : bool m_use_addrman_outgoing;
# 557 : : std::atomic<int> nBestHeight;
# 558 : : CClientUIInterface* clientInterface;
# 559 : : NetEventsInterface* m_msgproc;
# 560 : : /** Pointer to this node's banman. May be nullptr - check existence before dereferencing. */
# 561 : : BanMan* m_banman;
# 562 : :
# 563 : : /** SipHasher seeds for deterministic randomness */
# 564 : : const uint64_t nSeed0, nSeed1;
# 565 : :
# 566 : : /** flag for waking the message processor. */
# 567 : : bool fMsgProcWake GUARDED_BY(mutexMsgProc);
# 568 : :
# 569 : : std::condition_variable condMsgProc;
# 570 : : Mutex mutexMsgProc;
# 571 : : std::atomic<bool> flagInterruptMsgProc{false};
# 572 : :
# 573 : : CThreadInterrupt interruptNet;
# 574 : :
# 575 : : std::thread threadDNSAddressSeed;
# 576 : : std::thread threadSocketHandler;
# 577 : : std::thread threadOpenAddedConnections;
# 578 : : std::thread threadOpenConnections;
# 579 : : std::thread threadMessageHandler;
# 580 : :
# 581 : : /** flag for deciding to connect to an extra outbound peer,
# 582 : : * in excess of m_max_outbound_full_relay
# 583 : : * This takes the place of a feeler connection */
# 584 : : std::atomic_bool m_try_another_outbound_peer;
# 585 : :
# 586 : : std::atomic<int64_t> m_next_send_inv_to_incoming{0};
# 587 : :
# 588 : : friend struct CConnmanTest;
# 589 : : friend struct ConnmanTestMsg;
# 590 : : };
# 591 : : void Discover();
# 592 : : void StartMapPort();
# 593 : : void InterruptMapPort();
# 594 : : void StopMapPort();
# 595 : : uint16_t GetListenPort();
# 596 : :
# 597 : : struct CombinerAll
# 598 : : {
# 599 : : typedef bool result_type;
# 600 : :
# 601 : : template<typename I>
# 602 : : bool operator()(I first, I last) const
# 603 : 10 : {
# 604 : 12 : while (first != last) {
# 605 : 6 : if (!(*first)) return false;
# 606 : 2 : ++first;
# 607 : 2 : }
# 608 : 6 : return true;
# 609 : 10 : }
# 610 : : };
# 611 : :
# 612 : : /**
# 613 : : * Interface for message handling
# 614 : : */
# 615 : : class NetEventsInterface
# 616 : : {
# 617 : : public:
# 618 : : virtual bool ProcessMessages(CNode* pnode, std::atomic<bool>& interrupt) = 0;
# 619 : : virtual bool SendMessages(CNode* pnode) = 0;
# 620 : : virtual void InitializeNode(CNode* pnode) = 0;
# 621 : : virtual void FinalizeNode(NodeId id, bool& update_connection_time) = 0;
# 622 : :
# 623 : : protected:
# 624 : : /**
# 625 : : * Protected destructor so that instances can only be deleted by derived classes.
# 626 : : * If that restriction is no longer desired, this should be made public and virtual.
# 627 : : */
# 628 : : ~NetEventsInterface() = default;
# 629 : : };
# 630 : :
# 631 : : enum
# 632 : : {
# 633 : : LOCAL_NONE, // unknown
# 634 : : LOCAL_IF, // address a local interface listens on
# 635 : : LOCAL_BIND, // address explicit bound to
# 636 : : LOCAL_UPNP, // address reported by UPnP
# 637 : : LOCAL_MANUAL, // address explicitly specified (-externalip=)
# 638 : :
# 639 : : LOCAL_MAX
# 640 : : };
# 641 : :
# 642 : : bool IsPeerAddrLocalGood(CNode *pnode);
# 643 : : void AdvertiseLocal(CNode *pnode);
# 644 : :
# 645 : : /**
# 646 : : * Mark a network as reachable or unreachable (no automatic connects to it)
# 647 : : * @note Networks are reachable by default
# 648 : : */
# 649 : : void SetReachable(enum Network net, bool reachable);
# 650 : : /** @returns true if the network is reachable, false otherwise */
# 651 : : bool IsReachable(enum Network net);
# 652 : : /** @returns true if the address is in a reachable network, false otherwise */
# 653 : : bool IsReachable(const CNetAddr& addr);
# 654 : :
# 655 : : bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
# 656 : : bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
# 657 : : void RemoveLocal(const CService& addr);
# 658 : : bool SeenLocal(const CService& addr);
# 659 : : bool IsLocal(const CService& addr);
# 660 : : bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr);
# 661 : : CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices);
# 662 : :
# 663 : :
# 664 : : extern bool fDiscover;
# 665 : : extern bool fListen;
# 666 : : extern bool g_relay_txes;
# 667 : :
# 668 : : /** Subversion as sent to the P2P network in `version` messages */
# 669 : : extern std::string strSubVersion;
# 670 : :
# 671 : : struct LocalServiceInfo {
# 672 : : int nScore;
# 673 : : int nPort;
# 674 : : };
# 675 : :
# 676 : : extern RecursiveMutex cs_mapLocalHost;
# 677 : : extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(cs_mapLocalHost);
# 678 : :
# 679 : : extern const std::string NET_MESSAGE_COMMAND_OTHER;
# 680 : : typedef std::map<std::string, uint64_t> mapMsgCmdSize; //command, total bytes
# 681 : :
# 682 : : class CNodeStats
# 683 : : {
# 684 : : public:
# 685 : : NodeId nodeid;
# 686 : : ServiceFlags nServices;
# 687 : : bool fRelayTxes;
# 688 : : int64_t nLastSend;
# 689 : : int64_t nLastRecv;
# 690 : : int64_t nLastTXTime;
# 691 : : int64_t nLastBlockTime;
# 692 : : int64_t nTimeConnected;
# 693 : : int64_t nTimeOffset;
# 694 : : std::string addrName;
# 695 : : int nVersion;
# 696 : : std::string cleanSubVer;
# 697 : : bool fInbound;
# 698 : : bool m_manual_connection;
# 699 : : int nStartingHeight;
# 700 : : uint64_t nSendBytes;
# 701 : : mapMsgCmdSize mapSendBytesPerMsgCmd;
# 702 : : uint64_t nRecvBytes;
# 703 : : mapMsgCmdSize mapRecvBytesPerMsgCmd;
# 704 : : NetPermissionFlags m_permissionFlags;
# 705 : : bool m_legacyWhitelisted;
# 706 : : int64_t m_ping_usec;
# 707 : : int64_t m_ping_wait_usec;
# 708 : : int64_t m_min_ping_usec;
# 709 : : CAmount minFeeFilter;
# 710 : : // Our address, as reported by the peer
# 711 : : std::string addrLocal;
# 712 : : // Address of this peer
# 713 : : CAddress addr;
# 714 : : // Bind address of our side of the connection
# 715 : : CAddress addrBind;
# 716 : : uint32_t m_mapped_as;
# 717 : : std::string m_conn_type_string;
# 718 : : };
# 719 : :
# 720 : :
# 721 : :
# 722 : : /** Transport protocol agnostic message container.
# 723 : : * Ideally it should only contain receive time, payload,
# 724 : : * command and size.
# 725 : : */
# 726 : : class CNetMessage {
# 727 : : public:
# 728 : : CDataStream m_recv; //!< received message data
# 729 : : std::chrono::microseconds m_time{0}; //!< time of message receipt
# 730 : : uint32_t m_message_size{0}; //!< size of the payload
# 731 : : uint32_t m_raw_message_size{0}; //!< used wire size of the message (including header/checksum)
# 732 : : std::string m_command;
# 733 : :
# 734 : 83737 : CNetMessage(CDataStream&& recv_in) : m_recv(std::move(recv_in)) {}
# 735 : :
# 736 : : void SetVersion(int nVersionIn)
# 737 : 79518 : {
# 738 : 79518 : m_recv.SetVersion(nVersionIn);
# 739 : 79518 : }
# 740 : : };
# 741 : :
# 742 : : /** The TransportDeserializer takes care of holding and deserializing the
# 743 : : * network receive buffer. It can deserialize the network buffer into a
# 744 : : * transport protocol agnostic CNetMessage (command & payload)
# 745 : : */
# 746 : : class TransportDeserializer {
# 747 : : public:
# 748 : : // returns true if the current deserialization is complete
# 749 : : virtual bool Complete() const = 0;
# 750 : : // set the serialization context version
# 751 : : virtual void SetVersion(int version) = 0;
# 752 : : // read and deserialize data
# 753 : : virtual int Read(const char *data, unsigned int bytes) = 0;
# 754 : : // decomposes a message from the context
# 755 : : virtual Optional<CNetMessage> GetMessage(std::chrono::microseconds time, uint32_t& out_err) = 0;
# 756 : 1650 : virtual ~TransportDeserializer() {}
# 757 : : };
# 758 : :
# 759 : : class V1TransportDeserializer final : public TransportDeserializer
# 760 : : {
# 761 : : private:
# 762 : : const CChainParams& m_chain_params;
# 763 : : const NodeId m_node_id; // Only for logging
# 764 : : mutable CHash256 hasher;
# 765 : : mutable uint256 data_hash;
# 766 : : bool in_data; // parsing header (false) or data (true)
# 767 : : CDataStream hdrbuf; // partially received header
# 768 : : CMessageHeader hdr; // complete header
# 769 : : CDataStream vRecv; // received message data
# 770 : : unsigned int nHdrPos;
# 771 : : unsigned int nDataPos;
# 772 : :
# 773 : : const uint256& GetMessageHash() const;
# 774 : : int readHeader(const char *pch, unsigned int nBytes);
# 775 : : int readData(const char *pch, unsigned int nBytes);
# 776 : :
# 777 : 84566 : void Reset() {
# 778 : 84566 : vRecv.clear();
# 779 : 84566 : hdrbuf.clear();
# 780 : 84566 : hdrbuf.resize(24);
# 781 : 84566 : in_data = false;
# 782 : 84566 : nHdrPos = 0;
# 783 : 84566 : nDataPos = 0;
# 784 : 84566 : data_hash.SetNull();
# 785 : 84566 : hasher.Reset();
# 786 : 84566 : }
# 787 : :
# 788 : : public:
# 789 : : V1TransportDeserializer(const CChainParams& chain_params, const NodeId node_id, int nTypeIn, int nVersionIn)
# 790 : : : m_chain_params(chain_params),
# 791 : : m_node_id(node_id),
# 792 : : hdrbuf(nTypeIn, nVersionIn),
# 793 : : vRecv(nTypeIn, nVersionIn)
# 794 : 825 : {
# 795 : 825 : Reset();
# 796 : 825 : }
# 797 : :
# 798 : : bool Complete() const override
# 799 : 270957 : {
# 800 : 270957 : if (!in_data)
# 801 : 1 : return false;
# 802 : 270956 : return (hdr.nMessageSize == nDataPos);
# 803 : 270956 : }
# 804 : : void SetVersion(int nVersionIn) override
# 805 : 0 : {
# 806 : 0 : hdrbuf.SetVersion(nVersionIn);
# 807 : 0 : vRecv.SetVersion(nVersionIn);
# 808 : 0 : }
# 809 : 187224 : int Read(const char *pch, unsigned int nBytes) override {
# 810 : 103482 : int ret = in_data ? readData(pch, nBytes) : readHeader(pch, nBytes);
# 811 : 187224 : if (ret < 0) Reset();
# 812 : 187224 : return ret;
# 813 : 187224 : }
# 814 : : Optional<CNetMessage> GetMessage(std::chrono::microseconds time, uint32_t& out_err_raw_size) override;
# 815 : : };
# 816 : :
# 817 : : /** The TransportSerializer prepares messages for the network transport
# 818 : : */
# 819 : : class TransportSerializer {
# 820 : : public:
# 821 : : // prepare message for transport (header construction, error-correction computation, payload encryption, etc.)
# 822 : : virtual void prepareForTransport(CSerializedNetMsg& msg, std::vector<unsigned char>& header) = 0;
# 823 : 1650 : virtual ~TransportSerializer() {}
# 824 : : };
# 825 : :
# 826 : : class V1TransportSerializer : public TransportSerializer {
# 827 : : public:
# 828 : : void prepareForTransport(CSerializedNetMsg& msg, std::vector<unsigned char>& header) override;
# 829 : : };
# 830 : :
# 831 : : /** Information about a peer */
# 832 : : class CNode
# 833 : : {
# 834 : : friend class CConnman;
# 835 : : friend struct ConnmanTestMsg;
# 836 : :
# 837 : : public:
# 838 : : std::unique_ptr<TransportDeserializer> m_deserializer;
# 839 : : std::unique_ptr<TransportSerializer> m_serializer;
# 840 : :
# 841 : : // socket
# 842 : : std::atomic<ServiceFlags> nServices{NODE_NONE};
# 843 : : SOCKET hSocket GUARDED_BY(cs_hSocket);
# 844 : : size_t nSendSize{0}; // total size of all vSendMsg entries
# 845 : : size_t nSendOffset{0}; // offset inside the first vSendMsg already sent
# 846 : : uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
# 847 : : std::deque<std::vector<unsigned char>> vSendMsg GUARDED_BY(cs_vSend);
# 848 : : RecursiveMutex cs_vSend;
# 849 : : RecursiveMutex cs_hSocket;
# 850 : : RecursiveMutex cs_vRecv;
# 851 : :
# 852 : : RecursiveMutex cs_vProcessMsg;
# 853 : : std::list<CNetMessage> vProcessMsg GUARDED_BY(cs_vProcessMsg);
# 854 : : size_t nProcessQueueSize{0};
# 855 : :
# 856 : : RecursiveMutex cs_sendProcessing;
# 857 : :
# 858 : : std::deque<CInv> vRecvGetData;
# 859 : : uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
# 860 : :
# 861 : : std::atomic<int64_t> nLastSend{0};
# 862 : : std::atomic<int64_t> nLastRecv{0};
# 863 : : const int64_t nTimeConnected;
# 864 : : std::atomic<int64_t> nTimeOffset{0};
# 865 : : // Address of this peer
# 866 : : const CAddress addr;
# 867 : : // Bind address of our side of the connection
# 868 : : const CAddress addrBind;
# 869 : : std::atomic<int> nVersion{0};
# 870 : : RecursiveMutex cs_SubVer;
# 871 : : /**
# 872 : : * cleanSubVer is a sanitized string of the user agent byte array we read
# 873 : : * from the wire. This cleaned string can safely be logged or displayed.
# 874 : : */
# 875 : : std::string cleanSubVer GUARDED_BY(cs_SubVer){};
# 876 : : bool m_prefer_evict{false}; // This peer is preferred for eviction.
# 877 : 491310 : bool HasPermission(NetPermissionFlags permission) const {
# 878 : 491310 : return NetPermissions::HasFlag(m_permissionFlags, permission);
# 879 : 491310 : }
# 880 : : // This boolean is unusued in actual processing, only present for backward compatibility at RPC/QT level
# 881 : : bool m_legacyWhitelisted{false};
# 882 : : bool fClient{false}; // set by version message
# 883 : : bool m_limited_node{false}; //after BIP159, set by version message
# 884 : : std::atomic_bool fSuccessfullyConnected{false};
# 885 : : // Setting fDisconnect to true will cause the node to be disconnected the
# 886 : : // next time DisconnectNodes() runs
# 887 : : std::atomic_bool fDisconnect{false};
# 888 : : bool fSentAddr{false};
# 889 : : CSemaphoreGrant grantOutbound;
# 890 : : std::atomic<int> nRefCount{0};
# 891 : :
# 892 : : const uint64_t nKeyedNetGroup;
# 893 : : std::atomic_bool fPauseRecv{false};
# 894 : : std::atomic_bool fPauseSend{false};
# 895 : :
# 896 : 224091 : bool IsOutboundOrBlockRelayConn() const {
# 897 : 224091 : switch (m_conn_type) {
# 898 : 110 : case ConnectionType::OUTBOUND_FULL_RELAY:
# 899 : 110 : case ConnectionType::BLOCK_RELAY:
# 900 : 110 : return true;
# 901 : 223981 : case ConnectionType::INBOUND:
# 902 : 223981 : case ConnectionType::MANUAL:
# 903 : 223981 : case ConnectionType::ADDR_FETCH:
# 904 : 223981 : case ConnectionType::FEELER:
# 905 : 223981 : return false;
# 906 : 0 : } // no default case, so the compiler can warn about missing cases
# 907 : :
# 908 : 0 : assert(false);
# 909 : 0 : }
# 910 : :
# 911 : 24827 : bool IsFullOutboundConn() const {
# 912 : 24827 : return m_conn_type == ConnectionType::OUTBOUND_FULL_RELAY;
# 913 : 24827 : }
# 914 : :
# 915 : 7886 : bool IsManualConn() const {
# 916 : 7886 : return m_conn_type == ConnectionType::MANUAL;
# 917 : 7886 : }
# 918 : :
# 919 : 19707 : bool IsBlockOnlyConn() const {
# 920 : 19707 : return m_conn_type == ConnectionType::BLOCK_RELAY;
# 921 : 19707 : }
# 922 : :
# 923 : 778 : bool IsFeelerConn() const {
# 924 : 778 : return m_conn_type == ConnectionType::FEELER;
# 925 : 778 : }
# 926 : :
# 927 : 70425 : bool IsAddrFetchConn() const {
# 928 : 70425 : return m_conn_type == ConnectionType::ADDR_FETCH;
# 929 : 70425 : }
# 930 : :
# 931 : 29210 : bool IsInboundConn() const {
# 932 : 29210 : return m_conn_type == ConnectionType::INBOUND;
# 933 : 29210 : }
# 934 : :
# 935 : : /* Whether we send addr messages over this connection */
# 936 : : bool RelayAddrsWithConn() const
# 937 : 448519 : {
# 938 : 448519 : return m_conn_type != ConnectionType::BLOCK_RELAY;
# 939 : 448519 : }
# 940 : :
# 941 : 775 : bool ExpectServicesFromConn() const {
# 942 : 775 : switch (m_conn_type) {
# 943 : 775 : case ConnectionType::INBOUND:
# 944 : 775 : case ConnectionType::MANUAL:
# 945 : 775 : case ConnectionType::FEELER:
# 946 : 775 : return false;
# 947 : 0 : case ConnectionType::OUTBOUND_FULL_RELAY:
# 948 : 0 : case ConnectionType::BLOCK_RELAY:
# 949 : 0 : case ConnectionType::ADDR_FETCH:
# 950 : 0 : return true;
# 951 : 0 : } // no default case, so the compiler can warn about missing cases
# 952 : :
# 953 : 0 : assert(false);
# 954 : 0 : }
# 955 : :
# 956 : : protected:
# 957 : : mapMsgCmdSize mapSendBytesPerMsgCmd;
# 958 : : mapMsgCmdSize mapRecvBytesPerMsgCmd GUARDED_BY(cs_vRecv);
# 959 : :
# 960 : : public:
# 961 : : uint256 hashContinue;
# 962 : : std::atomic<int> nStartingHeight{-1};
# 963 : :
# 964 : : // flood relay
# 965 : : std::vector<CAddress> vAddrToSend;
# 966 : : std::unique_ptr<CRollingBloomFilter> m_addr_known{nullptr};
# 967 : : bool fGetAddr{false};
# 968 : : std::chrono::microseconds m_next_addr_send GUARDED_BY(cs_sendProcessing){0};
# 969 : : std::chrono::microseconds m_next_local_addr_send GUARDED_BY(cs_sendProcessing){0};
# 970 : :
# 971 : : // List of block ids we still have announce.
# 972 : : // There is no final sorting before sending, as they are always sent immediately
# 973 : : // and in the order requested.
# 974 : : std::vector<uint256> vInventoryBlockToSend GUARDED_BY(cs_inventory);
# 975 : : Mutex cs_inventory;
# 976 : :
# 977 : : struct TxRelay {
# 978 : : mutable RecursiveMutex cs_filter;
# 979 : : // We use fRelayTxes for two purposes -
# 980 : : // a) it allows us to not relay tx invs before receiving the peer's version message
# 981 : : // b) the peer may tell us in its version message that we should not relay tx invs
# 982 : : // unless it loads a bloom filter.
# 983 : : bool fRelayTxes GUARDED_BY(cs_filter){false};
# 984 : : std::unique_ptr<CBloomFilter> pfilter PT_GUARDED_BY(cs_filter) GUARDED_BY(cs_filter){nullptr};
# 985 : :
# 986 : : mutable RecursiveMutex cs_tx_inventory;
# 987 : : CRollingBloomFilter filterInventoryKnown GUARDED_BY(cs_tx_inventory){50000, 0.000001};
# 988 : : // Set of transaction ids we still have to announce.
# 989 : : // They are sorted by the mempool before relay, so the order is not important.
# 990 : : std::set<uint256> setInventoryTxToSend;
# 991 : : // Used for BIP35 mempool sending
# 992 : : bool fSendMempool GUARDED_BY(cs_tx_inventory){false};
# 993 : : // Last time a "MEMPOOL" request was serviced.
# 994 : : std::atomic<std::chrono::seconds> m_last_mempool_req{std::chrono::seconds{0}};
# 995 : : std::chrono::microseconds nNextInvSend{0};
# 996 : :
# 997 : : RecursiveMutex cs_feeFilter;
# 998 : : // Minimum fee rate with which to filter inv's to this node
# 999 : : CAmount minFeeFilter GUARDED_BY(cs_feeFilter){0};
# 1000 : : CAmount lastSentFeeFilter{0};
# 1001 : : int64_t nextSendTimeFeeFilter{0};
# 1002 : : };
# 1003 : :
# 1004 : : // m_tx_relay == nullptr if we're not relaying transactions with this peer
# 1005 : : std::unique_ptr<TxRelay> m_tx_relay;
# 1006 : :
# 1007 : : // Used for headers announcements - unfiltered blocks to relay
# 1008 : : std::vector<uint256> vBlockHashesToAnnounce GUARDED_BY(cs_inventory);
# 1009 : :
# 1010 : : /** UNIX epoch time of the last block received from this peer that we had
# 1011 : : * not yet seen (e.g. not already received from another peer), that passed
# 1012 : : * preliminary validity checks and was saved to disk, even if we don't
# 1013 : : * connect the block or it eventually fails connection. Used as an inbound
# 1014 : : * peer eviction criterium in CConnman::AttemptToEvictConnection. */
# 1015 : : std::atomic<int64_t> nLastBlockTime{0};
# 1016 : :
# 1017 : : /** UNIX epoch time of the last transaction received from this peer that we
# 1018 : : * had not yet seen (e.g. not already received from another peer) and that
# 1019 : : * was accepted into our mempool. Used as an inbound peer eviction criterium
# 1020 : : * in CConnman::AttemptToEvictConnection. */
# 1021 : : std::atomic<int64_t> nLastTXTime{0};
# 1022 : :
# 1023 : : // Ping time measurement:
# 1024 : : // The pong reply we're expecting, or 0 if no pong expected.
# 1025 : : std::atomic<uint64_t> nPingNonceSent{0};
# 1026 : : /** When the last ping was sent, or 0 if no ping was ever sent */
# 1027 : : std::atomic<std::chrono::microseconds> m_ping_start{std::chrono::microseconds{0}};
# 1028 : : // Last measured round-trip time.
# 1029 : : std::atomic<int64_t> nPingUsecTime{0};
# 1030 : : // Best measured round-trip time.
# 1031 : : std::atomic<int64_t> nMinPingUsecTime{std::numeric_limits<int64_t>::max()};
# 1032 : : // Whether a ping is requested.
# 1033 : : std::atomic<bool> fPingQueued{false};
# 1034 : :
# 1035 : : std::set<uint256> orphan_work_set;
# 1036 : :
# 1037 : : CNode(NodeId id, ServiceFlags nLocalServicesIn, int nMyStartingHeightIn, SOCKET hSocketIn, const CAddress &addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const CAddress &addrBindIn, const std::string &addrNameIn, ConnectionType conn_type_in);
# 1038 : : ~CNode();
# 1039 : : CNode(const CNode&) = delete;
# 1040 : : CNode& operator=(const CNode&) = delete;
# 1041 : :
# 1042 : : private:
# 1043 : : const NodeId id;
# 1044 : : const uint64_t nLocalHostNonce;
# 1045 : : const ConnectionType m_conn_type;
# 1046 : : std::atomic<int> m_greatest_common_version{INIT_PROTO_VERSION};
# 1047 : :
# 1048 : : //! Services offered to this peer.
# 1049 : : //!
# 1050 : : //! This is supplied by the parent CConnman during peer connection
# 1051 : : //! (CConnman::ConnectNode()) from its attribute of the same name.
# 1052 : : //!
# 1053 : : //! This is const because there is no protocol defined for renegotiating
# 1054 : : //! services initially offered to a peer. The set of local services we
# 1055 : : //! offer should not change after initialization.
# 1056 : : //!
# 1057 : : //! An interesting example of this is NODE_NETWORK and initial block
# 1058 : : //! download: a node which starts up from scratch doesn't have any blocks
# 1059 : : //! to serve, but still advertises NODE_NETWORK because it will eventually
# 1060 : : //! fulfill this role after IBD completes. P2P code is written in such a
# 1061 : : //! way that it can gracefully handle peers who don't make good on their
# 1062 : : //! service advertisements.
# 1063 : : const ServiceFlags nLocalServices;
# 1064 : :
# 1065 : : const int nMyStartingHeight;
# 1066 : : NetPermissionFlags m_permissionFlags{ PF_NONE };
# 1067 : : std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
# 1068 : :
# 1069 : : mutable RecursiveMutex cs_addrName;
# 1070 : : std::string addrName GUARDED_BY(cs_addrName);
# 1071 : :
# 1072 : : // Our address, as reported by the peer
# 1073 : : CService addrLocal GUARDED_BY(cs_addrLocal);
# 1074 : : mutable RecursiveMutex cs_addrLocal;
# 1075 : : public:
# 1076 : :
# 1077 : 1984417 : NodeId GetId() const {
# 1078 : 1984417 : return id;
# 1079 : 1984417 : }
# 1080 : :
# 1081 : 806 : uint64_t GetLocalNonce() const {
# 1082 : 806 : return nLocalHostNonce;
# 1083 : 806 : }
# 1084 : :
# 1085 : 806 : int GetMyStartingHeight() const {
# 1086 : 806 : return nMyStartingHeight;
# 1087 : 806 : }
# 1088 : :
# 1089 : : int GetRefCount() const
# 1090 : 344 : {
# 1091 : 344 : assert(nRefCount >= 0);
# 1092 : 344 : return nRefCount;
# 1093 : 344 : }
# 1094 : :
# 1095 : : bool ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool& complete);
# 1096 : :
# 1097 : : void SetCommonVersion(int greatest_common_version)
# 1098 : 800 : {
# 1099 : 800 : m_greatest_common_version = greatest_common_version;
# 1100 : 800 : }
# 1101 : : int GetCommonVersion() const
# 1102 : 995726 : {
# 1103 : 995726 : return m_greatest_common_version;
# 1104 : 995726 : }
# 1105 : :
# 1106 : : CService GetAddrLocal() const;
# 1107 : : //! May not be called more than once
# 1108 : : void SetAddrLocal(const CService& addrLocalIn);
# 1109 : :
# 1110 : : CNode* AddRef()
# 1111 : 575113 : {
# 1112 : 575113 : nRefCount++;
# 1113 : 575113 : return this;
# 1114 : 575113 : }
# 1115 : :
# 1116 : : void Release()
# 1117 : 574632 : {
# 1118 : 574632 : nRefCount--;
# 1119 : 574632 : }
# 1120 : :
# 1121 : :
# 1122 : :
# 1123 : : void AddAddressKnown(const CAddress& _addr)
# 1124 : 12 : {
# 1125 : 12 : assert(m_addr_known);
# 1126 : 12 : m_addr_known->insert(_addr.GetKey());
# 1127 : 12 : }
# 1128 : :
# 1129 : : void PushAddress(const CAddress& _addr, FastRandomContext &insecure_rand)
# 1130 : 6027 : {
# 1131 : : // Known checking here is only to save space from duplicates.
# 1132 : : // SendMessages will filter it again for knowns that were added
# 1133 : : // after addresses were pushed.
# 1134 : 6027 : assert(m_addr_known);
# 1135 : 6027 : if (_addr.IsValid() && !m_addr_known->contains(_addr.GetKey())) {
# 1136 : 6017 : if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
# 1137 : 0 : vAddrToSend[insecure_rand.randrange(vAddrToSend.size())] = _addr;
# 1138 : 6017 : } else {
# 1139 : 6017 : vAddrToSend.push_back(_addr);
# 1140 : 6017 : }
# 1141 : 6017 : }
# 1142 : 6027 : }
# 1143 : :
# 1144 : :
# 1145 : : void AddKnownTx(const uint256& hash)
# 1146 : 22623 : {
# 1147 : 22623 : if (m_tx_relay != nullptr) {
# 1148 : 22623 : LOCK(m_tx_relay->cs_tx_inventory);
# 1149 : 22623 : m_tx_relay->filterInventoryKnown.insert(hash);
# 1150 : 22623 : }
# 1151 : 22623 : }
# 1152 : :
# 1153 : : void PushTxInventory(const uint256& hash)
# 1154 : 28508 : {
# 1155 : 28508 : if (m_tx_relay == nullptr) return;
# 1156 : 28508 : LOCK(m_tx_relay->cs_tx_inventory);
# 1157 : 28508 : if (!m_tx_relay->filterInventoryKnown.contains(hash)) {
# 1158 : 19259 : m_tx_relay->setInventoryTxToSend.insert(hash);
# 1159 : 19259 : }
# 1160 : 28508 : }
# 1161 : :
# 1162 : : void CloseSocketDisconnect();
# 1163 : :
# 1164 : : void copyStats(CNodeStats &stats, const std::vector<bool> &m_asmap);
# 1165 : :
# 1166 : : ServiceFlags GetLocalServices() const
# 1167 : 40531 : {
# 1168 : 40531 : return nLocalServices;
# 1169 : 40531 : }
# 1170 : :
# 1171 : : std::string GetAddrName() const;
# 1172 : : //! Sets the addrName only if it was not previously set
# 1173 : : void MaybeSetAddrName(const std::string& addrNameIn);
# 1174 : :
# 1175 : : std::string ConnectionTypeAsString() const;
# 1176 : : };
# 1177 : :
# 1178 : : /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
# 1179 : : int64_t PoissonNextSend(int64_t now, int average_interval_seconds);
# 1180 : :
# 1181 : : /** Wrapper to return mockable type */
# 1182 : : inline std::chrono::microseconds PoissonNextSend(std::chrono::microseconds now, std::chrono::seconds average_interval)
# 1183 : 3915 : {
# 1184 : 3915 : return std::chrono::microseconds{PoissonNextSend(now.count(), average_interval.count())};
# 1185 : 3915 : }
# 1186 : :
# 1187 : : #endif // BITCOIN_NET_H
|