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