Coverage Report

Created: 2026-03-16 10:46

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