Coverage Report

Created: 2024-08-21 05:08

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