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