Coverage Report

Created: 2026-10-07 13:27

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