Branch data Line data Source code
# 1 : : // Copyright (c) 2009-2010 Satoshi Nakamoto
# 2 : : // Copyright (c) 2009-2022 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 <bip324.h>
# 10 : : #include <chainparams.h>
# 11 : : #include <common/bloom.h>
# 12 : : #include <compat/compat.h>
# 13 : : #include <node/connection_types.h>
# 14 : : #include <consensus/amount.h>
# 15 : : #include <crypto/siphash.h>
# 16 : : #include <hash.h>
# 17 : : #include <i2p.h>
# 18 : : #include <net_permissions.h>
# 19 : : #include <netaddress.h>
# 20 : : #include <netbase.h>
# 21 : : #include <netgroup.h>
# 22 : : #include <policy/feerate.h>
# 23 : : #include <protocol.h>
# 24 : : #include <random.h>
# 25 : : #include <span.h>
# 26 : : #include <streams.h>
# 27 : : #include <sync.h>
# 28 : : #include <uint256.h>
# 29 : : #include <util/check.h>
# 30 : : #include <util/sock.h>
# 31 : : #include <util/threadinterrupt.h>
# 32 : :
# 33 : : #include <atomic>
# 34 : : #include <condition_variable>
# 35 : : #include <cstdint>
# 36 : : #include <deque>
# 37 : : #include <functional>
# 38 : : #include <list>
# 39 : : #include <map>
# 40 : : #include <memory>
# 41 : : #include <optional>
# 42 : : #include <queue>
# 43 : : #include <thread>
# 44 : : #include <unordered_set>
# 45 : : #include <vector>
# 46 : :
# 47 : : class AddrMan;
# 48 : : class BanMan;
# 49 : : class CNode;
# 50 : : class CScheduler;
# 51 : : struct bilingual_str;
# 52 : :
# 53 : : /** Default for -whitelistrelay. */
# 54 : : static const bool DEFAULT_WHITELISTRELAY = true;
# 55 : : /** Default for -whitelistforcerelay. */
# 56 : : static const bool DEFAULT_WHITELISTFORCERELAY = false;
# 57 : :
# 58 : : /** Time after which to disconnect, after waiting for a ping response (or inactivity). */
# 59 : : static constexpr std::chrono::minutes TIMEOUT_INTERVAL{20};
# 60 : : /** Run the feeler connection loop once every 2 minutes. **/
# 61 : : static constexpr auto FEELER_INTERVAL = 2min;
# 62 : : /** Run the extra block-relay-only connection loop once every 5 minutes. **/
# 63 : : static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL = 5min;
# 64 : : /** Maximum length of incoming protocol messages (no message over 4 MB is currently acceptable). */
# 65 : : static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
# 66 : : /** Maximum length of the user agent string in `version` message */
# 67 : : static const unsigned int MAX_SUBVERSION_LENGTH = 256;
# 68 : : /** Maximum number of automatic outgoing nodes over which we'll relay everything (blocks, tx, addrs, etc) */
# 69 : : static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS = 8;
# 70 : : /** Maximum number of addnode outgoing nodes */
# 71 : : static const int MAX_ADDNODE_CONNECTIONS = 8;
# 72 : : /** Maximum number of block-relay-only outgoing connections */
# 73 : : static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS = 2;
# 74 : : /** Maximum number of feeler connections */
# 75 : : static const int MAX_FEELER_CONNECTIONS = 1;
# 76 : : /** -listen default */
# 77 : : static const bool DEFAULT_LISTEN = true;
# 78 : : /** The maximum number of peer connections to maintain. */
# 79 : : static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
# 80 : : /** The default for -maxuploadtarget. 0 = Unlimited */
# 81 : : static const std::string DEFAULT_MAX_UPLOAD_TARGET{"0M"};
# 82 : : /** Default for blocks only*/
# 83 : : static const bool DEFAULT_BLOCKSONLY = false;
# 84 : : /** -peertimeout default */
# 85 : : static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
# 86 : : /** Number of file descriptors required for message capture **/
# 87 : : static const int NUM_FDS_MESSAGE_CAPTURE = 1;
# 88 : :
# 89 : : static constexpr bool DEFAULT_FORCEDNSSEED{false};
# 90 : : static constexpr bool DEFAULT_DNSSEED{true};
# 91 : : static constexpr bool DEFAULT_FIXEDSEEDS{true};
# 92 : : static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
# 93 : : static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
# 94 : :
# 95 : : typedef int64_t NodeId;
# 96 : :
# 97 : : struct AddedNodeInfo
# 98 : : {
# 99 : : std::string strAddedNode;
# 100 : : CService resolvedAddress;
# 101 : : bool fConnected;
# 102 : : bool fInbound;
# 103 : : };
# 104 : :
# 105 : : class CNodeStats;
# 106 : : class CClientUIInterface;
# 107 : :
# 108 : : struct CSerializedNetMsg {
# 109 : 2300388 : CSerializedNetMsg() = default;
# 110 : 500119 : CSerializedNetMsg(CSerializedNetMsg&&) = default;
# 111 : 191646 : CSerializedNetMsg& operator=(CSerializedNetMsg&&) = default;
# 112 : : // No implicit copying, only moves.
# 113 : : CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
# 114 : : CSerializedNetMsg& operator=(const CSerializedNetMsg&) = delete;
# 115 : :
# 116 : : CSerializedNetMsg Copy() const
# 117 : 1475329 : {
# 118 : 1475329 : CSerializedNetMsg copy;
# 119 : 1475329 : copy.data = data;
# 120 : 1475329 : copy.m_type = m_type;
# 121 : 1475329 : return copy;
# 122 : 1475329 : }
# 123 : :
# 124 : : std::vector<unsigned char> data;
# 125 : : std::string m_type;
# 126 : :
# 127 : : /** Compute total memory usage of this object (own memory + any dynamic memory). */
# 128 : : size_t GetMemoryUsage() const noexcept;
# 129 : : };
# 130 : :
# 131 : : /**
# 132 : : * Look up IP addresses from all interfaces on the machine and add them to the
# 133 : : * list of local addresses to self-advertise.
# 134 : : * The loopback interface is skipped and only the first address from each
# 135 : : * interface is used.
# 136 : : */
# 137 : : void Discover();
# 138 : :
# 139 : : uint16_t GetListenPort();
# 140 : :
# 141 : : enum
# 142 : : {
# 143 : : LOCAL_NONE, // unknown
# 144 : : LOCAL_IF, // address a local interface listens on
# 145 : : LOCAL_BIND, // address explicit bound to
# 146 : : LOCAL_MAPPED, // address reported by UPnP or NAT-PMP
# 147 : : LOCAL_MANUAL, // address explicitly specified (-externalip=)
# 148 : :
# 149 : : LOCAL_MAX
# 150 : : };
# 151 : :
# 152 : : bool IsPeerAddrLocalGood(CNode *pnode);
# 153 : : /** Returns a local address that we should advertise to this peer. */
# 154 : : std::optional<CService> GetLocalAddrForPeer(CNode& node);
# 155 : :
# 156 : : /**
# 157 : : * Mark a network as reachable or unreachable (no automatic connects to it)
# 158 : : * @note Networks are reachable by default
# 159 : : */
# 160 : : void SetReachable(enum Network net, bool reachable);
# 161 : : /** @returns true if the network is reachable, false otherwise */
# 162 : : bool IsReachable(enum Network net);
# 163 : : /** @returns true if the address is in a reachable network, false otherwise */
# 164 : : bool IsReachable(const CNetAddr& addr);
# 165 : :
# 166 : : bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
# 167 : : bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
# 168 : : void RemoveLocal(const CService& addr);
# 169 : : bool SeenLocal(const CService& addr);
# 170 : : bool IsLocal(const CService& addr);
# 171 : : bool GetLocal(CService& addr, const CNode& peer);
# 172 : : CService GetLocalAddress(const CNode& peer);
# 173 : : CService MaybeFlipIPv6toCJDNS(const CService& service);
# 174 : :
# 175 : :
# 176 : : extern bool fDiscover;
# 177 : : extern bool fListen;
# 178 : :
# 179 : : /** Subversion as sent to the P2P network in `version` messages */
# 180 : : extern std::string strSubVersion;
# 181 : :
# 182 : : struct LocalServiceInfo {
# 183 : : int nScore;
# 184 : : uint16_t nPort;
# 185 : : };
# 186 : :
# 187 : : extern GlobalMutex g_maplocalhost_mutex;
# 188 : : extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(g_maplocalhost_mutex);
# 189 : :
# 190 : : extern const std::string NET_MESSAGE_TYPE_OTHER;
# 191 : : using mapMsgTypeSize = std::map</* message type */ std::string, /* total bytes */ uint64_t>;
# 192 : :
# 193 : : class CNodeStats
# 194 : : {
# 195 : : public:
# 196 : : NodeId nodeid;
# 197 : : std::chrono::seconds m_last_send;
# 198 : : std::chrono::seconds m_last_recv;
# 199 : : std::chrono::seconds m_last_tx_time;
# 200 : : std::chrono::seconds m_last_block_time;
# 201 : : std::chrono::seconds m_connected;
# 202 : : int64_t nTimeOffset;
# 203 : : std::string m_addr_name;
# 204 : : int nVersion;
# 205 : : std::string cleanSubVer;
# 206 : : bool fInbound;
# 207 : : // We requested high bandwidth connection to peer
# 208 : : bool m_bip152_highbandwidth_to;
# 209 : : // Peer requested high bandwidth connection
# 210 : : bool m_bip152_highbandwidth_from;
# 211 : : int m_starting_height;
# 212 : : uint64_t nSendBytes;
# 213 : : mapMsgTypeSize mapSendBytesPerMsgType;
# 214 : : uint64_t nRecvBytes;
# 215 : : mapMsgTypeSize mapRecvBytesPerMsgType;
# 216 : : NetPermissionFlags m_permission_flags;
# 217 : : std::chrono::microseconds m_last_ping_time;
# 218 : : std::chrono::microseconds m_min_ping_time;
# 219 : : // Our address, as reported by the peer
# 220 : : std::string addrLocal;
# 221 : : // Address of this peer
# 222 : : CAddress addr;
# 223 : : // Bind address of our side of the connection
# 224 : : CAddress addrBind;
# 225 : : // Network the peer connected through
# 226 : : Network m_network;
# 227 : : uint32_t m_mapped_as;
# 228 : : ConnectionType m_conn_type;
# 229 : : };
# 230 : :
# 231 : :
# 232 : : /** Transport protocol agnostic message container.
# 233 : : * Ideally it should only contain receive time, payload,
# 234 : : * type and size.
# 235 : : */
# 236 : : class CNetMessage {
# 237 : : public:
# 238 : : CDataStream m_recv; //!< received message data
# 239 : : std::chrono::microseconds m_time{0}; //!< time of message receipt
# 240 : : uint32_t m_message_size{0}; //!< size of the payload
# 241 : : uint32_t m_raw_message_size{0}; //!< used wire size of the message (including header/checksum)
# 242 : : std::string m_type;
# 243 : :
# 244 : 160436 : CNetMessage(CDataStream&& recv_in) : m_recv(std::move(recv_in)) {}
# 245 : : // Only one CNetMessage object will exist for the same message on either
# 246 : : // the receive or processing queue. For performance reasons we therefore
# 247 : : // delete the copy constructor and assignment operator to avoid the
# 248 : : // possibility of copying CNetMessage objects.
# 249 : 372664 : CNetMessage(CNetMessage&&) = default;
# 250 : : CNetMessage(const CNetMessage&) = delete;
# 251 : : CNetMessage& operator=(CNetMessage&&) = default;
# 252 : : CNetMessage& operator=(const CNetMessage&) = delete;
# 253 : :
# 254 : : void SetVersion(int nVersionIn)
# 255 : 122445 : {
# 256 : 122445 : m_recv.SetVersion(nVersionIn);
# 257 : 122445 : }
# 258 : : };
# 259 : :
# 260 : : /** The Transport converts one connection's sent messages to wire bytes, and received bytes back. */
# 261 : : class Transport {
# 262 : : public:
# 263 : 706488 : virtual ~Transport() {}
# 264 : :
# 265 : : // 1. Receiver side functions, for decoding bytes received on the wire into transport protocol
# 266 : : // agnostic CNetMessage (message type & payload) objects.
# 267 : :
# 268 : : /** Returns true if the current message is complete (so GetReceivedMessage can be called). */
# 269 : : virtual bool ReceivedMessageComplete() const = 0;
# 270 : :
# 271 : : /** Feed wire bytes to the transport.
# 272 : : *
# 273 : : * @return false if some bytes were invalid, in which case the transport can't be used anymore.
# 274 : : *
# 275 : : * Consumed bytes are chopped off the front of msg_bytes.
# 276 : : */
# 277 : : virtual bool ReceivedBytes(Span<const uint8_t>& msg_bytes) = 0;
# 278 : :
# 279 : : /** Retrieve a completed message from transport.
# 280 : : *
# 281 : : * This can only be called when ReceivedMessageComplete() is true.
# 282 : : *
# 283 : : * If reject_message=true is returned the message itself is invalid, but (other than false
# 284 : : * returned by ReceivedBytes) the transport is not in an inconsistent state.
# 285 : : */
# 286 : : virtual CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) = 0;
# 287 : :
# 288 : : // 2. Sending side functions, for converting messages into bytes to be sent over the wire.
# 289 : :
# 290 : : /** Set the next message to send.
# 291 : : *
# 292 : : * If no message can currently be set (perhaps because the previous one is not yet done being
# 293 : : * sent), returns false, and msg will be unmodified. Otherwise msg is enqueued (and
# 294 : : * possibly moved-from) and true is returned.
# 295 : : */
# 296 : : virtual bool SetMessageToSend(CSerializedNetMsg& msg) noexcept = 0;
# 297 : :
# 298 : : /** Return type for GetBytesToSend, consisting of:
# 299 : : * - Span<const uint8_t> to_send: span of bytes to be sent over the wire (possibly empty).
# 300 : : * - bool more: whether there will be more bytes to be sent after the ones in to_send are
# 301 : : * all sent (as signaled by MarkBytesSent()).
# 302 : : * - const std::string& m_type: message type on behalf of which this is being sent
# 303 : : * ("" for bytes that are not on behalf of any message).
# 304 : : */
# 305 : : using BytesToSend = std::tuple<
# 306 : : Span<const uint8_t> /*to_send*/,
# 307 : : bool /*more*/,
# 308 : : const std::string& /*m_type*/
# 309 : : >;
# 310 : :
# 311 : : /** Get bytes to send on the wire, if any, along with other information about it.
# 312 : : *
# 313 : : * As a const function, it does not modify the transport's observable state, and is thus safe
# 314 : : * to be called multiple times.
# 315 : : *
# 316 : : * @param[in] have_next_message If true, the "more" return value reports whether more will
# 317 : : * be sendable after a SetMessageToSend call. It is set by the caller when they know
# 318 : : * they have another message ready to send, and only care about what happens
# 319 : : * after that. The have_next_message argument only affects this "more" return value
# 320 : : * and nothing else.
# 321 : : *
# 322 : : * Effectively, there are three possible outcomes about whether there are more bytes
# 323 : : * to send:
# 324 : : * - Yes: the transport itself has more bytes to send later. For example, for
# 325 : : * V1Transport this happens during the sending of the header of a
# 326 : : * message, when there is a non-empty payload that follows.
# 327 : : * - No: the transport itself has no more bytes to send, but will have bytes to
# 328 : : * send if handed a message through SetMessageToSend. In V1Transport this
# 329 : : * happens when sending the payload of a message.
# 330 : : * - Blocked: the transport itself has no more bytes to send, and is also incapable
# 331 : : * of sending anything more at all now, if it were handed another
# 332 : : * message to send. This occurs in V2Transport before the handshake is
# 333 : : * complete, as the encryption ciphers are not set up for sending
# 334 : : * messages before that point.
# 335 : : *
# 336 : : * The boolean 'more' is true for Yes, false for Blocked, and have_next_message
# 337 : : * controls what is returned for No.
# 338 : : *
# 339 : : * @return a BytesToSend object. The to_send member returned acts as a stream which is only
# 340 : : * ever appended to. This means that with the exception of MarkBytesSent (which pops
# 341 : : * bytes off the front of later to_sends), operations on the transport can only append
# 342 : : * to what is being returned. Also note that m_type and to_send refer to data that is
# 343 : : * internal to the transport, and calling any non-const function on this object may
# 344 : : * invalidate them.
# 345 : : */
# 346 : : virtual BytesToSend GetBytesToSend(bool have_next_message) const noexcept = 0;
# 347 : :
# 348 : : /** Report how many bytes returned by the last GetBytesToSend() have been sent.
# 349 : : *
# 350 : : * bytes_sent cannot exceed to_send.size() of the last GetBytesToSend() result.
# 351 : : *
# 352 : : * If bytes_sent=0, this call has no effect.
# 353 : : */
# 354 : : virtual void MarkBytesSent(size_t bytes_sent) noexcept = 0;
# 355 : :
# 356 : : /** Return the memory usage of this transport attributable to buffered data to send. */
# 357 : : virtual size_t GetSendMemoryUsage() const noexcept = 0;
# 358 : : };
# 359 : :
# 360 : : class V1Transport final : public Transport
# 361 : : {
# 362 : : private:
# 363 : : CMessageHeader::MessageStartChars m_magic_bytes;
# 364 : : const NodeId m_node_id; // Only for logging
# 365 : : mutable Mutex m_recv_mutex; //!< Lock for receive state
# 366 : : mutable CHash256 hasher GUARDED_BY(m_recv_mutex);
# 367 : : mutable uint256 data_hash GUARDED_BY(m_recv_mutex);
# 368 : : bool in_data GUARDED_BY(m_recv_mutex); // parsing header (false) or data (true)
# 369 : : CDataStream hdrbuf GUARDED_BY(m_recv_mutex); // partially received header
# 370 : : CMessageHeader hdr GUARDED_BY(m_recv_mutex); // complete header
# 371 : : CDataStream vRecv GUARDED_BY(m_recv_mutex); // received message data
# 372 : : unsigned int nHdrPos GUARDED_BY(m_recv_mutex);
# 373 : : unsigned int nDataPos GUARDED_BY(m_recv_mutex);
# 374 : :
# 375 : : const uint256& GetMessageHash() const EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
# 376 : : int readHeader(Span<const uint8_t> msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
# 377 : : int readData(Span<const uint8_t> msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
# 378 : :
# 379 : 520732 : void Reset() EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex) {
# 380 : 520732 : AssertLockHeld(m_recv_mutex);
# 381 : 520732 : vRecv.clear();
# 382 : 520732 : hdrbuf.clear();
# 383 : 520732 : hdrbuf.resize(24);
# 384 : 520732 : in_data = false;
# 385 : 520732 : nHdrPos = 0;
# 386 : 520732 : nDataPos = 0;
# 387 : 520732 : data_hash.SetNull();
# 388 : 520732 : hasher.Reset();
# 389 : 520732 : }
# 390 : :
# 391 : : bool CompleteInternal() const noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
# 392 : 533010 : {
# 393 : 533010 : AssertLockHeld(m_recv_mutex);
# 394 [ + + ]: 533010 : if (!in_data) return false;
# 395 : 500727 : return hdr.nMessageSize == nDataPos;
# 396 : 533010 : }
# 397 : :
# 398 : : /** Lock for sending state. */
# 399 : : mutable Mutex m_send_mutex;
# 400 : : /** The header of the message currently being sent. */
# 401 : : std::vector<uint8_t> m_header_to_send GUARDED_BY(m_send_mutex);
# 402 : : /** The data of the message currently being sent. */
# 403 : : CSerializedNetMsg m_message_to_send GUARDED_BY(m_send_mutex);
# 404 : : /** Whether we're currently sending header bytes or message bytes. */
# 405 : : bool m_sending_header GUARDED_BY(m_send_mutex) {false};
# 406 : : /** How many bytes have been sent so far (from m_header_to_send, or from m_message_to_send.data). */
# 407 : : size_t m_bytes_sent GUARDED_BY(m_send_mutex) {0};
# 408 : :
# 409 : : public:
# 410 : : V1Transport(const NodeId node_id, int nTypeIn, int nVersionIn) noexcept;
# 411 : :
# 412 : : bool ReceivedMessageComplete() const override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
# 413 : 378569 : {
# 414 : 378569 : AssertLockNotHeld(m_recv_mutex);
# 415 : 378569 : return WITH_LOCK(m_recv_mutex, return CompleteInternal());
# 416 : 378569 : }
# 417 : :
# 418 : : bool ReceivedBytes(Span<const uint8_t>& msg_bytes) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
# 419 : 378570 : {
# 420 : 378570 : AssertLockNotHeld(m_recv_mutex);
# 421 : 378570 : LOCK(m_recv_mutex);
# 422 [ + + ]: 378570 : int ret = in_data ? readData(msg_bytes) : readHeader(msg_bytes);
# 423 [ + + ]: 378570 : if (ret < 0) {
# 424 : 3 : Reset();
# 425 : 378567 : } else {
# 426 : 378567 : msg_bytes = msg_bytes.subspan(ret);
# 427 : 378567 : }
# 428 : 378570 : return ret >= 0;
# 429 : 378570 : }
# 430 : :
# 431 : : CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
# 432 : :
# 433 : : bool SetMessageToSend(CSerializedNetMsg& msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
# 434 : : BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
# 435 : : void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
# 436 : : size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
# 437 : : };
# 438 : :
# 439 : : class V2Transport final : public Transport
# 440 : : {
# 441 : : private:
# 442 : : /** Contents of the version packet to send. BIP324 stipulates that senders should leave this
# 443 : : * empty, and receivers should ignore it. Future extensions can change what is sent as long as
# 444 : : * an empty version packet contents is interpreted as no extensions supported. */
# 445 : : static constexpr std::array<std::byte, 0> VERSION_CONTENTS = {};
# 446 : :
# 447 : : /** The length of the V1 prefix to match bytes initially received by responders with to
# 448 : : * determine if their peer is speaking V1 or V2. */
# 449 : : static constexpr size_t V1_PREFIX_LEN = 12;
# 450 : :
# 451 : : // The sender side and receiver side of V2Transport are state machines that are transitioned
# 452 : : // through, based on what has been received. The receive state corresponds to the contents of,
# 453 : : // and bytes received to, the receive buffer. The send state controls what can be appended to
# 454 : : // the send buffer and what can be sent from it.
# 455 : :
# 456 : : /** State type that defines the current contents of the receive buffer and/or how the next
# 457 : : * received bytes added to it will be interpreted.
# 458 : : *
# 459 : : * Diagram:
# 460 : : *
# 461 : : * start(responder)
# 462 : : * |
# 463 : : * | start(initiator) /---------\
# 464 : : * | | | |
# 465 : : * v v v |
# 466 : : * KEY_MAYBE_V1 -> KEY -> GARB_GARBTERM -> GARBAUTH -> VERSION -> APP -> APP_READY
# 467 : : * |
# 468 : : * \-------> V1
# 469 : : */
# 470 : : enum class RecvState : uint8_t {
# 471 : : /** (Responder only) either v2 public key or v1 header.
# 472 : : *
# 473 : : * This is the initial state for responders, before data has been received to distinguish
# 474 : : * v1 from v2 connections. When that happens, the state becomes either KEY (for v2) or V1
# 475 : : * (for v1). */
# 476 : : KEY_MAYBE_V1,
# 477 : :
# 478 : : /** Public key.
# 479 : : *
# 480 : : * This is the initial state for initiators, during which the other side's public key is
# 481 : : * received. When that information arrives, the ciphers get initialized and the state
# 482 : : * becomes GARB_GARBTERM. */
# 483 : : KEY,
# 484 : :
# 485 : : /** Garbage and garbage terminator.
# 486 : : *
# 487 : : * Whenever a byte is received, the last 16 bytes are compared with the expected garbage
# 488 : : * terminator. When that happens, the state becomes GARBAUTH. If no matching terminator is
# 489 : : * received in 4111 bytes (4095 for the maximum garbage length, and 16 bytes for the
# 490 : : * terminator), the connection aborts. */
# 491 : : GARB_GARBTERM,
# 492 : :
# 493 : : /** Garbage authentication packet.
# 494 : : *
# 495 : : * A packet is received, and decrypted/verified with AAD set to the garbage received during
# 496 : : * the GARB_GARBTERM state. If that succeeds, the state becomes VERSION. If it fails the
# 497 : : * connection aborts. */
# 498 : : GARBAUTH,
# 499 : :
# 500 : : /** Version packet.
# 501 : : *
# 502 : : * A packet is received, and decrypted/verified. If that succeeds, the state becomes APP,
# 503 : : * and the decrypted contents is interpreted as version negotiation (currently, that means
# 504 : : * ignoring it, but it can be used for negotiating future extensions). If it fails, the
# 505 : : * connection aborts. */
# 506 : : VERSION,
# 507 : :
# 508 : : /** Application packet.
# 509 : : *
# 510 : : * A packet is received, and decrypted/verified. If that succeeds, the state becomes
# 511 : : * APP_READY and the decrypted contents is kept in m_recv_decode_buffer until it is
# 512 : : * retrieved as a message by GetMessage(). */
# 513 : : APP,
# 514 : :
# 515 : : /** Nothing (an application packet is available for GetMessage()).
# 516 : : *
# 517 : : * Nothing can be received in this state. When the message is retrieved by GetMessage,
# 518 : : * the state becomes APP again. */
# 519 : : APP_READY,
# 520 : :
# 521 : : /** Nothing (this transport is using v1 fallback).
# 522 : : *
# 523 : : * All receive operations are redirected to m_v1_fallback. */
# 524 : : V1,
# 525 : : };
# 526 : :
# 527 : : /** State type that controls the sender side.
# 528 : : *
# 529 : : * Diagram:
# 530 : : *
# 531 : : * start(responder)
# 532 : : * |
# 533 : : * | start(initiator)
# 534 : : * | |
# 535 : : * v v
# 536 : : * MAYBE_V1 -> AWAITING_KEY -> READY
# 537 : : * |
# 538 : : * \-----> V1
# 539 : : */
# 540 : : enum class SendState : uint8_t {
# 541 : : /** (Responder only) Not sending until v1 or v2 is detected.
# 542 : : *
# 543 : : * This is the initial state for responders. The send buffer contains the public key to
# 544 : : * send, but nothing is sent in this state yet. When the receiver determines whether this
# 545 : : * is a V1 or V2 connection, the sender state becomes AWAITING_KEY (for v2) or V1 (for v1).
# 546 : : */
# 547 : : MAYBE_V1,
# 548 : :
# 549 : : /** Waiting for the other side's public key.
# 550 : : *
# 551 : : * This is the initial state for initiators. The public key is sent out. When the receiver
# 552 : : * receives the other side's public key and transitions to GARB_GARBTERM, the sender state
# 553 : : * becomes READY. */
# 554 : : AWAITING_KEY,
# 555 : :
# 556 : : /** Normal sending state.
# 557 : : *
# 558 : : * In this state, the ciphers are initialized, so packets can be sent. When this state is
# 559 : : * entered, the garbage, garbage terminator, garbage authentication packet, and version
# 560 : : * packet are appended to the send buffer (in addition to the key which may still be
# 561 : : * there). In this state a message can be provided if the send buffer is empty. */
# 562 : : READY,
# 563 : :
# 564 : : /** This transport is using v1 fallback.
# 565 : : *
# 566 : : * All send operations are redirected to m_v1_fallback. */
# 567 : : V1,
# 568 : : };
# 569 : :
# 570 : : /** Cipher state. */
# 571 : : BIP324Cipher m_cipher;
# 572 : : /** Whether we are the initiator side. */
# 573 : : const bool m_initiating;
# 574 : : /** NodeId (for debug logging). */
# 575 : : const NodeId m_nodeid;
# 576 : : /** Encapsulate a V1Transport to fall back to. */
# 577 : : V1Transport m_v1_fallback;
# 578 : :
# 579 : : /** Lock for receiver-side fields. */
# 580 : : mutable Mutex m_recv_mutex ACQUIRED_BEFORE(m_send_mutex);
# 581 : : /** In {GARBAUTH, VERSION, APP}, the decrypted packet length, if m_recv_buffer.size() >=
# 582 : : * BIP324Cipher::LENGTH_LEN. Unspecified otherwise. */
# 583 : : uint32_t m_recv_len GUARDED_BY(m_recv_mutex) {0};
# 584 : : /** Receive buffer; meaning is determined by m_recv_state. */
# 585 : : std::vector<uint8_t> m_recv_buffer GUARDED_BY(m_recv_mutex);
# 586 : : /** During GARBAUTH, the garbage received during GARB_GARBTERM. */
# 587 : : std::vector<uint8_t> m_recv_garbage GUARDED_BY(m_recv_mutex);
# 588 : : /** Buffer to put decrypted contents in, for converting to CNetMessage. */
# 589 : : std::vector<uint8_t> m_recv_decode_buffer GUARDED_BY(m_recv_mutex);
# 590 : : /** Deserialization type. */
# 591 : : const int m_recv_type;
# 592 : : /** Deserialization version number. */
# 593 : : const int m_recv_version;
# 594 : : /** Current receiver state. */
# 595 : : RecvState m_recv_state GUARDED_BY(m_recv_mutex);
# 596 : :
# 597 : : /** Lock for sending-side fields. If both sending and receiving fields are accessed,
# 598 : : * m_recv_mutex must be acquired before m_send_mutex. */
# 599 : : mutable Mutex m_send_mutex ACQUIRED_AFTER(m_recv_mutex);
# 600 : : /** The send buffer; meaning is determined by m_send_state. */
# 601 : : std::vector<uint8_t> m_send_buffer GUARDED_BY(m_send_mutex);
# 602 : : /** How many bytes from the send buffer have been sent so far. */
# 603 : : uint32_t m_send_pos GUARDED_BY(m_send_mutex) {0};
# 604 : : /** Type of the message being sent. */
# 605 : : std::string m_send_type GUARDED_BY(m_send_mutex);
# 606 : : /** Current sender state. */
# 607 : : SendState m_send_state GUARDED_BY(m_send_mutex);
# 608 : :
# 609 : : /** Change the receive state. */
# 610 : : void SetReceiveState(RecvState recv_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
# 611 : : /** Change the send state. */
# 612 : : void SetSendState(SendState send_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex);
# 613 : : /** Given a packet's contents, find the message type (if valid), and strip it from contents. */
# 614 : : static std::optional<std::string> GetMessageType(Span<const uint8_t>& contents) noexcept;
# 615 : : /** Determine how many received bytes can be processed in one go (not allowed in V1 state). */
# 616 : : size_t GetMaxBytesToProcess() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
# 617 : : /** Process bytes in m_recv_buffer, while in KEY_MAYBE_V1 state. */
# 618 : : void ProcessReceivedMaybeV1Bytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex, !m_send_mutex);
# 619 : : /** Process bytes in m_recv_buffer, while in KEY state. */
# 620 : : bool ProcessReceivedKeyBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex, !m_send_mutex);
# 621 : : /** Process bytes in m_recv_buffer, while in GARB_GARBTERM state. */
# 622 : : bool ProcessReceivedGarbageBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
# 623 : : /** Process bytes in m_recv_buffer, while in GARBAUTH/VERSION/APP state. */
# 624 : : bool ProcessReceivedPacketBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
# 625 : :
# 626 : : public:
# 627 : : static constexpr uint32_t MAX_GARBAGE_LEN = 4095;
# 628 : :
# 629 : : /** Construct a V2 transport with securely generated random keys.
# 630 : : *
# 631 : : * @param[in] nodeid the node's NodeId (only for debug log output).
# 632 : : * @param[in] initiating whether we are the initiator side.
# 633 : : * @param[in] type_in the serialization type of returned CNetMessages.
# 634 : : * @param[in] version_in the serialization version of returned CNetMessages.
# 635 : : */
# 636 : : V2Transport(NodeId nodeid, bool initiating, int type_in, int version_in) noexcept;
# 637 : :
# 638 : : /** Construct a V2 transport with specified keys and garbage (test use only). */
# 639 : : V2Transport(NodeId nodeid, bool initiating, int type_in, int version_in, const CKey& key, Span<const std::byte> ent32, Span<const uint8_t> garbage) noexcept;
# 640 : :
# 641 : : // Receive side functions.
# 642 : : bool ReceivedMessageComplete() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
# 643 : : bool ReceivedBytes(Span<const uint8_t>& msg_bytes) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex, !m_send_mutex);
# 644 : : CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
# 645 : :
# 646 : : // Send side functions.
# 647 : : bool SetMessageToSend(CSerializedNetMsg& msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
# 648 : : BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
# 649 : : void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
# 650 : : size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
# 651 : : };
# 652 : :
# 653 : : struct CNodeOptions
# 654 : : {
# 655 : : NetPermissionFlags permission_flags = NetPermissionFlags::None;
# 656 : : std::unique_ptr<i2p::sam::Session> i2p_sam_session = nullptr;
# 657 : : bool prefer_evict = false;
# 658 : : size_t recv_flood_size{DEFAULT_MAXRECEIVEBUFFER * 1000};
# 659 : : };
# 660 : :
# 661 : : /** Information about a peer */
# 662 : : class CNode
# 663 : : {
# 664 : : public:
# 665 : : /** Transport serializer/deserializer. The receive side functions are only called under cs_vRecv, while
# 666 : : * the sending side functions are only called under cs_vSend. */
# 667 : : const std::unique_ptr<Transport> m_transport;
# 668 : :
# 669 : : const NetPermissionFlags m_permission_flags;
# 670 : :
# 671 : : /**
# 672 : : * Socket used for communication with the node.
# 673 : : * May not own a Sock object (after `CloseSocketDisconnect()` or during tests).
# 674 : : * `shared_ptr` (instead of `unique_ptr`) is used to avoid premature close of
# 675 : : * the underlying file descriptor by one thread while another thread is
# 676 : : * poll(2)-ing it for activity.
# 677 : : * @see https://github.com/bitcoin/bitcoin/issues/21744 for details.
# 678 : : */
# 679 : : std::shared_ptr<Sock> m_sock GUARDED_BY(m_sock_mutex);
# 680 : :
# 681 : : /** Sum of GetMemoryUsage of all vSendMsg entries. */
# 682 : : size_t m_send_memusage GUARDED_BY(cs_vSend){0};
# 683 : : /** Total number of bytes sent on the wire to this peer. */
# 684 : : uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
# 685 : : /** Messages still to be fed to m_transport->SetMessageToSend. */
# 686 : : std::deque<CSerializedNetMsg> vSendMsg GUARDED_BY(cs_vSend);
# 687 : : Mutex cs_vSend;
# 688 : : Mutex m_sock_mutex;
# 689 : : Mutex cs_vRecv;
# 690 : :
# 691 : : uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
# 692 : :
# 693 : : std::atomic<std::chrono::seconds> m_last_send{0s};
# 694 : : std::atomic<std::chrono::seconds> m_last_recv{0s};
# 695 : : //! Unix epoch time at peer connection
# 696 : : const std::chrono::seconds m_connected;
# 697 : : std::atomic<int64_t> nTimeOffset{0};
# 698 : : // Address of this peer
# 699 : : const CAddress addr;
# 700 : : // Bind address of our side of the connection
# 701 : : const CAddress addrBind;
# 702 : : const std::string m_addr_name;
# 703 : : //! Whether this peer is an inbound onion, i.e. connected via our Tor onion service.
# 704 : : const bool m_inbound_onion;
# 705 : : std::atomic<int> nVersion{0};
# 706 : : Mutex m_subver_mutex;
# 707 : : /**
# 708 : : * cleanSubVer is a sanitized string of the user agent byte array we read
# 709 : : * from the wire. This cleaned string can safely be logged or displayed.
# 710 : : */
# 711 : : std::string cleanSubVer GUARDED_BY(m_subver_mutex){};
# 712 : : const bool m_prefer_evict{false}; // This peer is preferred for eviction.
# 713 : 602410 : bool HasPermission(NetPermissionFlags permission) const {
# 714 : 602410 : return NetPermissions::HasFlag(m_permission_flags, permission);
# 715 : 602410 : }
# 716 : : /** fSuccessfullyConnected is set to true on receiving VERACK from the peer. */
# 717 : : std::atomic_bool fSuccessfullyConnected{false};
# 718 : : // Setting fDisconnect to true will cause the node to be disconnected the
# 719 : : // next time DisconnectNodes() runs
# 720 : : std::atomic_bool fDisconnect{false};
# 721 : : CSemaphoreGrant grantOutbound;
# 722 : : std::atomic<int> nRefCount{0};
# 723 : :
# 724 : : const uint64_t nKeyedNetGroup;
# 725 : : std::atomic_bool fPauseRecv{false};
# 726 : : std::atomic_bool fPauseSend{false};
# 727 : :
# 728 : : const ConnectionType m_conn_type;
# 729 : :
# 730 : : /** Move all messages from the received queue to the processing queue. */
# 731 : : void MarkReceivedMsgsForProcessing()
# 732 : : EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex);
# 733 : :
# 734 : : /** Poll the next message from the processing queue of this connection.
# 735 : : *
# 736 : : * Returns std::nullopt if the processing queue is empty, or a pair
# 737 : : * consisting of the message and a bool that indicates if the processing
# 738 : : * queue has more entries. */
# 739 : : std::optional<std::pair<CNetMessage, bool>> PollMessage()
# 740 : : EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex);
# 741 : :
# 742 : : /** Account for the total size of a sent message in the per msg type connection stats. */
# 743 : : void AccountForSentBytes(const std::string& msg_type, size_t sent_bytes)
# 744 : : EXCLUSIVE_LOCKS_REQUIRED(cs_vSend)
# 745 : 257589 : {
# 746 : 257589 : mapSendBytesPerMsgType[msg_type] += sent_bytes;
# 747 : 257589 : }
# 748 : :
# 749 : 261321 : bool IsOutboundOrBlockRelayConn() const {
# 750 [ - + ]: 261321 : switch (m_conn_type) {
# 751 [ + + ]: 2642 : case ConnectionType::OUTBOUND_FULL_RELAY:
# 752 [ + + ]: 3429 : case ConnectionType::BLOCK_RELAY:
# 753 : 3429 : return true;
# 754 [ + + ]: 142340 : case ConnectionType::INBOUND:
# 755 [ + + ]: 257872 : case ConnectionType::MANUAL:
# 756 [ + + ]: 257892 : case ConnectionType::ADDR_FETCH:
# 757 [ - + ]: 257892 : case ConnectionType::FEELER:
# 758 : 257892 : return false;
# 759 : 261321 : } // no default case, so the compiler can warn about missing cases
# 760 : :
# 761 : 0 : assert(false);
# 762 : 0 : }
# 763 : :
# 764 : 7027 : bool IsFullOutboundConn() const {
# 765 : 7027 : return m_conn_type == ConnectionType::OUTBOUND_FULL_RELAY;
# 766 : 7027 : }
# 767 : :
# 768 : 106 : bool IsManualConn() const {
# 769 : 106 : return m_conn_type == ConnectionType::MANUAL;
# 770 : 106 : }
# 771 : :
# 772 : : bool IsManualOrFullOutboundConn() const
# 773 : 892 : {
# 774 [ - + ]: 892 : switch (m_conn_type) {
# 775 [ + + ]: 338 : case ConnectionType::INBOUND:
# 776 [ + + ]: 342 : case ConnectionType::FEELER:
# 777 [ + + ]: 379 : case ConnectionType::BLOCK_RELAY:
# 778 [ + + ]: 385 : case ConnectionType::ADDR_FETCH:
# 779 : 385 : return false;
# 780 [ + + ]: 80 : case ConnectionType::OUTBOUND_FULL_RELAY:
# 781 [ + + ]: 507 : case ConnectionType::MANUAL:
# 782 : 507 : return true;
# 783 : 892 : } // no default case, so the compiler can warn about missing cases
# 784 : :
# 785 : 0 : assert(false);
# 786 : 0 : }
# 787 : :
# 788 : 283537 : bool IsBlockOnlyConn() const {
# 789 : 283537 : return m_conn_type == ConnectionType::BLOCK_RELAY;
# 790 : 283537 : }
# 791 : :
# 792 : 20903 : bool IsFeelerConn() const {
# 793 : 20903 : return m_conn_type == ConnectionType::FEELER;
# 794 : 20903 : }
# 795 : :
# 796 : 349648 : bool IsAddrFetchConn() const {
# 797 : 349648 : return m_conn_type == ConnectionType::ADDR_FETCH;
# 798 : 349648 : }
# 799 : :
# 800 : 34521 : bool IsInboundConn() const {
# 801 : 34521 : return m_conn_type == ConnectionType::INBOUND;
# 802 : 34521 : }
# 803 : :
# 804 : 1050 : bool ExpectServicesFromConn() const {
# 805 [ - + ]: 1050 : switch (m_conn_type) {
# 806 [ + + ]: 702 : case ConnectionType::INBOUND:
# 807 [ + + ]: 980 : case ConnectionType::MANUAL:
# 808 [ + + ]: 982 : case ConnectionType::FEELER:
# 809 : 982 : return false;
# 810 [ + + ]: 44 : case ConnectionType::OUTBOUND_FULL_RELAY:
# 811 [ + + ]: 65 : case ConnectionType::BLOCK_RELAY:
# 812 [ + + ]: 68 : case ConnectionType::ADDR_FETCH:
# 813 : 68 : return true;
# 814 : 1050 : } // no default case, so the compiler can warn about missing cases
# 815 : :
# 816 : 0 : assert(false);
# 817 : 0 : }
# 818 : :
# 819 : : /**
# 820 : : * Get network the peer connected through.
# 821 : : *
# 822 : : * Returns Network::NET_ONION for *inbound* onion connections,
# 823 : : * and CNetAddr::GetNetClass() otherwise. The latter cannot be used directly
# 824 : : * because it doesn't detect the former, and it's not the responsibility of
# 825 : : * the CNetAddr class to know the actual network a peer is connected through.
# 826 : : *
# 827 : : * @return network the peer connected through.
# 828 : : */
# 829 : : Network ConnectedThroughNetwork() const;
# 830 : :
# 831 : : // We selected peer as (compact blocks) high-bandwidth peer (BIP152)
# 832 : : std::atomic<bool> m_bip152_highbandwidth_to{false};
# 833 : : // Peer selected us as (compact blocks) high-bandwidth peer (BIP152)
# 834 : : std::atomic<bool> m_bip152_highbandwidth_from{false};
# 835 : :
# 836 : : /** Whether this peer provides all services that we want. Used for eviction decisions */
# 837 : : std::atomic_bool m_has_all_wanted_services{false};
# 838 : :
# 839 : : /** Whether we should relay transactions to this peer. This only changes
# 840 : : * from false to true. It will never change back to false. */
# 841 : : std::atomic_bool m_relays_txs{false};
# 842 : :
# 843 : : /** Whether this peer has loaded a bloom filter. Used only in inbound
# 844 : : * eviction logic. */
# 845 : : std::atomic_bool m_bloom_filter_loaded{false};
# 846 : :
# 847 : : /** UNIX epoch time of the last block received from this peer that we had
# 848 : : * not yet seen (e.g. not already received from another peer), that passed
# 849 : : * preliminary validity checks and was saved to disk, even if we don't
# 850 : : * connect the block or it eventually fails connection. Used as an inbound
# 851 : : * peer eviction criterium in CConnman::AttemptToEvictConnection. */
# 852 : : std::atomic<std::chrono::seconds> m_last_block_time{0s};
# 853 : :
# 854 : : /** UNIX epoch time of the last transaction received from this peer that we
# 855 : : * had not yet seen (e.g. not already received from another peer) and that
# 856 : : * was accepted into our mempool. Used as an inbound peer eviction criterium
# 857 : : * in CConnman::AttemptToEvictConnection. */
# 858 : : std::atomic<std::chrono::seconds> m_last_tx_time{0s};
# 859 : :
# 860 : : /** Last measured round-trip time. Used only for RPC/GUI stats/debugging.*/
# 861 : : std::atomic<std::chrono::microseconds> m_last_ping_time{0us};
# 862 : :
# 863 : : /** Lowest measured round-trip time. Used as an inbound peer eviction
# 864 : : * criterium in CConnman::AttemptToEvictConnection. */
# 865 : : std::atomic<std::chrono::microseconds> m_min_ping_time{std::chrono::microseconds::max()};
# 866 : :
# 867 : : CNode(NodeId id,
# 868 : : std::shared_ptr<Sock> sock,
# 869 : : const CAddress& addrIn,
# 870 : : uint64_t nKeyedNetGroupIn,
# 871 : : uint64_t nLocalHostNonceIn,
# 872 : : const CAddress& addrBindIn,
# 873 : : const std::string& addrNameIn,
# 874 : : ConnectionType conn_type_in,
# 875 : : bool inbound_onion,
# 876 : : CNodeOptions&& node_opts = {});
# 877 : : CNode(const CNode&) = delete;
# 878 : : CNode& operator=(const CNode&) = delete;
# 879 : :
# 880 : 2644234 : NodeId GetId() const {
# 881 : 2644234 : return id;
# 882 : 2644234 : }
# 883 : :
# 884 : 1101 : uint64_t GetLocalNonce() const {
# 885 : 1101 : return nLocalHostNonce;
# 886 : 1101 : }
# 887 : :
# 888 : : int GetRefCount() const
# 889 : 495 : {
# 890 : 495 : assert(nRefCount >= 0);
# 891 : 495 : return nRefCount;
# 892 : 495 : }
# 893 : :
# 894 : : /**
# 895 : : * Receive bytes from the buffer and deserialize them into messages.
# 896 : : *
# 897 : : * @param[in] msg_bytes The raw data
# 898 : : * @param[out] complete Set True if at least one message has been
# 899 : : * deserialized and is ready to be processed
# 900 : : * @return True if the peer should stay connected,
# 901 : : * False if the peer should be disconnected from.
# 902 : : */
# 903 : : bool ReceiveMsgBytes(Span<const uint8_t> msg_bytes, bool& complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv);
# 904 : :
# 905 : : void SetCommonVersion(int greatest_common_version)
# 906 : 1085 : {
# 907 : 1085 : Assume(m_greatest_common_version == INIT_PROTO_VERSION);
# 908 : 1085 : m_greatest_common_version = greatest_common_version;
# 909 : 1085 : }
# 910 : : int GetCommonVersion() const
# 911 : 1278244 : {
# 912 : 1278244 : return m_greatest_common_version;
# 913 : 1278244 : }
# 914 : :
# 915 : : CService GetAddrLocal() const EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex);
# 916 : : //! May not be called more than once
# 917 : : void SetAddrLocal(const CService& addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex);
# 918 : :
# 919 : : CNode* AddRef()
# 920 : 648115 : {
# 921 : 648115 : nRefCount++;
# 922 : 648115 : return this;
# 923 : 648115 : }
# 924 : :
# 925 : : void Release()
# 926 : 647535 : {
# 927 : 647535 : nRefCount--;
# 928 : 647535 : }
# 929 : :
# 930 : : void CloseSocketDisconnect() EXCLUSIVE_LOCKS_REQUIRED(!m_sock_mutex);
# 931 : :
# 932 : : void CopyStats(CNodeStats& stats) EXCLUSIVE_LOCKS_REQUIRED(!m_subver_mutex, !m_addr_local_mutex, !cs_vSend, !cs_vRecv);
# 933 : :
# 934 : 416 : std::string ConnectionTypeAsString() const { return ::ConnectionTypeAsString(m_conn_type); }
# 935 : :
# 936 : : /** A ping-pong round trip has completed successfully. Update latest and minimum ping times. */
# 937 : 1884 : void PongReceived(std::chrono::microseconds ping_time) {
# 938 : 1884 : m_last_ping_time = ping_time;
# 939 : 1884 : m_min_ping_time = std::min(m_min_ping_time.load(), ping_time);
# 940 : 1884 : }
# 941 : :
# 942 : : private:
# 943 : : const NodeId id;
# 944 : : const uint64_t nLocalHostNonce;
# 945 : : std::atomic<int> m_greatest_common_version{INIT_PROTO_VERSION};
# 946 : :
# 947 : : const size_t m_recv_flood_size;
# 948 : : std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
# 949 : :
# 950 : : Mutex m_msg_process_queue_mutex;
# 951 : : std::list<CNetMessage> m_msg_process_queue GUARDED_BY(m_msg_process_queue_mutex);
# 952 : : size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex){0};
# 953 : :
# 954 : : // Our address, as reported by the peer
# 955 : : CService addrLocal GUARDED_BY(m_addr_local_mutex);
# 956 : : mutable Mutex m_addr_local_mutex;
# 957 : :
# 958 : : mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend);
# 959 : : mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv);
# 960 : :
# 961 : : /**
# 962 : : * If an I2P session is created per connection (for outbound transient I2P
# 963 : : * connections) then it is stored here so that it can be destroyed when the
# 964 : : * socket is closed. I2P sessions involve a data/transport socket (in `m_sock`)
# 965 : : * and a control socket (in `m_i2p_sam_session`). For transient sessions, once
# 966 : : * the data socket is closed, the control socket is not going to be used anymore
# 967 : : * and is just taking up resources. So better close it as soon as `m_sock` is
# 968 : : * closed.
# 969 : : * Otherwise this unique_ptr is empty.
# 970 : : */
# 971 : : std::unique_ptr<i2p::sam::Session> m_i2p_sam_session GUARDED_BY(m_sock_mutex);
# 972 : : };
# 973 : :
# 974 : : /**
# 975 : : * Interface for message handling
# 976 : : */
# 977 : : class NetEventsInterface
# 978 : : {
# 979 : : public:
# 980 : : /** Mutex for anything that is only accessed via the msg processing thread */
# 981 : : static Mutex g_msgproc_mutex;
# 982 : :
# 983 : : /** Initialize a peer (setup state, queue any initial messages) */
# 984 : : virtual void InitializeNode(CNode& node, ServiceFlags our_services) = 0;
# 985 : :
# 986 : : /** Handle removal of a peer (clear state) */
# 987 : : virtual void FinalizeNode(const CNode& node) = 0;
# 988 : :
# 989 : : /**
# 990 : : * Process protocol messages received from a given node
# 991 : : *
# 992 : : * @param[in] pnode The node which we have received messages from.
# 993 : : * @param[in] interrupt Interrupt condition for processing threads
# 994 : : * @return True if there is more work to be done
# 995 : : */
# 996 : : virtual bool ProcessMessages(CNode* pnode, std::atomic<bool>& interrupt) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) = 0;
# 997 : :
# 998 : : /**
# 999 : : * Send queued protocol messages to a given node.
# 1000 : : *
# 1001 : : * @param[in] pnode The node which we are sending messages to.
# 1002 : : * @return True if there is more work to be done
# 1003 : : */
# 1004 : : virtual bool SendMessages(CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) = 0;
# 1005 : :
# 1006 : :
# 1007 : : protected:
# 1008 : : /**
# 1009 : : * Protected destructor so that instances can only be deleted by derived classes.
# 1010 : : * If that restriction is no longer desired, this should be made public and virtual.
# 1011 : : */
# 1012 : : ~NetEventsInterface() = default;
# 1013 : : };
# 1014 : :
# 1015 : : class CConnman
# 1016 : : {
# 1017 : : public:
# 1018 : :
# 1019 : : struct Options
# 1020 : : {
# 1021 : : ServiceFlags nLocalServices = NODE_NONE;
# 1022 : : int nMaxConnections = 0;
# 1023 : : int m_max_outbound_full_relay = 0;
# 1024 : : int m_max_outbound_block_relay = 0;
# 1025 : : int nMaxAddnode = 0;
# 1026 : : int nMaxFeeler = 0;
# 1027 : : CClientUIInterface* uiInterface = nullptr;
# 1028 : : NetEventsInterface* m_msgproc = nullptr;
# 1029 : : BanMan* m_banman = nullptr;
# 1030 : : unsigned int nSendBufferMaxSize = 0;
# 1031 : : unsigned int nReceiveFloodSize = 0;
# 1032 : : uint64_t nMaxOutboundLimit = 0;
# 1033 : : int64_t m_peer_connect_timeout = DEFAULT_PEER_CONNECT_TIMEOUT;
# 1034 : : std::vector<std::string> vSeedNodes;
# 1035 : : std::vector<NetWhitelistPermissions> vWhitelistedRange;
# 1036 : : std::vector<NetWhitebindPermissions> vWhiteBinds;
# 1037 : : std::vector<CService> vBinds;
# 1038 : : std::vector<CService> onion_binds;
# 1039 : : /// True if the user did not specify -bind= or -whitebind= and thus
# 1040 : : /// we should bind on `0.0.0.0` (IPv4) and `::` (IPv6).
# 1041 : : bool bind_on_any;
# 1042 : : bool m_use_addrman_outgoing = true;
# 1043 : : std::vector<std::string> m_specified_outgoing;
# 1044 : : std::vector<std::string> m_added_nodes;
# 1045 : : bool m_i2p_accept_incoming;
# 1046 : : };
# 1047 : :
# 1048 : : void Init(const Options& connOptions) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex, !m_total_bytes_sent_mutex)
# 1049 : 1863 : {
# 1050 : 1863 : AssertLockNotHeld(m_total_bytes_sent_mutex);
# 1051 : :
# 1052 : 1863 : nLocalServices = connOptions.nLocalServices;
# 1053 : 1863 : nMaxConnections = connOptions.nMaxConnections;
# 1054 : 1863 : m_max_outbound_full_relay = std::min(connOptions.m_max_outbound_full_relay, connOptions.nMaxConnections);
# 1055 : 1863 : m_max_outbound_block_relay = connOptions.m_max_outbound_block_relay;
# 1056 : 1863 : m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
# 1057 : 1863 : nMaxAddnode = connOptions.nMaxAddnode;
# 1058 : 1863 : nMaxFeeler = connOptions.nMaxFeeler;
# 1059 : 1863 : m_max_outbound = m_max_outbound_full_relay + m_max_outbound_block_relay + nMaxFeeler;
# 1060 : 1863 : m_client_interface = connOptions.uiInterface;
# 1061 : 1863 : m_banman = connOptions.m_banman;
# 1062 : 1863 : m_msgproc = connOptions.m_msgproc;
# 1063 : 1863 : nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
# 1064 : 1863 : nReceiveFloodSize = connOptions.nReceiveFloodSize;
# 1065 : 1863 : m_peer_connect_timeout = std::chrono::seconds{connOptions.m_peer_connect_timeout};
# 1066 : 1863 : {
# 1067 : 1863 : LOCK(m_total_bytes_sent_mutex);
# 1068 : 1863 : nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
# 1069 : 1863 : }
# 1070 : 1863 : vWhitelistedRange = connOptions.vWhitelistedRange;
# 1071 : 1863 : {
# 1072 : 1863 : LOCK(m_added_nodes_mutex);
# 1073 : 1863 : m_added_nodes = connOptions.m_added_nodes;
# 1074 : 1863 : }
# 1075 : 1863 : m_onion_binds = connOptions.onion_binds;
# 1076 : 1863 : }
# 1077 : :
# 1078 : : CConnman(uint64_t seed0, uint64_t seed1, AddrMan& addrman, const NetGroupManager& netgroupman,
# 1079 : : bool network_active = true);
# 1080 : :
# 1081 : : ~CConnman();
# 1082 : :
# 1083 : : bool Start(CScheduler& scheduler, const Options& options) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !m_added_nodes_mutex, !m_addr_fetches_mutex, !mutexMsgProc);
# 1084 : :
# 1085 : : void StopThreads();
# 1086 : : void StopNodes();
# 1087 : : void Stop()
# 1088 : 1673 : {
# 1089 : 1673 : StopThreads();
# 1090 : 1673 : StopNodes();
# 1091 : 1673 : };
# 1092 : :
# 1093 : : void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);
# 1094 : 114 : bool GetNetworkActive() const { return fNetworkActive; };
# 1095 : 33 : bool GetUseAddrmanOutgoing() const { return m_use_addrman_outgoing; };
# 1096 : : void SetNetworkActive(bool active);
# 1097 : : void OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant* grantOutbound, const char* strDest, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex);
# 1098 : : bool CheckIncomingNonce(uint64_t nonce);
# 1099 : :
# 1100 : : // alias for thread safety annotations only, not defined
# 1101 : : RecursiveMutex& GetNodesMutex() const LOCK_RETURNED(m_nodes_mutex);
# 1102 : :
# 1103 : : bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
# 1104 : :
# 1105 : : void PushMessage(CNode* pnode, CSerializedNetMsg&& msg) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
# 1106 : :
# 1107 : : using NodeFn = std::function<void(CNode*)>;
# 1108 : : void ForEachNode(const NodeFn& func)
# 1109 : 50561 : {
# 1110 : 50561 : LOCK(m_nodes_mutex);
# 1111 [ + + ]: 54274 : for (auto&& node : m_nodes) {
# 1112 [ + + ]: 54274 : if (NodeFullyConnected(node))
# 1113 : 54269 : func(node);
# 1114 : 54274 : }
# 1115 : 50561 : };
# 1116 : :
# 1117 : : void ForEachNode(const NodeFn& func) const
# 1118 : 0 : {
# 1119 : 0 : LOCK(m_nodes_mutex);
# 1120 : 0 : for (auto&& node : m_nodes) {
# 1121 : 0 : if (NodeFullyConnected(node))
# 1122 : 0 : func(node);
# 1123 : 0 : }
# 1124 : 0 : };
# 1125 : :
# 1126 : : // Addrman functions
# 1127 : : /**
# 1128 : : * Return all or many randomly selected addresses, optionally by network.
# 1129 : : *
# 1130 : : * @param[in] max_addresses Maximum number of addresses to return (0 = all).
# 1131 : : * @param[in] max_pct Maximum percentage of addresses to return (0 = all).
# 1132 : : * @param[in] network Select only addresses of this network (nullopt = all).
# 1133 : : */
# 1134 : : std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct, std::optional<Network> network) const;
# 1135 : : /**
# 1136 : : * Cache is used to minimize topology leaks, so it should
# 1137 : : * be used for all non-trusted calls, for example, p2p.
# 1138 : : * A non-malicious call (from RPC or a peer with addr permission) should
# 1139 : : * call the function without a parameter to avoid using the cache.
# 1140 : : */
# 1141 : : std::vector<CAddress> GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct);
# 1142 : :
# 1143 : : // This allows temporarily exceeding m_max_outbound_full_relay, with the goal of finding
# 1144 : : // a peer that is better than all our current peers.
# 1145 : : void SetTryNewOutboundPeer(bool flag);
# 1146 : : bool GetTryNewOutboundPeer() const;
# 1147 : :
# 1148 : : void StartExtraBlockRelayPeers();
# 1149 : :
# 1150 : : // Return the number of outbound peers we have in excess of our target (eg,
# 1151 : : // if we previously called SetTryNewOutboundPeer(true), and have since set
# 1152 : : // to false, we may have extra peers that we wish to disconnect). This may
# 1153 : : // return a value less than (num_outbound_connections - num_outbound_slots)
# 1154 : : // in cases where some outbound connections are not yet fully connected, or
# 1155 : : // not yet fully disconnected.
# 1156 : : int GetExtraFullOutboundCount() const;
# 1157 : : // Count the number of block-relay-only peers we have over our limit.
# 1158 : : int GetExtraBlockRelayCount() const;
# 1159 : :
# 1160 : : bool AddNode(const std::string& node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
# 1161 : : bool RemoveAddedNode(const std::string& node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
# 1162 : : std::vector<AddedNodeInfo> GetAddedNodeInfo() const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
# 1163 : :
# 1164 : : /**
# 1165 : : * Attempts to open a connection. Currently only used from tests.
# 1166 : : *
# 1167 : : * @param[in] address Address of node to try connecting to
# 1168 : : * @param[in] conn_type ConnectionType::OUTBOUND, ConnectionType::BLOCK_RELAY,
# 1169 : : * ConnectionType::ADDR_FETCH or ConnectionType::FEELER
# 1170 : : * @return bool Returns false if there are no available
# 1171 : : * slots for this connection:
# 1172 : : * - conn_type not a supported ConnectionType
# 1173 : : * - Max total outbound connection capacity filled
# 1174 : : * - Max connection capacity for type is filled
# 1175 : : */
# 1176 : : bool AddConnection(const std::string& address, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex);
# 1177 : :
# 1178 : : size_t GetNodeCount(ConnectionDirection) const;
# 1179 : : uint32_t GetMappedAS(const CNetAddr& addr) const;
# 1180 : : void GetNodeStats(std::vector<CNodeStats>& vstats) const;
# 1181 : : bool DisconnectNode(const std::string& node);
# 1182 : : bool DisconnectNode(const CSubNet& subnet);
# 1183 : : bool DisconnectNode(const CNetAddr& addr);
# 1184 : : bool DisconnectNode(NodeId id);
# 1185 : :
# 1186 : : //! Used to convey which local services we are offering peers during node
# 1187 : : //! connection.
# 1188 : : //!
# 1189 : : //! The data returned by this is used in CNode construction,
# 1190 : : //! which is used to advertise which services we are offering
# 1191 : : //! that peer during `net_processing.cpp:PushNodeVersion()`.
# 1192 : : ServiceFlags GetLocalServices() const;
# 1193 : :
# 1194 : : uint64_t GetMaxOutboundTarget() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
# 1195 : : std::chrono::seconds GetMaxOutboundTimeframe() const;
# 1196 : :
# 1197 : : //! check if the outbound target is reached
# 1198 : : //! if param historicalBlockServingLimit is set true, the function will
# 1199 : : //! response true if the limit for serving historical blocks has been reached
# 1200 : : bool OutboundTargetReached(bool historicalBlockServingLimit) const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
# 1201 : :
# 1202 : : //! response the bytes left in the current max outbound cycle
# 1203 : : //! in case of no limit, it will always response 0
# 1204 : : uint64_t GetOutboundTargetBytesLeft() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
# 1205 : :
# 1206 : : std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
# 1207 : :
# 1208 : : uint64_t GetTotalBytesRecv() const;
# 1209 : : uint64_t GetTotalBytesSent() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
# 1210 : :
# 1211 : : /** Get a unique deterministic randomizer. */
# 1212 : : CSipHasher GetDeterministicRandomizer(uint64_t id) const;
# 1213 : :
# 1214 : : void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);
# 1215 : :
# 1216 : : /** Return true if we should disconnect the peer for failing an inactivity check. */
# 1217 : : bool ShouldRunInactivityChecks(const CNode& node, std::chrono::seconds now) const;
# 1218 : :
# 1219 : : bool MultipleManualOrFullOutboundConns(Network net) const EXCLUSIVE_LOCKS_REQUIRED(m_nodes_mutex);
# 1220 : :
# 1221 : : private:
# 1222 : : struct ListenSocket {
# 1223 : : public:
# 1224 : : std::shared_ptr<Sock> sock;
# 1225 : 707 : inline void AddSocketPermissionFlags(NetPermissionFlags& flags) const { NetPermissions::AddFlag(flags, m_permissions); }
# 1226 : : ListenSocket(std::shared_ptr<Sock> sock_, NetPermissionFlags permissions_)
# 1227 : : : sock{sock_}, m_permissions{permissions_}
# 1228 : 817 : {
# 1229 : 817 : }
# 1230 : :
# 1231 : : private:
# 1232 : : NetPermissionFlags m_permissions;
# 1233 : : };
# 1234 : :
# 1235 : : //! returns the time left in the current max outbound cycle
# 1236 : : //! in case of no limit, it will always return 0
# 1237 : : std::chrono::seconds GetMaxOutboundTimeLeftInCycle_() const EXCLUSIVE_LOCKS_REQUIRED(m_total_bytes_sent_mutex);
# 1238 : :
# 1239 : : bool BindListenPort(const CService& bindAddr, bilingual_str& strError, NetPermissionFlags permissions);
# 1240 : : bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions);
# 1241 : : bool InitBinds(const Options& options);
# 1242 : :
# 1243 : : void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex, !m_unused_i2p_sessions_mutex);
# 1244 : : void AddAddrFetch(const std::string& strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex);
# 1245 : : void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex, !m_unused_i2p_sessions_mutex);
# 1246 : : void ThreadOpenConnections(std::vector<std::string> connect) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex, !m_added_nodes_mutex, !m_nodes_mutex, !m_unused_i2p_sessions_mutex);
# 1247 : : void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);
# 1248 : : void ThreadI2PAcceptIncoming();
# 1249 : : void AcceptConnection(const ListenSocket& hListenSocket);
# 1250 : :
# 1251 : : /**
# 1252 : : * Create a `CNode` object from a socket that has just been accepted and add the node to
# 1253 : : * the `m_nodes` member.
# 1254 : : * @param[in] sock Connected socket to communicate with the peer.
# 1255 : : * @param[in] permission_flags The peer's permissions.
# 1256 : : * @param[in] addr_bind The address and port at our side of the connection.
# 1257 : : * @param[in] addr The address and port at the peer's side of the connection.
# 1258 : : */
# 1259 : : void CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock,
# 1260 : : NetPermissionFlags permission_flags,
# 1261 : : const CAddress& addr_bind,
# 1262 : : const CAddress& addr);
# 1263 : :
# 1264 : : void DisconnectNodes();
# 1265 : : void NotifyNumConnectionsChanged();
# 1266 : : /** Return true if the peer is inactive and should be disconnected. */
# 1267 : : bool InactivityCheck(const CNode& node) const;
# 1268 : :
# 1269 : : /**
# 1270 : : * Generate a collection of sockets to check for IO readiness.
# 1271 : : * @param[in] nodes Select from these nodes' sockets.
# 1272 : : * @return sockets to check for readiness
# 1273 : : */
# 1274 : : Sock::EventsPerSock GenerateWaitSockets(Span<CNode* const> nodes);
# 1275 : :
# 1276 : : /**
# 1277 : : * Check connected and listening sockets for IO readiness and process them accordingly.
# 1278 : : */
# 1279 : : void SocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !mutexMsgProc);
# 1280 : :
# 1281 : : /**
# 1282 : : * Do the read/write for connected sockets that are ready for IO.
# 1283 : : * @param[in] nodes Nodes to process. The socket of each node is checked against `what`.
# 1284 : : * @param[in] events_per_sock Sockets that are ready for IO.
# 1285 : : */
# 1286 : : void SocketHandlerConnected(const std::vector<CNode*>& nodes,
# 1287 : : const Sock::EventsPerSock& events_per_sock)
# 1288 : : EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !mutexMsgProc);
# 1289 : :
# 1290 : : /**
# 1291 : : * Accept incoming connections, one from each read-ready listening socket.
# 1292 : : * @param[in] events_per_sock Sockets that are ready for IO.
# 1293 : : */
# 1294 : : void SocketHandlerListening(const Sock::EventsPerSock& events_per_sock);
# 1295 : :
# 1296 : : void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !mutexMsgProc);
# 1297 : : void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex, !m_nodes_mutex);
# 1298 : :
# 1299 : : uint64_t CalculateKeyedNetGroup(const CAddress& ad) const;
# 1300 : :
# 1301 : : CNode* FindNode(const CNetAddr& ip);
# 1302 : : CNode* FindNode(const CSubNet& subNet);
# 1303 : : CNode* FindNode(const std::string& addrName);
# 1304 : : CNode* FindNode(const CService& addr);
# 1305 : :
# 1306 : : /**
# 1307 : : * Determine whether we're already connected to a given address, in order to
# 1308 : : * avoid initiating duplicate connections.
# 1309 : : */
# 1310 : : bool AlreadyConnectedToAddress(const CAddress& addr);
# 1311 : :
# 1312 : : bool AttemptToEvictConnection();
# 1313 : : CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex);
# 1314 : : void AddWhitelistPermissionFlags(NetPermissionFlags& flags, const CNetAddr &addr) const;
# 1315 : :
# 1316 : : void DeleteNode(CNode* pnode);
# 1317 : :
# 1318 : : NodeId GetNewNodeId();
# 1319 : :
# 1320 : : /** (Try to) send data from node's vSendMsg. Returns (bytes_sent, data_left). */
# 1321 : : std::pair<size_t, bool> SocketSendData(CNode& node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend);
# 1322 : :
# 1323 : : void DumpAddresses();
# 1324 : :
# 1325 : : // Network stats
# 1326 : : void RecordBytesRecv(uint64_t bytes);
# 1327 : : void RecordBytesSent(uint64_t bytes) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
# 1328 : :
# 1329 : : /**
# 1330 : : Return reachable networks for which we have no addresses in addrman and therefore
# 1331 : : may require loading fixed seeds.
# 1332 : : */
# 1333 : : std::unordered_set<Network> GetReachableEmptyNetworks() const;
# 1334 : :
# 1335 : : /**
# 1336 : : * Return vector of current BLOCK_RELAY peers.
# 1337 : : */
# 1338 : : std::vector<CAddress> GetCurrentBlockRelayOnlyConns() const;
# 1339 : :
# 1340 : : /**
# 1341 : : * Search for a "preferred" network, a reachable network to which we
# 1342 : : * currently don't have any OUTBOUND_FULL_RELAY or MANUAL connections.
# 1343 : : * There needs to be at least one address in AddrMan for a preferred
# 1344 : : * network to be picked.
# 1345 : : *
# 1346 : : * @param[out] network Preferred network, if found.
# 1347 : : *
# 1348 : : * @return bool Whether a preferred network was found.
# 1349 : : */
# 1350 : : bool MaybePickPreferredNetwork(std::optional<Network>& network);
# 1351 : :
# 1352 : : // Whether the node should be passed out in ForEach* callbacks
# 1353 : : static bool NodeFullyConnected(const CNode* pnode);
# 1354 : :
# 1355 : : // Network usage totals
# 1356 : : mutable Mutex m_total_bytes_sent_mutex;
# 1357 : : std::atomic<uint64_t> nTotalBytesRecv{0};
# 1358 : : uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex) {0};
# 1359 : :
# 1360 : : // outbound limit & stats
# 1361 : : uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex) {0};
# 1362 : : std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex) {0};
# 1363 : : uint64_t nMaxOutboundLimit GUARDED_BY(m_total_bytes_sent_mutex);
# 1364 : :
# 1365 : : // P2P timeout in seconds
# 1366 : : std::chrono::seconds m_peer_connect_timeout;
# 1367 : :
# 1368 : : // Whitelisted ranges. Any node connecting from these is automatically
# 1369 : : // whitelisted (as well as those connecting to whitelisted binds).
# 1370 : : std::vector<NetWhitelistPermissions> vWhitelistedRange;
# 1371 : :
# 1372 : : unsigned int nSendBufferMaxSize{0};
# 1373 : : unsigned int nReceiveFloodSize{0};
# 1374 : :
# 1375 : : std::vector<ListenSocket> vhListenSocket;
# 1376 : : std::atomic<bool> fNetworkActive{true};
# 1377 : : bool fAddressesInitialized{false};
# 1378 : : AddrMan& addrman;
# 1379 : : const NetGroupManager& m_netgroupman;
# 1380 : : std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
# 1381 : : Mutex m_addr_fetches_mutex;
# 1382 : : std::vector<std::string> m_added_nodes GUARDED_BY(m_added_nodes_mutex);
# 1383 : : mutable Mutex m_added_nodes_mutex;
# 1384 : : std::vector<CNode*> m_nodes GUARDED_BY(m_nodes_mutex);
# 1385 : : std::list<CNode*> m_nodes_disconnected;
# 1386 : : mutable RecursiveMutex m_nodes_mutex;
# 1387 : : std::atomic<NodeId> nLastNodeId{0};
# 1388 : : unsigned int nPrevNodeCount{0};
# 1389 : :
# 1390 : : // Stores number of full-tx connections (outbound and manual) per network
# 1391 : : std::array<unsigned int, Network::NET_MAX> m_network_conn_counts GUARDED_BY(m_nodes_mutex) = {};
# 1392 : :
# 1393 : : /**
# 1394 : : * Cache responses to addr requests to minimize privacy leak.
# 1395 : : * Attack example: scraping addrs in real-time may allow an attacker
# 1396 : : * to infer new connections of the victim by detecting new records
# 1397 : : * with fresh timestamps (per self-announcement).
# 1398 : : */
# 1399 : : struct CachedAddrResponse {
# 1400 : : std::vector<CAddress> m_addrs_response_cache;
# 1401 : : std::chrono::microseconds m_cache_entry_expiration{0};
# 1402 : : };
# 1403 : :
# 1404 : : /**
# 1405 : : * Addr responses stored in different caches
# 1406 : : * per (network, local socket) prevent cross-network node identification.
# 1407 : : * If a node for example is multi-homed under Tor and IPv6,
# 1408 : : * a single cache (or no cache at all) would let an attacker
# 1409 : : * to easily detect that it is the same node by comparing responses.
# 1410 : : * Indexing by local socket prevents leakage when a node has multiple
# 1411 : : * listening addresses on the same network.
# 1412 : : *
# 1413 : : * The used memory equals to 1000 CAddress records (or around 40 bytes) per
# 1414 : : * distinct Network (up to 5) we have/had an inbound peer from,
# 1415 : : * resulting in at most ~196 KB. Every separate local socket may
# 1416 : : * add up to ~196 KB extra.
# 1417 : : */
# 1418 : : std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
# 1419 : :
# 1420 : : /**
# 1421 : : * Services this node offers.
# 1422 : : *
# 1423 : : * This data is replicated in each Peer instance we create.
# 1424 : : *
# 1425 : : * This data is not marked const, but after being set it should not
# 1426 : : * change.
# 1427 : : *
# 1428 : : * \sa Peer::our_services
# 1429 : : */
# 1430 : : ServiceFlags nLocalServices;
# 1431 : :
# 1432 : : std::unique_ptr<CSemaphore> semOutbound;
# 1433 : : std::unique_ptr<CSemaphore> semAddnode;
# 1434 : : int nMaxConnections;
# 1435 : :
# 1436 : : // How many full-relay (tx, block, addr) outbound peers we want
# 1437 : : int m_max_outbound_full_relay;
# 1438 : :
# 1439 : : // How many block-relay only outbound peers we want
# 1440 : : // We do not relay tx or addr messages with these peers
# 1441 : : int m_max_outbound_block_relay;
# 1442 : :
# 1443 : : int nMaxAddnode;
# 1444 : : int nMaxFeeler;
# 1445 : : int m_max_outbound;
# 1446 : : bool m_use_addrman_outgoing;
# 1447 : : CClientUIInterface* m_client_interface;
# 1448 : : NetEventsInterface* m_msgproc;
# 1449 : : /** Pointer to this node's banman. May be nullptr - check existence before dereferencing. */
# 1450 : : BanMan* m_banman;
# 1451 : :
# 1452 : : /**
# 1453 : : * Addresses that were saved during the previous clean shutdown. We'll
# 1454 : : * attempt to make block-relay-only connections to them.
# 1455 : : */
# 1456 : : std::vector<CAddress> m_anchors;
# 1457 : :
# 1458 : : /** SipHasher seeds for deterministic randomness */
# 1459 : : const uint64_t nSeed0, nSeed1;
# 1460 : :
# 1461 : : /** flag for waking the message processor. */
# 1462 : : bool fMsgProcWake GUARDED_BY(mutexMsgProc);
# 1463 : :
# 1464 : : std::condition_variable condMsgProc;
# 1465 : : Mutex mutexMsgProc;
# 1466 : : std::atomic<bool> flagInterruptMsgProc{false};
# 1467 : :
# 1468 : : /**
# 1469 : : * This is signaled when network activity should cease.
# 1470 : : * A pointer to it is saved in `m_i2p_sam_session`, so make sure that
# 1471 : : * the lifetime of `interruptNet` is not shorter than
# 1472 : : * the lifetime of `m_i2p_sam_session`.
# 1473 : : */
# 1474 : : CThreadInterrupt interruptNet;
# 1475 : :
# 1476 : : /**
# 1477 : : * I2P SAM session.
# 1478 : : * Used to accept incoming and make outgoing I2P connections from a persistent
# 1479 : : * address.
# 1480 : : */
# 1481 : : std::unique_ptr<i2p::sam::Session> m_i2p_sam_session;
# 1482 : :
# 1483 : : std::thread threadDNSAddressSeed;
# 1484 : : std::thread threadSocketHandler;
# 1485 : : std::thread threadOpenAddedConnections;
# 1486 : : std::thread threadOpenConnections;
# 1487 : : std::thread threadMessageHandler;
# 1488 : : std::thread threadI2PAcceptIncoming;
# 1489 : :
# 1490 : : /** flag for deciding to connect to an extra outbound peer,
# 1491 : : * in excess of m_max_outbound_full_relay
# 1492 : : * This takes the place of a feeler connection */
# 1493 : : std::atomic_bool m_try_another_outbound_peer;
# 1494 : :
# 1495 : : /** flag for initiating extra block-relay-only peer connections.
# 1496 : : * this should only be enabled after initial chain sync has occurred,
# 1497 : : * as these connections are intended to be short-lived and low-bandwidth.
# 1498 : : */
# 1499 : : std::atomic_bool m_start_extra_block_relay_peers{false};
# 1500 : :
# 1501 : : /**
# 1502 : : * A vector of -bind=<address>:<port>=onion arguments each of which is
# 1503 : : * an address and port that are designated for incoming Tor connections.
# 1504 : : */
# 1505 : : std::vector<CService> m_onion_binds;
# 1506 : :
# 1507 : : /**
# 1508 : : * Mutex protecting m_i2p_sam_sessions.
# 1509 : : */
# 1510 : : Mutex m_unused_i2p_sessions_mutex;
# 1511 : :
# 1512 : : /**
# 1513 : : * A pool of created I2P SAM transient sessions that should be used instead
# 1514 : : * of creating new ones in order to reduce the load on the I2P network.
# 1515 : : * Creating a session in I2P is not cheap, thus if this is not empty, then
# 1516 : : * pick an entry from it instead of creating a new session. If connecting to
# 1517 : : * a host fails, then the created session is put to this pool for reuse.
# 1518 : : */
# 1519 : : std::queue<std::unique_ptr<i2p::sam::Session>> m_unused_i2p_sessions GUARDED_BY(m_unused_i2p_sessions_mutex);
# 1520 : :
# 1521 : : /**
# 1522 : : * Cap on the size of `m_unused_i2p_sessions`, to ensure it does not
# 1523 : : * unexpectedly use too much memory.
# 1524 : : */
# 1525 : : static constexpr size_t MAX_UNUSED_I2P_SESSIONS_SIZE{10};
# 1526 : :
# 1527 : : /**
# 1528 : : * RAII helper to atomically create a copy of `m_nodes` and add a reference
# 1529 : : * to each of the nodes. The nodes are released when this object is destroyed.
# 1530 : : */
# 1531 : : class NodesSnapshot
# 1532 : : {
# 1533 : : public:
# 1534 : : explicit NodesSnapshot(const CConnman& connman, bool shuffle)
# 1535 : 382918 : {
# 1536 : 382918 : {
# 1537 : 382918 : LOCK(connman.m_nodes_mutex);
# 1538 : 382918 : m_nodes_copy = connman.m_nodes;
# 1539 [ + + ]: 647043 : for (auto& node : m_nodes_copy) {
# 1540 : 647043 : node->AddRef();
# 1541 : 647043 : }
# 1542 : 382918 : }
# 1543 [ + + ]: 382918 : if (shuffle) {
# 1544 : 165528 : Shuffle(m_nodes_copy.begin(), m_nodes_copy.end(), FastRandomContext{});
# 1545 : 165528 : }
# 1546 : 382918 : }
# 1547 : :
# 1548 : : ~NodesSnapshot()
# 1549 : 382918 : {
# 1550 [ + + ]: 647043 : for (auto& node : m_nodes_copy) {
# 1551 : 647043 : node->Release();
# 1552 : 647043 : }
# 1553 : 382918 : }
# 1554 : :
# 1555 : : const std::vector<CNode*>& Nodes() const
# 1556 : 600297 : {
# 1557 : 600297 : return m_nodes_copy;
# 1558 : 600297 : }
# 1559 : :
# 1560 : : private:
# 1561 : : std::vector<CNode*> m_nodes_copy;
# 1562 : : };
# 1563 : :
# 1564 : : friend struct ConnmanTestMsg;
# 1565 : : };
# 1566 : :
# 1567 : : /** Dump binary message to file, with timestamp */
# 1568 : : void CaptureMessageToFile(const CAddress& addr,
# 1569 : : const std::string& msg_type,
# 1570 : : Span<const unsigned char> data,
# 1571 : : bool is_incoming);
# 1572 : :
# 1573 : : /** Defaults to `CaptureMessageToFile()`, but can be overridden by unit tests. */
# 1574 : : extern std::function<void(const CAddress& addr,
# 1575 : : const std::string& msg_type,
# 1576 : : Span<const unsigned char> data,
# 1577 : : bool is_incoming)>
# 1578 : : CaptureMessage;
# 1579 : :
# 1580 : : #endif // BITCOIN_NET_H
|