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