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