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