Line data Source code
1 : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : // Copyright (c) 2009-2021 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 <consensus/amount.h>
14 : #include <consensus/params.h>
15 : #include <fs.h>
16 : #include <crypto/siphash.h>
17 : #include <hash.h>
18 : #include <i2p.h>
19 : #include <limitedmap.h>
20 : #include <net_permissions.h>
21 : #include <netaddress.h>
22 : #include <netbase.h>
23 : #include <netgroup.h>
24 : #include <node/connection_types.h>
25 : #include <policy/feerate.h>
26 : #include <protocol.h>
27 : #include <random.h>
28 : #include <saltedhasher.h>
29 : #include <span.h>
30 : #include <streams.h>
31 : #include <sync.h>
32 : #include <uint256.h>
33 : #include <util/check.h>
34 : #include <util/edge.h>
35 : #include <util/sock.h>
36 : #include <util/system.h>
37 : #include <util/threadinterrupt.h>
38 : #include <util/wpipe.h>
39 :
40 : #include <atomic>
41 : #include <condition_variable>
42 : #include <cstdint>
43 : #include <deque>
44 : #include <functional>
45 : #include <list>
46 : #include <map>
47 : #include <memory>
48 : #include <optional>
49 : #include <queue>
50 : #include <thread>
51 : #include <type_traits>
52 : #include <unordered_set>
53 : #include <vector>
54 :
55 : class AddrMan;
56 : class BanMan;
57 : class CConnman;
58 : class CDeterministicMNList;
59 : class CDeterministicMNManager;
60 : class CMasternodeMetaMan;
61 : class CMasternodeSync;
62 : class CNode;
63 : class CScheduler;
64 : struct bilingual_str;
65 : struct NodeEvictionCandidate;
66 :
67 : /** Default for -whitelistrelay. */
68 : static const bool DEFAULT_WHITELISTRELAY = true;
69 : /** Default for -whitelistforcerelay. */
70 : static const bool DEFAULT_WHITELISTFORCERELAY = false;
71 :
72 : /** Time after which to disconnect, after waiting for a ping response (or inactivity). */
73 : static constexpr std::chrono::minutes TIMEOUT_INTERVAL{20};
74 : /** Time to wait since m_connected before disconnecting a probe node. */
75 : static const auto PROBE_WAIT_INTERVAL{5s};
76 : /** Minimum time between warnings printed to log. */
77 : static const int WARNING_INTERVAL = 10 * 60;
78 : /** Run the feeler connection loop once every 2 minutes. **/
79 : static constexpr auto FEELER_INTERVAL = 2min;
80 : /** The maximum number of entries in an 'inv' protocol message */
81 : static const unsigned int MAX_INV_SZ = 50000;
82 : /** Run the extra block-relay-only connection loop once every 5 minutes. **/
83 : static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL = 5min;
84 : /** Maximum length of incoming protocol messages (no message over 3 MiB is currently acceptable). */
85 : static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 3 * 1024 * 1024;
86 : /** Maximum length of the user agent string in `version` message */
87 : static const unsigned int MAX_SUBVERSION_LENGTH = 256;
88 : /** Maximum number of automatic outgoing nodes over which we'll relay everything (blocks, tx, addrs, etc) */
89 : static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS = 8;
90 : /** Maximum number of addnode outgoing nodes */
91 : static const int MAX_ADDNODE_CONNECTIONS = 8;
92 : /** Eviction protection time for incoming connections */
93 : static const auto INBOUND_EVICTION_PROTECTION_TIME{1s};
94 : /** Maximum number of block-relay-only outgoing connections */
95 : static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS = 2;
96 : /** Maximum number of onion connections we will try harder to connect to / protect from eviction */
97 : static const int MAX_DESIRED_ONION_CONNECTIONS = 2;
98 : /** Maximum number of feeler connections */
99 : static const int MAX_FEELER_CONNECTIONS = 1;
100 : /** -listen default */
101 : static const bool DEFAULT_LISTEN = true;
102 : /** The maximum number of peer connections to maintain.
103 : * Masternodes are forced to accept at least this many connections
104 : */
105 : static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
106 : /** The default for -maxuploadtarget. 0 = Unlimited */
107 : static const std::string DEFAULT_MAX_UPLOAD_TARGET{"0M"};
108 : /** Default for blocks only*/
109 : static const bool DEFAULT_BLOCKSONLY = false;
110 : /** -peertimeout default */
111 : static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
112 : /** Number of file descriptors required for message capture **/
113 : static const int NUM_FDS_MESSAGE_CAPTURE = 1;
114 : /** Interval for ASMap Health Check **/
115 : static constexpr std::chrono::hours ASMAP_HEALTH_CHECK_INTERVAL{24};
116 :
117 : static constexpr bool DEFAULT_FORCEDNSSEED{false};
118 : static constexpr bool DEFAULT_DNSSEED{true};
119 : static constexpr bool DEFAULT_FIXEDSEEDS{true};
120 : static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
121 : static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
122 :
123 : static constexpr bool DEFAULT_V2_TRANSPORT{true};
124 :
125 : typedef int64_t NodeId;
126 :
127 : struct AddedNodeParams {
128 : std::string m_added_node;
129 : bool m_use_v2transport;
130 : };
131 :
132 0 : struct AddedNodeInfo {
133 : AddedNodeParams m_params;
134 : CService resolvedAddress;
135 : bool fConnected;
136 : bool fInbound;
137 : };
138 :
139 : class CNodeStats;
140 : class CClientUIInterface;
141 :
142 : struct CSerializedNetMsg {
143 432 : CSerializedNetMsg() = default;
144 188 : CSerializedNetMsg(CSerializedNetMsg&&) = default;
145 2 : CSerializedNetMsg& operator=(CSerializedNetMsg&&) = default;
146 : // No implicit copying, only moves.
147 : CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
148 : CSerializedNetMsg& operator=(const CSerializedNetMsg&) = delete;
149 :
150 0 : CSerializedNetMsg Copy() const
151 : {
152 0 : CSerializedNetMsg copy;
153 0 : copy.data = data;
154 0 : copy.m_type = m_type;
155 0 : return copy;
156 0 : }
157 :
158 : std::vector<unsigned char> data;
159 : std::string m_type;
160 :
161 : /** Compute total memory usage of this object (own memory + any dynamic memory). */
162 : size_t GetMemoryUsage() const noexcept;
163 : };
164 :
165 : /**
166 : * Look up IP addresses from all interfaces on the machine and add them to the
167 : * list of local addresses to self-advertise.
168 : * The loopback interface is skipped.
169 : */
170 : void Discover();
171 :
172 : uint16_t GetListenPort();
173 :
174 : enum
175 : {
176 : LOCAL_NONE, // unknown
177 : LOCAL_IF, // address a local interface listens on
178 : LOCAL_BIND, // address explicit bound to
179 : LOCAL_MAPPED, // address reported by UPnP or NAT-PMP
180 : LOCAL_MANUAL, // address explicitly specified (-externalip=)
181 :
182 : LOCAL_MAX
183 : };
184 :
185 : /** Returns a local address that we should advertise to this peer. */
186 : std::optional<CService> GetLocalAddrForPeer(CNode& node);
187 :
188 : bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
189 : bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
190 : void RemoveLocal(const CService& addr);
191 : bool SeenLocal(const CService& addr);
192 : bool IsLocal(const CService& addr);
193 : CService GetLocalAddress(const CNode& peer);
194 :
195 : extern bool fDiscover;
196 : extern bool fListen;
197 :
198 : /** Subversion as sent to the P2P network in `version` messages */
199 : extern std::string strSubVersion;
200 :
201 : struct LocalServiceInfo {
202 : int nScore;
203 : uint16_t nPort;
204 : };
205 :
206 : extern GlobalMutex g_maplocalhost_mutex;
207 : extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(g_maplocalhost_mutex);
208 :
209 : extern const std::string NET_MESSAGE_TYPE_OTHER;
210 : using mapMsgTypeSize = std::map</* message type */ std::string, /* total bytes */ uint64_t>;
211 :
212 0 : class CNodeStats
213 : {
214 : public:
215 : NodeId nodeid;
216 : std::chrono::seconds m_last_send;
217 : std::chrono::seconds m_last_recv;
218 : std::chrono::seconds m_last_tx_time;
219 : std::chrono::seconds m_last_block_time;
220 : std::chrono::seconds m_connected;
221 : int64_t nTimeOffset;
222 : std::string m_addr_name;
223 : int nVersion;
224 : std::string cleanSubVer;
225 : bool fInbound;
226 : bool m_bip152_highbandwidth_to;
227 : bool m_bip152_highbandwidth_from;
228 : int m_starting_height;
229 : uint64_t nSendBytes;
230 : mapMsgTypeSize mapSendBytesPerMsgType;
231 : uint64_t nRecvBytes;
232 : mapMsgTypeSize mapRecvBytesPerMsgType;
233 : NetPermissionFlags m_permission_flags;
234 : std::chrono::microseconds m_last_ping_time;
235 : std::chrono::microseconds m_min_ping_time;
236 : // Our address, as reported by the peer
237 : std::string addrLocal;
238 : // Address of this peer
239 : CAddress addr;
240 : // Bind address of our side of the connection
241 : CAddress addrBind;
242 : // Network the peer connected through
243 : Network m_network;
244 : uint32_t m_mapped_as;
245 : // In case this is a verified MN, this value is the proTx of the MN
246 : uint256 verifiedProRegTxHash;
247 : // In case this is a verified MN, this value is the hashed operator pubkey of the MN
248 : uint256 verifiedPubKeyHash;
249 : bool m_masternode_connection;
250 : ConnectionType m_conn_type;
251 : /** Transport protocol type. */
252 : TransportProtocolType m_transport_type;
253 : /** BIP324 session id string in hex, if any. */
254 : std::string m_session_id;
255 : };
256 :
257 :
258 : /** Transport protocol agnostic message container.
259 : * Ideally it should only contain receive time, payload,
260 : * type and size.
261 : */
262 : class CNetMessage {
263 : public:
264 : CDataStream m_recv; //!< received message data
265 254 : std::chrono::microseconds m_time{0}; //!< time of message receipt
266 254 : uint32_t m_message_size{0}; //!< size of the payload
267 254 : uint32_t m_raw_message_size{0}; //!< used wire size of the message (including header/checksum)
268 : std::string m_type;
269 :
270 508 : CNetMessage(CDataStream&& recv_in) : m_recv(std::move(recv_in)) {}
271 : // Only one CNetMessage object will exist for the same message on either
272 : // the receive or processing queue. For performance reasons we therefore
273 : // delete the copy constructor and assignment operator to avoid the
274 : // possibility of copying CNetMessage objects.
275 754 : CNetMessage(CNetMessage&&) = default;
276 : CNetMessage(const CNetMessage&) = delete;
277 : CNetMessage& operator=(CNetMessage&&) = default;
278 : CNetMessage& operator=(const CNetMessage&) = delete;
279 :
280 2 : void SetVersion(int nVersionIn)
281 : {
282 2 : m_recv.SetVersion(nVersionIn);
283 2 : }
284 : };
285 :
286 : /** The Transport converts one connection's sent messages to wire bytes, and received bytes back. */
287 : class Transport {
288 : public:
289 196 : virtual ~Transport() {}
290 :
291 : struct Info
292 : {
293 : TransportProtocolType transport_type;
294 : std::optional<uint256> session_id;
295 : };
296 :
297 : /** Retrieve information about this transport. */
298 : virtual Info GetInfo() const noexcept = 0;
299 :
300 : // 1. Receiver side functions, for decoding bytes received on the wire into transport protocol
301 : // agnostic CNetMessage (message type & payload) objects.
302 :
303 : /** Returns true if the current message is complete (so GetReceivedMessage can be called). */
304 : virtual bool ReceivedMessageComplete() const = 0;
305 :
306 : /** Feed wire bytes to the transport.
307 : *
308 : * @return false if some bytes were invalid, in which case the transport can't be used anymore.
309 : *
310 : * Consumed bytes are chopped off the front of msg_bytes.
311 : */
312 : virtual bool ReceivedBytes(Span<const uint8_t>& msg_bytes) = 0;
313 :
314 : /** Retrieve a completed message from transport.
315 : *
316 : * This can only be called when ReceivedMessageComplete() is true.
317 : *
318 : * If reject_message=true is returned the message itself is invalid, but (other than false
319 : * returned by ReceivedBytes) the transport is not in an inconsistent state.
320 : */
321 : virtual CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) = 0;
322 :
323 : // 2. Sending side functions, for converting messages into bytes to be sent over the wire.
324 :
325 : /** Set the next message to send.
326 : *
327 : * If no message can currently be set (perhaps because the previous one is not yet done being
328 : * sent), returns false, and msg will be unmodified. Otherwise msg is enqueued (and
329 : * possibly moved-from) and true is returned.
330 : */
331 : virtual bool SetMessageToSend(CSerializedNetMsg& msg) noexcept = 0;
332 :
333 : /** Return type for GetBytesToSend, consisting of:
334 : * - Span<const uint8_t> to_send: span of bytes to be sent over the wire (possibly empty).
335 : * - bool more: whether there will be more bytes to be sent after the ones in to_send are
336 : * all sent (as signaled by MarkBytesSent()).
337 : * - const std::string& m_type: message type on behalf of which this is being sent
338 : * ("" for bytes that are not on behalf of any message).
339 : */
340 : using BytesToSend = std::tuple<
341 : Span<const uint8_t> /*to_send*/,
342 : bool /*more*/,
343 : const std::string& /*m_type*/
344 : >;
345 :
346 : /** Get bytes to send on the wire, if any, along with other information about it.
347 : *
348 : * As a const function, it does not modify the transport's observable state, and is thus safe
349 : * to be called multiple times.
350 : *
351 : * @param[in] have_next_message If true, the "more" return value reports whether more will
352 : * be sendable after a SetMessageToSend call. It is set by the caller when they know
353 : * they have another message ready to send, and only care about what happens
354 : * after that. The have_next_message argument only affects this "more" return value
355 : * and nothing else.
356 : *
357 : * Effectively, there are three possible outcomes about whether there are more bytes
358 : * to send:
359 : * - Yes: the transport itself has more bytes to send later. For example, for
360 : * V1Transport this happens during the sending of the header of a
361 : * message, when there is a non-empty payload that follows.
362 : * - No: the transport itself has no more bytes to send, but will have bytes to
363 : * send if handed a message through SetMessageToSend. In V1Transport this
364 : * happens when sending the payload of a message.
365 : * - Blocked: the transport itself has no more bytes to send, and is also incapable
366 : * of sending anything more at all now, if it were handed another
367 : * message to send. This occurs in V2Transport before the handshake is
368 : * complete, as the encryption ciphers are not set up for sending
369 : * messages before that point.
370 : *
371 : * The boolean 'more' is true for Yes, false for Blocked, and have_next_message
372 : * controls what is returned for No.
373 : *
374 : * @return a BytesToSend object. The to_send member returned acts as a stream which is only
375 : * ever appended to. This means that with the exception of MarkBytesSent (which pops
376 : * bytes off the front of later to_sends), operations on the transport can only append
377 : * to what is being returned. Also note that m_type and to_send refer to data that is
378 : * internal to the transport, and calling any non-const function on this object may
379 : * invalidate them.
380 : */
381 : virtual BytesToSend GetBytesToSend(bool have_next_message) const noexcept = 0;
382 :
383 : /** Report how many bytes returned by the last GetBytesToSend() have been sent.
384 : *
385 : * bytes_sent cannot exceed to_send.size() of the last GetBytesToSend() result.
386 : *
387 : * If bytes_sent=0, this call has no effect.
388 : */
389 : virtual void MarkBytesSent(size_t bytes_sent) noexcept = 0;
390 :
391 : /** Return the memory usage of this transport attributable to buffered data to send. */
392 : virtual size_t GetSendMemoryUsage() const noexcept = 0;
393 :
394 : /** Set the peer's protocol version (used for v2 short ID negotiation).
395 : *
396 : * This is a no-op for V1 transport. V2 transport uses it to determine which
397 : * short IDs are supported by the peer.
398 : */
399 26 : virtual void SetPeerVersion(int version) noexcept {}
400 :
401 : // 3. Miscellaneous functions.
402 :
403 : /** Whether upon disconnections, a reconnect with V1 is warranted. */
404 : virtual bool ShouldReconnectV1() const noexcept = 0;
405 : };
406 :
407 : class V1Transport final : public Transport
408 : {
409 : private:
410 : CMessageHeader::MessageStartChars m_magic_bytes;
411 : const NodeId m_node_id; // Only for logging
412 : mutable Mutex m_recv_mutex; //!< Lock for receive state
413 : mutable CHash256 hasher GUARDED_BY(m_recv_mutex);
414 : mutable uint256 data_hash GUARDED_BY(m_recv_mutex);
415 : bool in_data GUARDED_BY(m_recv_mutex); // parsing header (false) or data (true)
416 : CDataStream hdrbuf GUARDED_BY(m_recv_mutex); // partially received header
417 : CMessageHeader hdr GUARDED_BY(m_recv_mutex); // complete header
418 : CDataStream vRecv GUARDED_BY(m_recv_mutex); // received message data
419 : unsigned int nHdrPos GUARDED_BY(m_recv_mutex);
420 : unsigned int nDataPos GUARDED_BY(m_recv_mutex);
421 :
422 : const uint256& GetMessageHash() const EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
423 : int readHeader(Span<const uint8_t> msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
424 : int readData(Span<const uint8_t> msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
425 :
426 120 : void Reset() EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex) {
427 120 : AssertLockHeld(m_recv_mutex);
428 120 : vRecv.clear();
429 120 : hdrbuf.clear();
430 120 : hdrbuf.resize(24);
431 120 : in_data = false;
432 120 : nHdrPos = 0;
433 120 : nDataPos = 0;
434 120 : data_hash.SetNull();
435 120 : hasher.Reset();
436 120 : }
437 :
438 11 : bool CompleteInternal() const noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
439 : {
440 11 : AssertLockHeld(m_recv_mutex);
441 11 : if (!in_data) return false;
442 7 : return hdr.nMessageSize == nDataPos;
443 11 : }
444 :
445 : /** Lock for sending state. */
446 : mutable Mutex m_send_mutex;
447 : /** The header of the message currently being sent. */
448 : std::vector<uint8_t> m_header_to_send GUARDED_BY(m_send_mutex);
449 : /** The data of the message currently being sent. */
450 : CSerializedNetMsg m_message_to_send GUARDED_BY(m_send_mutex);
451 : /** Whether we're currently sending header bytes or message bytes. */
452 : bool m_sending_header GUARDED_BY(m_send_mutex) {false};
453 : /** How many bytes have been sent so far (from m_header_to_send, or from m_message_to_send.data). */
454 : size_t m_bytes_sent GUARDED_BY(m_send_mutex) {0};
455 :
456 : public:
457 : V1Transport(const NodeId node_id, int nTypeIn, int nVersionIn) noexcept;
458 :
459 9 : bool ReceivedMessageComplete() const override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
460 : {
461 9 : AssertLockNotHeld(m_recv_mutex);
462 18 : return WITH_LOCK(m_recv_mutex, return CompleteInternal());
463 : }
464 :
465 : Info GetInfo() const noexcept override;
466 :
467 8 : bool ReceivedBytes(Span<const uint8_t>& msg_bytes) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
468 : {
469 8 : AssertLockNotHeld(m_recv_mutex);
470 8 : LOCK(m_recv_mutex);
471 8 : int ret = in_data ? readData(msg_bytes) : readHeader(msg_bytes);
472 8 : if (ret < 0) {
473 0 : Reset();
474 0 : } else {
475 8 : msg_bytes = msg_bytes.subspan(ret);
476 : }
477 8 : return ret >= 0;
478 8 : }
479 :
480 : CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
481 :
482 : bool SetMessageToSend(CSerializedNetMsg& msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
483 : BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
484 : void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
485 : size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
486 0 : bool ShouldReconnectV1() const noexcept override { return false; }
487 : };
488 :
489 : class V2Transport final : public Transport
490 : {
491 : private:
492 : /** Contents of the version packet to send. BIP324 stipulates that senders should leave this
493 : * empty, and receivers should ignore it. Future extensions can change what is sent as long as
494 : * an empty version packet contents is interpreted as no extensions supported. */
495 : static constexpr std::array<std::byte, 0> VERSION_CONTENTS = {};
496 :
497 : /** The length of the V1 prefix to match bytes initially received by responders with to
498 : * determine if their peer is speaking V1 or V2. */
499 : static constexpr size_t V1_PREFIX_LEN = 16;
500 :
501 : // The sender side and receiver side of V2Transport are state machines that are transitioned
502 : // through, based on what has been received. The receive state corresponds to the contents of,
503 : // and bytes received to, the receive buffer. The send state controls what can be appended to
504 : // the send buffer and what can be sent from it.
505 :
506 : /** State type that defines the current contents of the receive buffer and/or how the next
507 : * received bytes added to it will be interpreted.
508 : *
509 : * Diagram:
510 : *
511 : * start(responder)
512 : * |
513 : * | start(initiator) /---------\
514 : * | | | |
515 : * v v v |
516 : * KEY_MAYBE_V1 -> KEY -> GARB_GARBTERM -> VERSION -> APP -> APP_READY
517 : * |
518 : * \-------> V1
519 : */
520 : enum class RecvState : uint8_t {
521 : /** (Responder only) either v2 public key or v1 header.
522 : *
523 : * This is the initial state for responders, before data has been received to distinguish
524 : * v1 from v2 connections. When that happens, the state becomes either KEY (for v2) or V1
525 : * (for v1). */
526 : KEY_MAYBE_V1,
527 :
528 : /** Public key.
529 : *
530 : * This is the initial state for initiators, during which the other side's public key is
531 : * received. When that information arrives, the ciphers get initialized and the state
532 : * becomes GARB_GARBTERM. */
533 : KEY,
534 :
535 : /** Garbage and garbage terminator.
536 : *
537 : * Whenever a byte is received, the last 16 bytes are compared with the expected garbage
538 : * terminator. When that happens, the state becomes VERSION. If no matching terminator is
539 : * received in 4111 bytes (4095 for the maximum garbage length, and 16 bytes for the
540 : * terminator), the connection aborts. */
541 : GARB_GARBTERM,
542 :
543 : /** Version packet.
544 : *
545 : * A packet is received, and decrypted/verified. If that fails, the connection aborts. The
546 : * first received packet in this state (whether it's a decoy or not) is expected to
547 : * authenticate the garbage received during the GARB_GARBTERM state as associated
548 : * authenticated data (AAD). The first non-decoy packet in this state is interpreted as
549 : * version negotiation (currently, that means ignoring the contents, but it can be used for
550 : * negotiating future extensions), and afterwards the state becomes APP. */
551 : VERSION,
552 :
553 : /** Application packet.
554 : *
555 : * A packet is received, and decrypted/verified. If that succeeds, the state becomes
556 : * APP_READY and the decrypted contents is kept in m_recv_decode_buffer until it is
557 : * retrieved as a message by GetMessage(). */
558 : APP,
559 :
560 : /** Nothing (an application packet is available for GetMessage()).
561 : *
562 : * Nothing can be received in this state. When the message is retrieved by GetMessage,
563 : * the state becomes APP again. */
564 : APP_READY,
565 :
566 : /** Nothing (this transport is using v1 fallback).
567 : *
568 : * All receive operations are redirected to m_v1_fallback. */
569 : V1,
570 : };
571 :
572 : /** State type that controls the sender side.
573 : *
574 : * Diagram:
575 : *
576 : * start(responder)
577 : * |
578 : * | start(initiator)
579 : * | |
580 : * v v
581 : * MAYBE_V1 -> AWAITING_KEY -> READY
582 : * |
583 : * \-----> V1
584 : */
585 : enum class SendState : uint8_t {
586 : /** (Responder only) Not sending until v1 or v2 is detected.
587 : *
588 : * This is the initial state for responders. The send buffer is empty.
589 : * When the receiver determines whether this
590 : * is a V1 or V2 connection, the sender state becomes AWAITING_KEY (for v2) or V1 (for v1).
591 : */
592 : MAYBE_V1,
593 :
594 : /** Waiting for the other side's public key.
595 : *
596 : * This is the initial state for initiators. The public key and garbage is sent out. When
597 : * the receiver receives the other side's public key and transitions to GARB_GARBTERM, the
598 : * sender state becomes READY. */
599 : AWAITING_KEY,
600 :
601 : /** Normal sending state.
602 : *
603 : * In this state, the ciphers are initialized, so packets can be sent. When this state is
604 : * entered, the garbage terminator and version packet are appended to the send buffer (in
605 : * addition to the key and garbage which may still be there). In this state a message can be
606 : * provided if the send buffer is empty. */
607 : READY,
608 :
609 : /** This transport is using v1 fallback.
610 : *
611 : * All send operations are redirected to m_v1_fallback. */
612 : V1,
613 : };
614 :
615 : /** Cipher state. */
616 : BIP324Cipher m_cipher;
617 : /** Whether we are the initiator side. */
618 : const bool m_initiating;
619 : /** NodeId (for debug logging). */
620 : const NodeId m_nodeid;
621 : /** Encapsulate a V1Transport to fall back to. */
622 : V1Transport m_v1_fallback;
623 :
624 : /** Lock for receiver-side fields. */
625 : mutable Mutex m_recv_mutex ACQUIRED_BEFORE(m_send_mutex);
626 : /** In {VERSION, APP}, the decrypted packet length, if m_recv_buffer.size() >=
627 : * BIP324Cipher::LENGTH_LEN. Unspecified otherwise. */
628 : uint32_t m_recv_len GUARDED_BY(m_recv_mutex) {0};
629 : /** Receive buffer; meaning is determined by m_recv_state. */
630 : std::vector<uint8_t> m_recv_buffer GUARDED_BY(m_recv_mutex);
631 : /** AAD expected in next received packet (currently used only for garbage). */
632 : std::vector<uint8_t> m_recv_aad GUARDED_BY(m_recv_mutex);
633 : /** Buffer to put decrypted contents in, for converting to CNetMessage. */
634 : std::vector<uint8_t> m_recv_decode_buffer GUARDED_BY(m_recv_mutex);
635 : /** Deserialization type. */
636 : const int m_recv_type;
637 : /** Deserialization version number. */
638 : const int m_recv_version;
639 : /** Current receiver state. */
640 : RecvState m_recv_state GUARDED_BY(m_recv_mutex);
641 :
642 : /** Lock for sending-side fields. If both sending and receiving fields are accessed,
643 : * m_recv_mutex must be acquired before m_send_mutex. */
644 : mutable Mutex m_send_mutex ACQUIRED_AFTER(m_recv_mutex);
645 : /** The send buffer; meaning is determined by m_send_state. */
646 : std::vector<uint8_t> m_send_buffer GUARDED_BY(m_send_mutex);
647 : /** How many bytes from the send buffer have been sent so far. */
648 : uint32_t m_send_pos GUARDED_BY(m_send_mutex) {0};
649 : /** The garbage sent, or to be sent (MAYBE_V1 and AWAITING_KEY state only). */
650 : std::vector<uint8_t> m_send_garbage GUARDED_BY(m_send_mutex);
651 : /** Type of the message being sent. */
652 : std::string m_send_type GUARDED_BY(m_send_mutex);
653 : /** Current sender state. */
654 : SendState m_send_state GUARDED_BY(m_send_mutex);
655 : /** Whether we've sent at least 24 bytes (which would trigger disconnect for V1 peers). */
656 : bool m_sent_v1_header_worth GUARDED_BY(m_send_mutex) {false};
657 : /** Peer's protocol version for encoding decisions (e.g., v2 short ID negotiation). */
658 : int m_peer_version GUARDED_BY(m_send_mutex) {INIT_PROTO_VERSION};
659 :
660 : /** Change the receive state. */
661 : void SetReceiveState(RecvState recv_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
662 : /** Change the send state. */
663 : void SetSendState(SendState send_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex);
664 : /** Given a packet's contents, find the message type (if valid), and strip it from contents. */
665 : static std::optional<std::string> GetMessageType(Span<const uint8_t>& contents) noexcept;
666 : /** Determine how many received bytes can be processed in one go (not allowed in V1 state). */
667 : size_t GetMaxBytesToProcess() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
668 : /** Put our public key + garbage in the send buffer. */
669 : void StartSendingHandshake() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex);
670 : /** Process bytes in m_recv_buffer, while in KEY_MAYBE_V1 state. */
671 : void ProcessReceivedMaybeV1Bytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex, !m_send_mutex);
672 : /** Process bytes in m_recv_buffer, while in KEY state. */
673 : bool ProcessReceivedKeyBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex, !m_send_mutex);
674 : /** Process bytes in m_recv_buffer, while in GARB_GARBTERM state. */
675 : bool ProcessReceivedGarbageBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
676 : /** Process bytes in m_recv_buffer, while in VERSION/APP state. */
677 : bool ProcessReceivedPacketBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
678 :
679 : public:
680 : static constexpr uint32_t MAX_GARBAGE_LEN = 4095;
681 :
682 : /** Construct a V2 transport with securely generated random keys.
683 : *
684 : * @param[in] nodeid the node's NodeId (only for debug log output).
685 : * @param[in] initiating whether we are the initiator side.
686 : * @param[in] type_in the serialization type of returned CNetMessages.
687 : * @param[in] version_in the serialization version of returned CNetMessages.
688 : */
689 : V2Transport(NodeId nodeid, bool initiating, int type_in, int version_in) noexcept;
690 :
691 : /** Construct a V2 transport with specified keys and garbage (test use only). */
692 : V2Transport(NodeId nodeid, bool initiating, int type_in, int version_in, const CKey& key, Span<const std::byte> ent32, std::vector<uint8_t> garbage) noexcept;
693 :
694 : // Receive side functions.
695 : bool ReceivedMessageComplete() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
696 : bool ReceivedBytes(Span<const uint8_t>& msg_bytes) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex, !m_send_mutex);
697 : CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
698 :
699 : // Send side functions.
700 : bool SetMessageToSend(CSerializedNetMsg& msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
701 : BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
702 : void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
703 : size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
704 : void SetPeerVersion(int version) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
705 :
706 : // Miscellaneous functions.
707 : bool ShouldReconnectV1() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex, !m_send_mutex);
708 : Info GetInfo() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
709 : };
710 :
711 : struct CNodeOptions
712 : {
713 : NetPermissionFlags permission_flags = NetPermissionFlags::None;
714 : std::unique_ptr<i2p::sam::Session> i2p_sam_session = nullptr;
715 : bool prefer_evict = false;
716 : size_t recv_flood_size{DEFAULT_MAXRECEIVEBUFFER * 1000};
717 : bool use_v2transport = false;
718 : };
719 :
720 : /** Information about a peer */
721 : class CNode
722 : {
723 : public:
724 : /** Transport serializer/deserializer. The receive side functions are only called under cs_vRecv, while
725 : * the sending side functions are only called under cs_vSend. */
726 : const std::unique_ptr<Transport> m_transport;
727 :
728 : const NetPermissionFlags m_permission_flags;
729 :
730 : /**
731 : * Socket used for communication with the node.
732 : * May not own a Sock object (after `CloseSocketDisconnect()` or during tests).
733 : * `shared_ptr` (instead of `unique_ptr`) is used to avoid premature close of
734 : * the underlying file descriptor by one thread while another thread is
735 : * poll(2)-ing it for activity.
736 : * @see https://github.com/bitcoin/bitcoin/issues/21744 for details.
737 : */
738 : std::shared_ptr<Sock> m_sock GUARDED_BY(m_sock_mutex);
739 :
740 : /** Sum of GetMemoryUsage of all vSendMsg entries. */
741 : size_t m_send_memusage GUARDED_BY(cs_vSend){0};
742 : /** Total number of bytes sent on the wire to this peer. */
743 : uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
744 : /** Messages still to be fed to m_transport->SetMessageToSend. */
745 : std::deque<CSerializedNetMsg> vSendMsg GUARDED_BY(cs_vSend);
746 : std::atomic<size_t> nSendMsgSize{0};
747 : mutable Mutex cs_vSend;
748 : Mutex m_sock_mutex;
749 : mutable Mutex cs_vRecv;
750 :
751 : uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
752 :
753 : std::atomic<std::chrono::seconds> m_last_send{0s};
754 : std::atomic<std::chrono::seconds> m_last_recv{0s};
755 : //! Unix epoch time at peer connection
756 : const std::chrono::seconds m_connected;
757 : std::atomic<int64_t> nTimeOffset{0};
758 : std::atomic<int64_t> nLastWarningTime{0};
759 : std::atomic<std::chrono::seconds> nTimeFirstMessageReceived{0s};
760 : std::atomic<bool> fFirstMessageIsMNAUTH{false};
761 : // Address of this peer
762 : const CAddress addr;
763 : // Bind address of our side of the connection
764 : const CAddress addrBind;
765 : const std::string m_addr_name;
766 : /** The pszDest argument provided to ConnectNode(). Only used for reconnections. */
767 : const std::string m_dest;
768 : //! Whether this peer is an inbound onion, i.e. connected via our Tor onion service.
769 : const bool m_inbound_onion;
770 : std::atomic<int> nNumWarningsSkipped{0};
771 : std::atomic<int> nVersion{0};
772 : mutable Mutex m_subver_mutex;
773 : /**
774 : * cleanSubVer is a sanitized string of the user agent byte array we read
775 : * from the wire. This cleaned string can safely be logged or displayed.
776 : */
777 : std::string cleanSubVer GUARDED_BY(m_subver_mutex){};
778 : const bool m_prefer_evict{false}; // This peer is preferred for eviction.
779 9 : bool HasPermission(NetPermissionFlags permission) const {
780 9 : return NetPermissions::HasFlag(m_permission_flags, permission);
781 : }
782 : /** fSuccessfullyConnected is set to true on receiving VERACK from the peer. */
783 : std::atomic_bool fSuccessfullyConnected{false};
784 : // Setting fDisconnect to true will cause the node to be disconnected the
785 : // next time DisconnectNodes() runs
786 : std::atomic_bool fDisconnect{false};
787 : std::atomic<SteadyClock::time_point> nDisconnectLingerTime{SteadyClock::time_point{}};
788 : std::atomic_bool fSocketShutdown{false};
789 : std::atomic_bool fOtherSideDisconnected { false };
790 : // If 'true' this node will be disconnected on CMasternodeMan::ProcessMasternodeConnections()
791 : std::atomic<bool> m_masternode_connection{false};
792 : /**
793 : * If 'true' this node will be disconnected after MNAUTH (outbound only) or
794 : * after PROBE_WAIT_INTERVAL seconds since m_connected
795 : */
796 : std::atomic<bool> m_masternode_probe_connection{false};
797 : // If 'true', we identified it as an intra-quorum relay connection
798 : std::atomic<bool> m_masternode_iqr_connection{false};
799 : CSemaphoreGrant grantOutbound;
800 : std::atomic<int> nRefCount{0};
801 :
802 : const uint64_t nKeyedNetGroup;
803 :
804 : std::atomic_bool fPauseRecv{false};
805 : std::atomic_bool fPauseSend{false};
806 :
807 : std::atomic_bool fHasRecvData{false};
808 : std::atomic_bool fCanSendData{false};
809 :
810 : const ConnectionType m_conn_type;
811 :
812 : /** Move all messages from the received queue to the processing queue. */
813 : void MarkReceivedMsgsForProcessing()
814 : EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex);
815 :
816 : /** Poll the next message from the processing queue of this connection.
817 : *
818 : * Returns std::nullopt if the processing queue is empty, or a pair
819 : * consisting of the message and a bool that indicates if the processing
820 : * queue has more entries. */
821 : std::optional<std::pair<CNetMessage, bool>> PollMessage()
822 : EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex);
823 :
824 : /** Account for the total size of a sent message in the per msg type connection stats. */
825 0 : void AccountForSentBytes(const std::string& msg_type, size_t sent_bytes)
826 : EXCLUSIVE_LOCKS_REQUIRED(cs_vSend)
827 : {
828 0 : mapSendBytesPerMsgType[msg_type] += sent_bytes;
829 0 : }
830 :
831 : /** Update a supplied map with bytes sent for each msg type for this node */
832 0 : void UpdateSentMapWithStats(mapMsgTypeSize& map_sentbytes_msg)
833 : EXCLUSIVE_LOCKS_REQUIRED(cs_vSend)
834 : {
835 0 : for (auto& [msg_type, bytes] : mapSendBytesPerMsgType) {
836 0 : map_sentbytes_msg[msg_type] += bytes;
837 : }
838 0 : }
839 :
840 : /** Update a supplied map with bytes recv for each msg type for this node */
841 0 : void UpdateRecvMapWithStats(mapMsgTypeSize& map_recvbytes_msg)
842 : EXCLUSIVE_LOCKS_REQUIRED(cs_vRecv)
843 : {
844 0 : for (auto& [msg_type, bytes] : mapRecvBytesPerMsgType) {
845 0 : map_recvbytes_msg[msg_type] += bytes;
846 : }
847 0 : }
848 :
849 : /**
850 : * Get network the peer connected through.
851 : *
852 : * Returns Network::NET_ONION for *inbound* onion connections,
853 : * and CNetAddr::GetNetClass() otherwise. The latter cannot be used directly
854 : * because it doesn't detect the former, and it's not the responsibility of
855 : * the CNetAddr class to know the actual network a peer is connected through.
856 : *
857 : * @return network the peer connected through.
858 : */
859 : Network ConnectedThroughNetwork() const;
860 :
861 6 : bool IsOutboundOrBlockRelayConn() const {
862 6 : switch (m_conn_type) {
863 : case ConnectionType::OUTBOUND_FULL_RELAY:
864 : case ConnectionType::BLOCK_RELAY:
865 5 : return true;
866 : case ConnectionType::INBOUND:
867 : case ConnectionType::MANUAL:
868 : case ConnectionType::ADDR_FETCH:
869 : case ConnectionType::FEELER:
870 1 : return false;
871 : } // no default case, so the compiler can warn about missing cases
872 :
873 0 : assert(false);
874 6 : }
875 :
876 105 : bool IsFullOutboundConn() const {
877 105 : return m_conn_type == ConnectionType::OUTBOUND_FULL_RELAY;
878 : }
879 :
880 8 : bool IsManualConn() const {
881 8 : return m_conn_type == ConnectionType::MANUAL;
882 : }
883 :
884 23 : bool IsManualOrFullOutboundConn() const
885 : {
886 23 : switch (m_conn_type) {
887 : case ConnectionType::INBOUND:
888 : case ConnectionType::FEELER:
889 : case ConnectionType::BLOCK_RELAY:
890 : case ConnectionType::ADDR_FETCH:
891 8 : return false;
892 : case ConnectionType::OUTBOUND_FULL_RELAY:
893 : case ConnectionType::MANUAL:
894 15 : return true;
895 : } // no default case, so the compiler can warn about missing cases
896 :
897 0 : assert(false);
898 23 : }
899 :
900 132 : bool IsBlockOnlyConn() const {
901 132 : return m_conn_type == ConnectionType::BLOCK_RELAY;
902 : }
903 :
904 27 : bool IsFeelerConn() const {
905 27 : return m_conn_type == ConnectionType::FEELER;
906 : }
907 :
908 12 : bool IsAddrFetchConn() const {
909 12 : return m_conn_type == ConnectionType::ADDR_FETCH;
910 : }
911 :
912 132 : bool IsInboundConn() const {
913 132 : return m_conn_type == ConnectionType::INBOUND;
914 : }
915 :
916 2 : bool ExpectServicesFromConn() const {
917 2 : switch (m_conn_type) {
918 : case ConnectionType::INBOUND:
919 : case ConnectionType::MANUAL:
920 : case ConnectionType::FEELER:
921 0 : return false;
922 : case ConnectionType::OUTBOUND_FULL_RELAY:
923 : case ConnectionType::BLOCK_RELAY:
924 : case ConnectionType::ADDR_FETCH:
925 2 : return true;
926 : } // no default case, so the compiler can warn about missing cases
927 :
928 0 : assert(false);
929 2 : }
930 :
931 : public:
932 : /** Whether this peer connected through a privacy network. */
933 : [[nodiscard]] bool IsConnectedThroughPrivacyNet() const;
934 :
935 : // We selected peer as (compact blocks) high-bandwidth peer (BIP152)
936 : std::atomic<bool> m_bip152_highbandwidth_to{false};
937 : // Peer selected us as (compact blocks) high-bandwidth peer (BIP152)
938 : std::atomic<bool> m_bip152_highbandwidth_from{false};
939 :
940 : /** Whether this peer provides all services that we want. Used for eviction decisions */
941 : std::atomic_bool m_has_all_wanted_services{false};
942 :
943 : /** Whether we should relay transactions to this peer. This only changes
944 : * from false to true. It will never change back to false. */
945 : std::atomic_bool m_relays_txs{false};
946 :
947 : /** Whether this peer has loaded a bloom filter. Used only in inbound
948 : * eviction logic. */
949 : std::atomic_bool m_bloom_filter_loaded{false};
950 :
951 : /** UNIX epoch time of the last block received from this peer that we had
952 : * not yet seen (e.g. not already received from another peer), that passed
953 : * preliminary validity checks and was saved to disk, even if we don't
954 : * connect the block or it eventually fails connection. Used as an inbound
955 : * peer eviction criterium in CConnman::AttemptToEvictConnection. */
956 : std::atomic<std::chrono::seconds> m_last_block_time{0s};
957 :
958 : /** UNIX epoch time of the last transaction received from this peer that we
959 : * had not yet seen (e.g. not already received from another peer) and that
960 : * was accepted into our mempool. Used as an inbound peer eviction criterium
961 : * in CConnman::AttemptToEvictConnection. */
962 : std::atomic<std::chrono::seconds> m_last_tx_time{0s};
963 :
964 : /** Last measured round-trip time. Used only for RPC/GUI stats/debugging.*/
965 : std::atomic<std::chrono::microseconds> m_last_ping_time{0us};
966 :
967 : /** Lowest measured round-trip time. Used as an inbound peer eviction
968 : * criterium in CConnman::AttemptToEvictConnection. */
969 : std::atomic<std::chrono::microseconds> m_min_ping_time{std::chrono::microseconds::max()};
970 :
971 : // If true, we will send him CoinJoin queue messages
972 : std::atomic<bool> fSendDSQueue{false};
973 :
974 : // If true, we will send him all quorum related messages, even if he is not a member of our quorums
975 : std::atomic<bool> qwatch{false};
976 :
977 : bool IsBlockRelayOnly() const;
978 :
979 : CNode(NodeId id,
980 : std::shared_ptr<Sock> sock,
981 : const CAddress &addrIn,
982 : uint64_t nKeyedNetGroupIn,
983 : uint64_t nLocalHostNonceIn,
984 : const CAddress &addrBindIn,
985 : const std::string &addrNameIn,
986 : ConnectionType conn_type_in,
987 : bool inbound_onion,
988 : CNodeOptions&& node_opts = {});
989 : CNode(const CNode&) = delete;
990 : CNode& operator=(const CNode&) = delete;
991 :
992 358 : NodeId GetId() const {
993 358 : return id;
994 : }
995 :
996 21 : uint64_t GetLocalNonce() const {
997 21 : return nLocalHostNonce;
998 : }
999 :
1000 0 : int GetRefCount() const
1001 : {
1002 0 : assert(nRefCount >= 0);
1003 0 : return nRefCount;
1004 : }
1005 :
1006 : /**
1007 : * Receive bytes from the buffer and deserialize them into messages.
1008 : *
1009 : * @param[in] msg_bytes The raw data
1010 : * @param[out] complete Set True if at least one message has been
1011 : * deserialized and is ready to be processed
1012 : * @return True if the peer should stay connected,
1013 : * False if the peer should be disconnected from.
1014 : */
1015 : bool ReceiveMsgBytes(Span<const uint8_t> msg_bytes, bool& complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv);
1016 :
1017 26 : void SetCommonVersion(int greatest_common_version)
1018 : {
1019 26 : Assume(m_greatest_common_version == INIT_PROTO_VERSION);
1020 26 : m_greatest_common_version = greatest_common_version;
1021 : // Also update transport's peer version for v2 short ID negotiation
1022 26 : m_transport->SetPeerVersion(greatest_common_version);
1023 26 : }
1024 21 : int GetCommonVersion() const
1025 : {
1026 21 : return m_greatest_common_version;
1027 : }
1028 :
1029 : CService GetAddrLocal() const EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex);
1030 : //! May not be called more than once
1031 : void SetAddrLocal(const CService& addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex);
1032 :
1033 0 : CNode* AddRef()
1034 : {
1035 0 : nRefCount++;
1036 0 : return this;
1037 : }
1038 :
1039 0 : void Release()
1040 : {
1041 0 : nRefCount--;
1042 0 : }
1043 :
1044 : void CloseSocketDisconnect(CConnman* connman) EXCLUSIVE_LOCKS_REQUIRED(!m_sock_mutex);
1045 :
1046 : void CopyStats(CNodeStats& stats) const EXCLUSIVE_LOCKS_REQUIRED(!m_subver_mutex, !m_addr_local_mutex, !cs_vSend, !cs_vRecv, !cs_mnauth);
1047 :
1048 2 : std::string ConnectionTypeAsString() const { return ::ConnectionTypeAsString(m_conn_type); }
1049 :
1050 : /** A ping-pong round trip has completed successfully. Update latest and minimum ping times. */
1051 0 : void PongReceived(std::chrono::microseconds ping_time) {
1052 0 : m_last_ping_time = ping_time;
1053 0 : m_min_ping_time = std::min(m_min_ping_time.load(), ping_time);
1054 0 : }
1055 :
1056 : std::string GetLogString() const;
1057 :
1058 15 : bool CanRelay() const { return !m_masternode_connection || m_masternode_iqr_connection; }
1059 :
1060 0 : uint256 GetSentMNAuthChallenge() const EXCLUSIVE_LOCKS_REQUIRED(!cs_mnauth) {
1061 0 : LOCK(cs_mnauth);
1062 0 : return sentMNAuthChallenge;
1063 0 : }
1064 :
1065 0 : uint256 GetReceivedMNAuthChallenge() const EXCLUSIVE_LOCKS_REQUIRED(!cs_mnauth) {
1066 0 : LOCK(cs_mnauth);
1067 0 : return receivedMNAuthChallenge;
1068 0 : }
1069 :
1070 9 : uint256 GetVerifiedProRegTxHash() const EXCLUSIVE_LOCKS_REQUIRED(!cs_mnauth) {
1071 9 : LOCK(cs_mnauth);
1072 9 : return verifiedProRegTxHash;
1073 9 : }
1074 :
1075 0 : uint256 GetVerifiedPubKeyHash() const EXCLUSIVE_LOCKS_REQUIRED(!cs_mnauth) {
1076 0 : LOCK(cs_mnauth);
1077 0 : return verifiedPubKeyHash;
1078 0 : }
1079 :
1080 21 : void SetSentMNAuthChallenge(const uint256& newSentMNAuthChallenge) EXCLUSIVE_LOCKS_REQUIRED(!cs_mnauth) {
1081 21 : LOCK(cs_mnauth);
1082 21 : sentMNAuthChallenge = newSentMNAuthChallenge;
1083 21 : }
1084 :
1085 0 : void SetReceivedMNAuthChallenge(const uint256& newReceivedMNAuthChallenge) EXCLUSIVE_LOCKS_REQUIRED(!cs_mnauth) {
1086 0 : LOCK(cs_mnauth);
1087 0 : receivedMNAuthChallenge = newReceivedMNAuthChallenge;
1088 0 : }
1089 :
1090 0 : void SetVerifiedProRegTxHash(const uint256& newVerifiedProRegTxHash) EXCLUSIVE_LOCKS_REQUIRED(!cs_mnauth) {
1091 0 : LOCK(cs_mnauth);
1092 0 : verifiedProRegTxHash = newVerifiedProRegTxHash;
1093 0 : }
1094 :
1095 0 : void SetVerifiedPubKeyHash(const uint256& newVerifiedPubKeyHash) EXCLUSIVE_LOCKS_REQUIRED(!cs_mnauth) {
1096 0 : LOCK(cs_mnauth);
1097 0 : verifiedPubKeyHash = newVerifiedPubKeyHash;
1098 0 : }
1099 :
1100 : private:
1101 : const NodeId id;
1102 : const uint64_t nLocalHostNonce;
1103 : std::atomic<int> m_greatest_common_version{INIT_PROTO_VERSION};
1104 :
1105 : const size_t m_recv_flood_size;
1106 : std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
1107 :
1108 : Mutex m_msg_process_queue_mutex;
1109 : std::list<CNetMessage> m_msg_process_queue GUARDED_BY(m_msg_process_queue_mutex);
1110 : size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex){0};
1111 : std::list<CNetMessage> m_msg_quorum_queue GUARDED_BY(m_msg_process_queue_mutex);
1112 : size_t m_msg_quorum_queue_size GUARDED_BY(m_msg_process_queue_mutex){0};
1113 : size_t m_quorum_msg_count_since_normal GUARDED_BY(m_msg_process_queue_mutex){0};
1114 :
1115 : // Our address, as reported by the peer
1116 : CService addrLocal GUARDED_BY(m_addr_local_mutex);
1117 : mutable Mutex m_addr_local_mutex;
1118 :
1119 : // Challenge sent in VERSION to be answered with MNAUTH (only happens between MNs)
1120 : mutable Mutex cs_mnauth;
1121 : uint256 sentMNAuthChallenge GUARDED_BY(cs_mnauth);
1122 : uint256 receivedMNAuthChallenge GUARDED_BY(cs_mnauth);
1123 : uint256 verifiedProRegTxHash GUARDED_BY(cs_mnauth);
1124 : uint256 verifiedPubKeyHash GUARDED_BY(cs_mnauth);
1125 :
1126 : mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend);
1127 : mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv);
1128 :
1129 : /**
1130 : * If an I2P session is created per connection (for outbound transient I2P
1131 : * connections) then it is stored here so that it can be destroyed when the
1132 : * socket is closed. I2P sessions involve a data/transport socket (in `m_sock`)
1133 : * and a control socket (in `m_i2p_sam_session`). For transient sessions, once
1134 : * the data socket is closed, the control socket is not going to be used anymore
1135 : * and is just taking up resources. So better close it as soon as `m_sock` is
1136 : * closed.
1137 : * Otherwise this unique_ptr is empty.
1138 : */
1139 : std::unique_ptr<i2p::sam::Session> m_i2p_sam_session GUARDED_BY(m_sock_mutex);
1140 : };
1141 :
1142 : /**
1143 : * Interface for message handling
1144 : */
1145 : class NetEventsInterface
1146 : {
1147 : public:
1148 : /** Mutex for anything that is only accessed via the msg processing thread */
1149 : static Mutex g_msgproc_mutex;
1150 :
1151 : /** Initialize a peer (setup state, queue any initial messages) */
1152 : virtual void InitializeNode(CNode& node, ServiceFlags our_services) = 0;
1153 :
1154 : /** Handle removal of a peer (clear state) */
1155 : virtual void FinalizeNode(const CNode& node) = 0;
1156 :
1157 : /**
1158 : * Process protocol messages received from a given node
1159 : *
1160 : * @param[in] pnode The node which we have received messages from.
1161 : * @param[in] interrupt Interrupt condition for processing threads
1162 : * @return True if there is more work to be done
1163 : */
1164 : virtual bool ProcessMessages(CNode* pnode, std::atomic<bool>& interrupt) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) = 0;
1165 :
1166 : /**
1167 : * Send queued protocol messages to a given node.
1168 : *
1169 : * @param[in] pnode The node which we are sending messages to.
1170 : * @return True if there is more work to be done
1171 : */
1172 : virtual bool SendMessages(CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) = 0;
1173 :
1174 :
1175 : protected:
1176 : /**
1177 : * Protected destructor so that instances can only be deleted by derived classes.
1178 : * If that restriction is no longer desired, this should be made public and virtual.
1179 : */
1180 : ~NetEventsInterface() = default;
1181 : };
1182 :
1183 : class CConnman
1184 : {
1185 : friend class CNode;
1186 : public:
1187 2436 : struct Options
1188 : {
1189 812 : ServiceFlags nLocalServices = NODE_NONE;
1190 812 : int nMaxConnections = 0;
1191 812 : int m_max_outbound_full_relay = 0;
1192 812 : int m_max_outbound_block_relay = 0;
1193 812 : int m_max_outbound_onion = 0;
1194 812 : int nMaxAddnode = 0;
1195 812 : int nMaxFeeler = 0;
1196 812 : CClientUIInterface* uiInterface = nullptr;
1197 812 : NetEventsInterface* m_msgproc = nullptr;
1198 812 : BanMan* m_banman = nullptr;
1199 812 : unsigned int nSendBufferMaxSize = 0;
1200 812 : unsigned int nReceiveFloodSize = 0;
1201 812 : uint64_t nMaxOutboundLimit = 0;
1202 812 : int64_t m_peer_connect_timeout = DEFAULT_PEER_CONNECT_TIMEOUT;
1203 : std::vector<std::string> vSeedNodes;
1204 : std::vector<NetWhitelistPermissions> vWhitelistedRange;
1205 : std::vector<NetWhitebindPermissions> vWhiteBinds;
1206 : std::vector<CService> vBinds;
1207 : std::vector<CService> onion_binds;
1208 : /// True if the user did not specify -bind= or -whitebind= and thus
1209 : /// we should bind on `0.0.0.0` (IPv4) and `::` (IPv6).
1210 : bool bind_on_any;
1211 812 : bool m_use_addrman_outgoing = true;
1212 : std::vector<std::string> m_specified_outgoing;
1213 : std::vector<std::string> m_added_nodes;
1214 812 : SocketEventsMode socketEventsMode = SocketEventsMode::Select;
1215 : bool m_i2p_accept_incoming;
1216 812 : bool m_active_masternode = false;
1217 : };
1218 :
1219 812 : void Init(const Options& connOptions) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex, !m_total_bytes_sent_mutex)
1220 : {
1221 812 : AssertLockNotHeld(m_total_bytes_sent_mutex);
1222 :
1223 812 : nLocalServices = connOptions.nLocalServices;
1224 812 : nMaxConnections = connOptions.nMaxConnections;
1225 812 : m_max_outbound_full_relay = std::min(connOptions.m_max_outbound_full_relay, connOptions.nMaxConnections);
1226 812 : m_max_outbound_block_relay = connOptions.m_max_outbound_block_relay;
1227 812 : m_max_outbound_onion = connOptions.m_max_outbound_onion;
1228 812 : m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
1229 812 : nMaxAddnode = connOptions.nMaxAddnode;
1230 812 : nMaxFeeler = connOptions.nMaxFeeler;
1231 812 : m_max_outbound = m_max_outbound_full_relay + m_max_outbound_block_relay + nMaxFeeler;
1232 812 : m_client_interface = connOptions.uiInterface;
1233 812 : m_banman = connOptions.m_banman;
1234 812 : m_msgproc = connOptions.m_msgproc;
1235 812 : nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
1236 812 : nReceiveFloodSize = connOptions.nReceiveFloodSize;
1237 812 : m_peer_connect_timeout = std::chrono::seconds{connOptions.m_peer_connect_timeout};
1238 : {
1239 812 : LOCK(m_total_bytes_sent_mutex);
1240 812 : nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
1241 812 : }
1242 812 : vWhitelistedRange = connOptions.vWhitelistedRange;
1243 : {
1244 812 : LOCK(m_added_nodes_mutex);
1245 : // Attempt v2 connection if we support v2 - we'll reconnect with v1 if our
1246 : // peer doesn't support it or immediately disconnects us for another reason.
1247 812 : const bool use_v2transport(GetLocalServices() & NODE_P2P_V2);
1248 812 : for (const std::string& added_node : connOptions.m_added_nodes) {
1249 0 : m_added_node_params.push_back({added_node, use_v2transport});
1250 : }
1251 812 : }
1252 812 : socketEventsMode = connOptions.socketEventsMode;
1253 812 : m_onion_binds = connOptions.onion_binds;
1254 812 : m_active_masternode = connOptions.m_active_masternode;
1255 812 : }
1256 :
1257 : CConnman(uint64_t seed0, uint64_t seed1, AddrMan& addrman, const NetGroupManager& netgroupman,
1258 : bool network_active = true);
1259 :
1260 : ~CConnman();
1261 : bool Start(CDeterministicMNManager& dmnman, CMasternodeMetaMan& mn_metaman, CMasternodeSync& mn_sync,
1262 : CScheduler& scheduler, const Options& options)
1263 : EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !m_added_nodes_mutex, !m_addr_fetches_mutex, !mutexMsgProc);
1264 :
1265 : void StopThreads();
1266 : void StopNodes() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !cs_mapSocketToNode, !cs_sendable_receivable_nodes, !m_reconnections_mutex);
1267 809 : void Stop() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !cs_mapSocketToNode, !cs_sendable_receivable_nodes, !m_reconnections_mutex)
1268 : {
1269 809 : StopThreads();
1270 809 : StopNodes();
1271 809 : };
1272 :
1273 : void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);
1274 8 : bool GetNetworkActive() const { return fNetworkActive; };
1275 3 : bool GetUseAddrmanOutgoing() const { return m_use_addrman_outgoing; };
1276 : void SetNetworkActive(bool active, CMasternodeSync* const mn_sync);
1277 0 : bool GetMasternodeThreadActive() const { return m_masternode_thread_active; };
1278 0 : void SetMasternodeThreadActive(bool active) { m_masternode_thread_active = active; };
1279 0 : bool IsActiveMasternode() const { return m_active_masternode; }
1280 3 : SocketEventsMode GetSocketEventsMode() const { return socketEventsMode; }
1281 :
1282 : enum class MasternodeConn {
1283 : IsNotConnection,
1284 : IsConnection,
1285 : };
1286 :
1287 : enum class MasternodeProbeConn {
1288 : IsNotConnection,
1289 : IsConnection,
1290 : };
1291 :
1292 : void OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant&& grant_outbound,
1293 : const char* strDest, ConnectionType conn_type, bool use_v2transport,
1294 : MasternodeConn masternode_connection = MasternodeConn::IsNotConnection,
1295 : MasternodeProbeConn masternode_probe_connection = MasternodeProbeConn::IsNotConnection)
1296 : EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !m_unused_i2p_sessions_mutex, !mutexMsgProc, !cs_mapSocketToNode);
1297 : void OpenMasternodeConnection(const CAddress& addrConnect, bool use_v2transport, MasternodeProbeConn probe = MasternodeProbeConn::IsConnection)
1298 : EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !m_unused_i2p_sessions_mutex, !mutexMsgProc, !cs_mapSocketToNode);
1299 : bool CheckIncomingNonce(uint64_t nonce) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1300 : void ASMapHealthCheck();
1301 :
1302 : // alias for thread safety annotations only, not defined
1303 : SharedMutex& GetNodesMutex() const LOCK_RETURNED(m_nodes_mutex);
1304 :
1305 : struct CFullyConnectedOnly {
1306 55 : bool operator() (const CNode* pnode) const {
1307 55 : return NodeFullyConnected(pnode);
1308 : }
1309 : };
1310 :
1311 : constexpr static const CFullyConnectedOnly FullyConnectedOnly{};
1312 :
1313 : struct CAllNodes {
1314 0 : bool operator() (const CNode*) const {return true;}
1315 : };
1316 :
1317 : constexpr static const CAllNodes AllNodes{};
1318 :
1319 : bool ForNode(NodeId id, std::function<bool(const CNode* pnode)> cond, std::function<bool(CNode* pnode)> func) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1320 : bool ForNode(NodeId id, std::function<bool(const CNode* pnode)> cond, std::function<bool(const CNode* pnode)> func) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1321 : bool ForNode(const CService& addr, std::function<bool(const CNode* pnode)> cond, std::function<bool(CNode* pnode)> func) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1322 : bool ForNode(const CService& addr, std::function<bool(const CNode* pnode)> cond, std::function<bool(const CNode* pnode)> func) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1323 :
1324 : template<typename Callable>
1325 0 : bool ForNode(const CService& addr, Callable&& func) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
1326 : {
1327 0 : return ForNode(addr, FullyConnectedOnly, func);
1328 0 : }
1329 :
1330 : template<typename Callable>
1331 7 : bool ForNode(NodeId id, Callable&& func) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
1332 : {
1333 7 : return ForNode(id, FullyConnectedOnly, func);
1334 0 : }
1335 :
1336 : using NodeFn = std::function<void(CNode*)>;
1337 :
1338 0 : bool IsConnected(const CService& addr, std::function<bool(const CNode* pnode)> cond) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
1339 : {
1340 0 : return ForNode(addr, cond, [](const CNode* pnode){
1341 0 : return true;
1342 : });
1343 0 : }
1344 :
1345 : bool IsMasternodeOrDisconnectRequested(const CService& addr) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1346 :
1347 : void PushMessage(CNode* pnode, CSerializedNetMsg&& msg)
1348 : EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc, !m_total_bytes_sent_mutex);
1349 :
1350 : template<typename Condition, typename Callable>
1351 0 : bool ForEachNodeContinueIf(const Condition& cond, Callable&& func) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
1352 : {
1353 0 : READ_LOCK(m_nodes_mutex);
1354 0 : for (auto&& node : m_nodes)
1355 0 : if (cond(node))
1356 0 : if(!func(node))
1357 0 : return false;
1358 0 : return true;
1359 0 : };
1360 :
1361 : template<typename Callable>
1362 : bool ForEachNodeContinueIf(Callable&& func) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
1363 : {
1364 : return ForEachNodeContinueIf(FullyConnectedOnly, func);
1365 : }
1366 :
1367 : template<typename Condition, typename Callable>
1368 : bool ForEachNodeContinueIf(const Condition& cond, Callable&& func) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
1369 : {
1370 : READ_LOCK(m_nodes_mutex);
1371 : for (const auto& node : m_nodes)
1372 : if (cond(node))
1373 : if(!func(node))
1374 : return false;
1375 : return true;
1376 : };
1377 :
1378 : template<typename Callable>
1379 : bool ForEachNodeContinueIf(Callable&& func) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
1380 : {
1381 : return ForEachNodeContinueIf(FullyConnectedOnly, func);
1382 : }
1383 :
1384 7 : void ForEachNode(const NodeFn& fn) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
1385 : {
1386 7 : ForEachNode(FullyConnectedOnly, fn);
1387 7 : }
1388 :
1389 : template<typename Condition, typename Callable>
1390 7 : void ForEachNode(const Condition& cond, Callable&& func) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
1391 : {
1392 7 : READ_LOCK(m_nodes_mutex);
1393 55 : for (auto&& node : m_nodes) {
1394 48 : if (cond(node))
1395 47 : func(node);
1396 : }
1397 7 : };
1398 :
1399 0 : void ForEachNode(const NodeFn& fn) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
1400 : {
1401 0 : ForEachNode(FullyConnectedOnly, fn);
1402 0 : }
1403 :
1404 : // Addrman functions
1405 : /**
1406 : * Return all or many randomly selected addresses, optionally by network.
1407 : *
1408 : * @param[in] max_addresses Maximum number of addresses to return (0 = all).
1409 : * @param[in] max_pct Maximum percentage of addresses to return (0 = all).
1410 : * @param[in] network Select only addresses of this network (nullopt = all).
1411 : * @param[in] filtered Select only addresses that are considered high quality (false = all).
1412 : */
1413 : std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct, std::optional<Network> network, const bool filtered = true) const;
1414 :
1415 : /**
1416 : * Cache is used to minimize topology leaks, so it should
1417 : * be used for all non-trusted calls, for example, p2p.
1418 : * A non-malicious call (from RPC or a peer with addr permission) should
1419 : * call the function without a parameter to avoid using the cache.
1420 : */
1421 : std::vector<CAddress> GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct);
1422 :
1423 : // This allows temporarily exceeding m_max_outbound_full_relay, with the goal of finding
1424 : // a peer that is better than all our current peers.
1425 : void SetTryNewOutboundPeer(bool flag);
1426 : bool GetTryNewOutboundPeer() const;
1427 :
1428 : void StartExtraBlockRelayPeers();
1429 :
1430 : // Return the number of outbound peers we have in excess of our target (eg,
1431 : // if we previously called SetTryNewOutboundPeer(true), and have since set
1432 : // to false, we may have extra peers that we wish to disconnect). This may
1433 : // return a value less than (num_outbound_connections - num_outbound_slots)
1434 : // in cases where some outbound connections are not yet fully connected, or
1435 : // not yet fully disconnected.
1436 : int GetExtraFullOutboundCount() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1437 : // Count the number of block-relay-only peers we have over our limit.
1438 : int GetExtraBlockRelayCount() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1439 :
1440 : bool AddNode(const AddedNodeParams& add) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1441 : bool RemoveAddedNode(const std::string& node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1442 : bool AddedNodesContain(const CAddress& addr) const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1443 : std::vector<AddedNodeInfo> GetAddedNodeInfo(bool include_connected) const
1444 : EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex, !m_nodes_mutex);
1445 :
1446 : /**
1447 : * Attempts to open a connection. Currently only used from tests.
1448 : *
1449 : * @param[in] address Address of node to try connecting to
1450 : * @param[in] conn_type ConnectionType::OUTBOUND, ConnectionType::BLOCK_RELAY,
1451 : * ConnectionType::ADDR_FETCH or ConnectionType::FEELER
1452 : * @param[in] use_v2transport Set to true if node attempts to connect using BIP 324 v2 transport protocol.
1453 : * @return bool Returns false if there are no available
1454 : * slots for this connection:
1455 : * - conn_type not a supported ConnectionType
1456 : * - Max total outbound connection capacity filled
1457 : * - Max connection capacity for type is filled
1458 : */
1459 : bool AddConnection(const std::string& address, ConnectionType conn_type, bool use_v2transport)
1460 : EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !m_unused_i2p_sessions_mutex, !mutexMsgProc, !cs_mapSocketToNode);
1461 :
1462 : bool AddPendingMasternode(const uint256& proTxHash);
1463 : void SetMasternodeQuorumNodes(Consensus::LLMQType llmqType, const uint256& quorumHash, const Uint256HashSet& proTxHashes);
1464 : void SetMasternodeQuorumRelayMembers(Consensus::LLMQType llmqType, const uint256& quorumHash, const Uint256HashSet& proTxHashes) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1465 : bool HasMasternodeQuorumNodes(Consensus::LLMQType llmqType, const uint256& quorumHash) const;
1466 : Uint256HashSet GetMasternodeQuorums(Consensus::LLMQType llmqType) const;
1467 : // also returns QWATCH nodes
1468 : std::vector<NodeId> GetMasternodeQuorumNodes(Consensus::LLMQType llmqType, const uint256& quorumHash) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1469 : void RemoveMasternodeQuorumNodes(Consensus::LLMQType llmqType, const uint256& quorumHash);
1470 : bool IsMasternodeQuorumNode(const CNode* pnode, const CDeterministicMNList& tip_mn_list) const;
1471 : bool IsMasternodeQuorumRelayMember(const uint256& protxHash);
1472 : void AddPendingProbeConnections(const Uint256HashSet& proTxHashes);
1473 :
1474 : size_t GetNodeCount(ConnectionDirection) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1475 : std::map<CNetAddr, LocalServiceInfo> getNetLocalAddresses() const;
1476 : size_t GetMaxOutboundNodeCount();
1477 : size_t GetMaxOutboundOnionNodeCount();
1478 : void GetNodeStats(std::vector<CNodeStats>& vstats) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1479 : uint32_t GetMappedAS(const CNetAddr& addr) const;
1480 : bool DisconnectNode(const std::string& node) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1481 : bool DisconnectNode(const CSubNet& subnet) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1482 : bool DisconnectNode(const CNetAddr& addr) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1483 : bool DisconnectNode(NodeId id) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1484 :
1485 : //! Used to convey which local services we are offering peers during node
1486 : //! connection.
1487 : //!
1488 : //! The data returned by this is used in CNode construction,
1489 : //! which is used to advertise which services we are offering
1490 : //! that peer during `net_processing.cpp:PushNodeVersion()`.
1491 : ServiceFlags GetLocalServices() const;
1492 :
1493 : uint64_t GetMaxOutboundTarget() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1494 : std::chrono::seconds GetMaxOutboundTimeframe() const;
1495 :
1496 : //! check if the outbound target is reached
1497 : //! if param historicalBlockServingLimit is set true, the function will
1498 : //! response true if the limit for serving historical blocks has been reached
1499 : bool OutboundTargetReached(bool historicalBlockServingLimit) const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1500 :
1501 : //! response the bytes left in the current max outbound cycle
1502 : //! in case of no limit, it will always response 0
1503 : uint64_t GetOutboundTargetBytesLeft() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1504 :
1505 : std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1506 :
1507 : uint64_t GetTotalBytesRecv() const;
1508 : uint64_t GetTotalBytesSent() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1509 :
1510 : /** Get a unique deterministic randomizer. */
1511 : CSipHasher GetDeterministicRandomizer(uint64_t id) const;
1512 :
1513 : void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);
1514 :
1515 : /** Return true if we should disconnect the peer for failing an inactivity check. */
1516 : bool ShouldRunInactivityChecks(const CNode& node, std::chrono::seconds now) const;
1517 :
1518 : bool MultipleManualOrFullOutboundConns(Network net) const SHARED_LOCKS_REQUIRED(m_nodes_mutex);
1519 :
1520 : /**
1521 : * RAII helper to atomically create a copy of `m_nodes` and add a reference
1522 : * to each of the nodes. The nodes are released when this object is destroyed.
1523 : */
1524 : class NodesSnapshot
1525 : {
1526 : public:
1527 : explicit NodesSnapshot(const CConnman& connman, std::function<bool(const CNode* pnode)> cond = AllNodes,
1528 : bool shuffle = false)
1529 : EXCLUSIVE_LOCKS_REQUIRED(!connman.m_nodes_mutex);
1530 : ~NodesSnapshot();
1531 :
1532 0 : const std::vector<CNode*>& Nodes() const
1533 : {
1534 0 : return m_nodes_copy;
1535 : }
1536 :
1537 : private:
1538 : std::vector<CNode*> m_nodes_copy;
1539 : };
1540 :
1541 : private:
1542 : struct ListenSocket {
1543 : public:
1544 : std::shared_ptr<Sock> sock;
1545 0 : inline void AddSocketPermissionFlags(NetPermissionFlags& flags) const { NetPermissions::AddFlag(flags, m_permissions); }
1546 0 : ListenSocket(std::shared_ptr<Sock> sock_, NetPermissionFlags permissions_)
1547 0 : : sock{sock_}, m_permissions{permissions_}
1548 0 : {
1549 0 : }
1550 :
1551 : private:
1552 : NetPermissionFlags m_permissions;
1553 : };
1554 :
1555 : //! returns the time left in the current max outbound cycle
1556 : //! in case of no limit, it will always return 0
1557 : std::chrono::seconds GetMaxOutboundTimeLeftInCycle_() const EXCLUSIVE_LOCKS_REQUIRED(m_total_bytes_sent_mutex);
1558 :
1559 : bool BindListenPort(const CService& bindAddr, bilingual_str& strError, NetPermissionFlags permissions);
1560 : bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions);
1561 : bool InitBinds(const Options& options);
1562 :
1563 : void ThreadOpenAddedConnections()
1564 : EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex, !m_nodes_mutex, !m_reconnections_mutex,
1565 : !m_unused_i2p_sessions_mutex, !mutexMsgProc, !cs_mapSocketToNode);
1566 : void AddAddrFetch(const std::string& strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex);
1567 : void ProcessAddrFetch()
1568 : EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex, !m_nodes_mutex, !m_unused_i2p_sessions_mutex,
1569 : !mutexMsgProc, !cs_mapSocketToNode);
1570 : void ThreadOpenConnections(const std::vector<std::string> connect, CDeterministicMNManager& dmnman)
1571 : EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex, !m_added_nodes_mutex, !m_nodes_mutex, !m_reconnections_mutex,
1572 : !m_unused_i2p_sessions_mutex, !mutexMsgProc, !cs_mapSocketToNode);
1573 : void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !mutexMsgProc);
1574 : void ThreadI2PAcceptIncoming(CMasternodeSync& mn_sync) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !mutexMsgProc, !cs_mapSocketToNode);
1575 : void AcceptConnection(const ListenSocket& hListenSocket, CMasternodeSync& mn_sync)
1576 : EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !mutexMsgProc, !cs_mapSocketToNode);
1577 :
1578 : /**
1579 : * Create a `CNode` object from a socket that has just been accepted and add the node to
1580 : * the `m_nodes` member.
1581 : * @param[in] sock Connected socket to communicate with the peer.
1582 : * @param[in] permission_flags The peer's permissions.
1583 : * @param[in] addr_bind The address and port at our side of the connection.
1584 : * @param[in] addr The address and port at the peer's side of the connection.
1585 : */
1586 : void CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock,
1587 : NetPermissionFlags permission_flags,
1588 : const CAddress& addr_bind,
1589 : const CAddress& addr,
1590 : CMasternodeSync& mn_sync)
1591 : EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !mutexMsgProc, !cs_mapSocketToNode);
1592 :
1593 : void DisconnectNodes() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex, !m_nodes_mutex);
1594 : void NotifyNumConnectionsChanged(CMasternodeSync& mn_sync) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1595 : void CalculateNumConnectionsChangedStats() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1596 : /** Return true if the peer is inactive and should be disconnected. */
1597 : bool InactivityCheck(const CNode& node) const;
1598 :
1599 : /**
1600 : * Generate a collection of sockets to check for IO readiness.
1601 : * @param[in] nodes Select from these nodes' sockets.
1602 : * @return sockets to check for readiness
1603 : */
1604 : Sock::EventsPerSock GenerateWaitSockets(Span<CNode* const> nodes);
1605 :
1606 : /**
1607 : * Check connected and listening sockets for IO readiness and process them accordingly.
1608 : */
1609 : void SocketHandler(CMasternodeSync& mn_sync) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !m_total_bytes_sent_mutex, !mutexMsgProc, !cs_mapSocketToNode, !cs_sendable_receivable_nodes);
1610 :
1611 : /**
1612 : * Do the read/write for connected sockets that are ready for IO.
1613 : * @param[in] events_per_sock Sockets that are ready for IO.
1614 : */
1615 : void SocketHandlerConnected(const Sock::EventsPerSock& events_per_sock)
1616 : EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !m_total_bytes_sent_mutex, !mutexMsgProc, !cs_sendable_receivable_nodes, !cs_mapSocketToNode);
1617 :
1618 : /**
1619 : * Accept incoming connections, one from each read-ready listening socket.
1620 : * @param[in] events_per_sock Sockets that are ready for IO.
1621 : */
1622 : void SocketHandlerListening(const Sock::EventsPerSock& events_per_sock, CMasternodeSync& mn_sync)
1623 : EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !mutexMsgProc, !cs_mapSocketToNode);
1624 :
1625 : void ThreadSocketHandler(CMasternodeSync& mn_sync)
1626 : EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !mutexMsgProc, !m_nodes_mutex, !m_reconnections_mutex, !cs_mapSocketToNode, !cs_sendable_receivable_nodes);
1627 : void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex, !m_nodes_mutex);
1628 : void ThreadOpenMasternodeConnections(CDeterministicMNManager& dmnman, CMasternodeMetaMan& mn_metaman,
1629 : CMasternodeSync& mn_sync)
1630 : EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex, !m_nodes_mutex, !m_unused_i2p_sessions_mutex, !mutexMsgProc, !cs_mapSocketToNode);
1631 :
1632 : uint64_t CalculateKeyedNetGroup(const CAddress& ad) const;
1633 :
1634 : // Type-agnostic node matching helpers
1635 37 : static inline bool NodeMatches(const CNode* p, const CService& addr)
1636 : {
1637 37 : return static_cast<CService>(p->addr) == addr;
1638 0 : }
1639 : static inline bool NodeMatches(const CNode* p, const CNetAddr& ip)
1640 : {
1641 : return static_cast<CNetAddr>(p->addr) == ip;
1642 : }
1643 0 : static inline bool NodeMatches(const CNode* p, const std::string& addrName)
1644 : {
1645 0 : return p->m_addr_name == addrName;
1646 : }
1647 44 : static inline bool NodeMatches(const CNode* p, const NodeId id)
1648 : {
1649 44 : return p->GetId() == id;
1650 : }
1651 :
1652 : template<typename Key>
1653 22 : const CNode* FindNode(const Key& key, bool fExcludeDisconnecting = true) const SHARED_LOCKS_REQUIRED(m_nodes_mutex)
1654 : {
1655 22 : AssertSharedLockHeld(m_nodes_mutex);
1656 43 : for (const CNode* pnode : m_nodes) {
1657 37 : if (fExcludeDisconnecting && pnode->fDisconnect) continue;
1658 37 : if (NodeMatches(pnode, key)) return pnode;
1659 : }
1660 6 : return nullptr;
1661 22 : }
1662 :
1663 : template<typename Key>
1664 7 : CNode* FindNodeMutable(const Key& key, bool fExcludeDisconnecting = true) SHARED_LOCKS_REQUIRED(m_nodes_mutex)
1665 : {
1666 7 : AssertSharedLockHeld(m_nodes_mutex);
1667 44 : for (CNode* pnode : m_nodes) {
1668 44 : if (fExcludeDisconnecting && pnode->fDisconnect) continue;
1669 44 : if (NodeMatches(pnode, key)) return pnode;
1670 : }
1671 0 : return nullptr;
1672 7 : }
1673 :
1674 : // Callback helpers with explicit lock semantics (templated on key type)
1675 : // Lambda-based shared accessor returning optional result (nullopt = not found)
1676 : template<typename Key, typename Callable>
1677 0 : std::optional<std::invoke_result_t<Callable, CNode*>> WithNodeMutable(const Key& key, Callable&& fn) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
1678 : {
1679 0 : READ_LOCK(m_nodes_mutex);
1680 0 : if (CNode* p = FindNodeMutable(key)) return std::optional<std::invoke_result_t<Callable, CNode*>>{fn(p)};
1681 0 : return std::nullopt;
1682 0 : }
1683 :
1684 : // Fast existence check under shared lock
1685 : template<typename Key>
1686 16 : bool ExistsNode(const Key& key) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
1687 : {
1688 16 : READ_LOCK(m_nodes_mutex);
1689 16 : return FindNode(key) != nullptr;
1690 16 : }
1691 :
1692 : /**
1693 : * Determine whether we're already connected to a given address, in order to
1694 : * avoid initiating duplicate connections.
1695 : */
1696 : bool AlreadyConnectedToAddress(const CAddress& addr) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1697 :
1698 : std::vector<NodeEvictionCandidate> GetEvictionCandidates() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1699 : bool AttemptToEvictConnection() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1700 : CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type, bool use_v2transport) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !m_unused_i2p_sessions_mutex);
1701 : void AddWhitelistPermissionFlags(NetPermissionFlags& flags, const CNetAddr &addr) const;
1702 :
1703 : void DeleteNode(CNode* pnode);
1704 :
1705 : NodeId GetNewNodeId();
1706 :
1707 : /** (Try to) send data from node's vSendMsg. Returns (bytes_sent, data_left). */
1708 : std::pair<size_t, bool> SocketSendData(CNode& node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend);
1709 :
1710 : size_t SocketRecvData(CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !mutexMsgProc);
1711 :
1712 : void DumpAddresses();
1713 :
1714 : // Network stats
1715 : void RecordBytesRecv(uint64_t bytes);
1716 : void RecordBytesSent(uint64_t bytes) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1717 :
1718 : /**
1719 : Return reachable networks for which we have no addresses in addrman and therefore
1720 : may require loading fixed seeds.
1721 : */
1722 : std::unordered_set<Network> GetReachableEmptyNetworks() const;
1723 :
1724 : /**
1725 : * Return vector of current BLOCK_RELAY peers.
1726 : */
1727 : std::vector<CAddress> GetCurrentBlockRelayOnlyConns() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1728 :
1729 : /**
1730 : * Search for a "preferred" network, a reachable network to which we
1731 : * currently don't have any OUTBOUND_FULL_RELAY or MANUAL connections.
1732 : * There needs to be at least one address in AddrMan for a preferred
1733 : * network to be picked.
1734 : *
1735 : * @param[out] network Preferred network, if found.
1736 : *
1737 : * @return bool Whether a preferred network was found.
1738 : */
1739 : bool MaybePickPreferredNetwork(std::optional<Network>& network) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1740 :
1741 : // Whether the node should be passed out in ForEach* callbacks
1742 : static bool NodeFullyConnected(const CNode* pnode);
1743 :
1744 : // Network usage totals
1745 : mutable Mutex m_total_bytes_sent_mutex;
1746 : std::atomic<uint64_t> nTotalBytesRecv{0};
1747 : uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex) {0};
1748 :
1749 : // outbound limit & stats
1750 : uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex) {0};
1751 : std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex) {0};
1752 : uint64_t nMaxOutboundLimit GUARDED_BY(m_total_bytes_sent_mutex);
1753 :
1754 : // P2P timeout in seconds
1755 : std::chrono::seconds m_peer_connect_timeout;
1756 :
1757 : // Whitelisted ranges. Any node connecting from these is automatically
1758 : // whitelisted (as well as those connecting to whitelisted binds).
1759 : std::vector<NetWhitelistPermissions> vWhitelistedRange;
1760 :
1761 : unsigned int nSendBufferMaxSize{0};
1762 : unsigned int nReceiveFloodSize{0};
1763 :
1764 : std::vector<ListenSocket> vhListenSocket;
1765 : std::atomic<bool> fNetworkActive{true};
1766 : std::atomic<bool> m_masternode_thread_active{true};
1767 : bool fAddressesInitialized{false};
1768 : AddrMan& addrman;
1769 : const NetGroupManager& m_netgroupman;
1770 : std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
1771 : Mutex m_addr_fetches_mutex;
1772 :
1773 : // connection string and whether to use v2 p2p
1774 : std::vector<AddedNodeParams> m_added_node_params GUARDED_BY(m_added_nodes_mutex);
1775 :
1776 : mutable Mutex m_added_nodes_mutex;
1777 : std::vector<CNode*> m_nodes GUARDED_BY(m_nodes_mutex);
1778 : std::list<CNode*> m_nodes_disconnected;
1779 : mutable SharedMutex m_nodes_mutex;
1780 : std::atomic<NodeId> nLastNodeId{0};
1781 : unsigned int nPrevNodeCount{0};
1782 :
1783 : // Stores number of full-tx connections (outbound and manual) per network
1784 : std::array<unsigned int, Network::NET_MAX> m_network_conn_counts GUARDED_BY(m_nodes_mutex) = {}; // TODO consider moving this to seperate mutex
1785 :
1786 : std::vector<uint256> vPendingMasternodes;
1787 : mutable RecursiveMutex cs_vPendingMasternodes;
1788 : std::map<std::pair<Consensus::LLMQType, uint256>, Uint256HashSet> masternodeQuorumNodes GUARDED_BY(cs_vPendingMasternodes);
1789 : std::map<std::pair<Consensus::LLMQType, uint256>, Uint256HashSet> masternodeQuorumRelayMembers GUARDED_BY(cs_vPendingMasternodes);
1790 : Uint256HashSet masternodePendingProbes GUARDED_BY(cs_vPendingMasternodes);
1791 :
1792 : mutable Mutex cs_mapSocketToNode;
1793 : std::unordered_map<SOCKET, CNode*> mapSocketToNode GUARDED_BY(cs_mapSocketToNode);
1794 :
1795 : /**
1796 : * Cache responses to addr requests to minimize privacy leak.
1797 : * Attack example: scraping addrs in real-time may allow an attacker
1798 : * to infer new connections of the victim by detecting new records
1799 : * with fresh timestamps (per self-announcement).
1800 : */
1801 : struct CachedAddrResponse {
1802 : std::vector<CAddress> m_addrs_response_cache;
1803 : std::chrono::microseconds m_cache_entry_expiration{0};
1804 : };
1805 :
1806 : /**
1807 : * Addr responses stored in different caches
1808 : * per (network, local socket) prevent cross-network node identification.
1809 : * If a node for example is multi-homed under Tor and IPv6,
1810 : * a single cache (or no cache at all) would let an attacker
1811 : * to easily detect that it is the same node by comparing responses.
1812 : * Indexing by local socket prevents leakage when a node has multiple
1813 : * listening addresses on the same network.
1814 : *
1815 : * The used memory equals to 1000 CAddress records (or around 40 bytes) per
1816 : * distinct Network (up to 5) we have/had an inbound peer from,
1817 : * resulting in at most ~196 KB. Every separate local socket may
1818 : * add up to ~196 KB extra.
1819 : */
1820 : std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
1821 :
1822 : /**
1823 : * Services this node offers.
1824 : *
1825 : * This data is replicated in each Peer instance we create.
1826 : *
1827 : * This data is not marked const, but after being set it should not
1828 : * change.
1829 : *
1830 : * \sa Peer::our_services
1831 : */
1832 : ServiceFlags nLocalServices;
1833 :
1834 : std::unique_ptr<CSemaphore> semOutbound;
1835 : std::unique_ptr<CSemaphore> semAddnode;
1836 : int nMaxConnections;
1837 :
1838 : // How many full-relay (tx, block, addr) outbound peers we want
1839 : int m_max_outbound_full_relay;
1840 :
1841 : // How many block-relay only outbound peers we want
1842 : // We do not relay tx or addr messages with these peers
1843 : int m_max_outbound_block_relay;
1844 :
1845 : // How many onion outbound peers we want; don't care if full or block only; does not increase m_max_outbound
1846 : int m_max_outbound_onion;
1847 :
1848 : int nMaxAddnode;
1849 : int nMaxFeeler;
1850 : int m_max_outbound;
1851 : bool m_use_addrman_outgoing;
1852 : CClientUIInterface* m_client_interface;
1853 : NetEventsInterface* m_msgproc;
1854 : /** Pointer to this node's banman. May be nullptr - check existence before dereferencing. */
1855 : BanMan* m_banman;
1856 :
1857 : /**
1858 : * Addresses that were saved during the previous clean shutdown. We'll
1859 : * attempt to make block-relay-only connections to them.
1860 : */
1861 : std::vector<CAddress> m_anchors;
1862 :
1863 : /** SipHasher seeds for deterministic randomness */
1864 : const uint64_t nSeed0, nSeed1;
1865 :
1866 : /** flag for waking the message processor. */
1867 : bool fMsgProcWake GUARDED_BY(mutexMsgProc);
1868 :
1869 : std::condition_variable condMsgProc;
1870 : Mutex mutexMsgProc;
1871 : std::atomic<bool> flagInterruptMsgProc{false};
1872 :
1873 : /**
1874 : * This is signaled when network activity should cease.
1875 : * A pointer to it is saved in `m_i2p_sam_session`, so make sure that
1876 : * the lifetime of `interruptNet` is not shorter than
1877 : * the lifetime of `m_i2p_sam_session`.
1878 : */
1879 : CThreadInterrupt interruptNet;
1880 :
1881 : /**
1882 : * I2P SAM session.
1883 : * Used to accept incoming and make outgoing I2P connections from a persistent
1884 : * address.
1885 : */
1886 : std::unique_ptr<i2p::sam::Session> m_i2p_sam_session;
1887 :
1888 : /** Flag for activating masternode mode */
1889 : bool m_active_masternode{false};
1890 :
1891 : SocketEventsMode socketEventsMode;
1892 : std::unique_ptr<EdgeTriggeredEvents> m_edge_trig_events{nullptr};
1893 : std::unique_ptr<WakeupPipe> m_wakeup_pipe{nullptr};
1894 :
1895 0 : SOCKET GetModeFileDescriptor()
1896 : {
1897 0 : if (m_edge_trig_events) {
1898 0 : return static_cast<SOCKET>(m_edge_trig_events->GetFileDescriptor());
1899 : }
1900 0 : return INVALID_SOCKET;
1901 0 : }
1902 :
1903 0 : SocketEventsParams::wrap_fn ToggleWakeupPipe = [&](std::function<void()>&& func)
1904 : {
1905 0 : if (m_wakeup_pipe) {
1906 0 : m_wakeup_pipe->Toggle(func);
1907 0 : } else {
1908 0 : func();
1909 : }
1910 0 : };
1911 :
1912 : Mutex cs_sendable_receivable_nodes;
1913 : std::unordered_map<NodeId, CNode*> mapReceivableNodes GUARDED_BY(cs_sendable_receivable_nodes);
1914 : std::unordered_map<NodeId, CNode*> mapSendableNodes GUARDED_BY(cs_sendable_receivable_nodes);
1915 :
1916 : std::thread threadDNSAddressSeed;
1917 : std::thread threadSocketHandler;
1918 : std::thread threadOpenAddedConnections;
1919 : std::thread threadOpenConnections;
1920 : std::thread threadOpenMasternodeConnections;
1921 : std::thread threadMessageHandler;
1922 : std::thread threadI2PAcceptIncoming;
1923 :
1924 : /** flag for deciding to connect to an extra outbound peer,
1925 : * in excess of m_max_outbound_full_relay
1926 : * This takes the place of a feeler connection */
1927 : std::atomic_bool m_try_another_outbound_peer;
1928 :
1929 : /** flag for initiating extra block-relay-only peer connections.
1930 : * this should only be enabled after initial chain sync has occurred,
1931 : * as these connections are intended to be short-lived and low-bandwidth.
1932 : */
1933 : std::atomic_bool m_start_extra_block_relay_peers{false};
1934 :
1935 : /**
1936 : * A vector of -bind=<address>:<port>=onion arguments each of which is
1937 : * an address and port that are designated for incoming Tor connections.
1938 : */
1939 : std::vector<CService> m_onion_binds;
1940 :
1941 : /**
1942 : * Mutex protecting m_i2p_sam_sessions.
1943 : */
1944 : Mutex m_unused_i2p_sessions_mutex;
1945 :
1946 : /**
1947 : * A pool of created I2P SAM transient sessions that should be used instead
1948 : * of creating new ones in order to reduce the load on the I2P network.
1949 : * Creating a session in I2P is not cheap, thus if this is not empty, then
1950 : * pick an entry from it instead of creating a new session. If connecting to
1951 : * a host fails, then the created session is put to this pool for reuse.
1952 : */
1953 : std::queue<std::unique_ptr<i2p::sam::Session>> m_unused_i2p_sessions GUARDED_BY(m_unused_i2p_sessions_mutex);
1954 :
1955 : /**
1956 : * Mutex protecting m_reconnections.
1957 : */
1958 : Mutex m_reconnections_mutex;
1959 :
1960 : /** Struct for entries in m_reconnections. */
1961 : struct ReconnectionInfo
1962 : {
1963 : CAddress addr_connect;
1964 : CSemaphoreGrant grant;
1965 : std::string destination;
1966 : ConnectionType conn_type;
1967 : bool use_v2transport;
1968 : bool masternode_connection;
1969 : bool masternode_probe_connection;
1970 : };
1971 :
1972 : /**
1973 : * List of reconnections we have to make.
1974 : */
1975 : std::list<ReconnectionInfo> m_reconnections GUARDED_BY(m_reconnections_mutex);
1976 :
1977 : /** Attempt reconnections, if m_reconnections non-empty. */
1978 : void PerformReconnections() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !mutexMsgProc, !m_reconnections_mutex, !m_unused_i2p_sessions_mutex, !cs_mapSocketToNode);
1979 :
1980 : /**
1981 : * Cap on the size of `m_unused_i2p_sessions`, to ensure it does not
1982 : * unexpectedly use too much memory.
1983 : */
1984 : static constexpr size_t MAX_UNUSED_I2P_SESSIONS_SIZE{10};
1985 :
1986 : friend struct ConnmanTestMsg;
1987 : };
1988 :
1989 : /** Defaults to `CaptureMessageToFile()`, but can be overridden by unit tests. */
1990 : extern std::function<void(const CAddress& addr,
1991 : const std::string& msg_type,
1992 : Span<const unsigned char> data,
1993 : bool is_incoming)>
1994 : CaptureMessage;
1995 :
1996 : class CExplicitNetCleanup
1997 : {
1998 : public:
1999 : static void callCleanup();
2000 : };
2001 :
2002 : // Helper function to determine if a message type should be prioritized in the quorum queue
2003 2 : inline bool IsQuorumPriorityMessage(const std::string& msg_type)
2004 : {
2005 : // LLMQ signing/data messages
2006 4 : if (msg_type == NetMsgType::QSIGSHARE ||
2007 2 : msg_type == NetMsgType::QBSIGSHARES ||
2008 2 : msg_type == NetMsgType::QSIGSHARESINV ||
2009 2 : msg_type == NetMsgType::QGETSIGSHARES ||
2010 2 : msg_type == NetMsgType::QSIGSESANN ||
2011 2 : msg_type == NetMsgType::QSIGREC) {
2012 0 : return true;
2013 : }
2014 : // High-level lock messages (ChainLocks, InstantSend locks)
2015 2 : if (msg_type == NetMsgType::CLSIG ||
2016 2 : msg_type == NetMsgType::ISDLOCK) {
2017 0 : return true;
2018 : }
2019 2 : return false;
2020 2 : }
2021 :
2022 : #endif // BITCOIN_NET_H
|