Coverage Report

Created: 2025-06-10 13:21

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