Coverage Report

Created: 2026-11-13 17:38

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