Coverage Report

Created: 2026-10-03 10:33

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