Coverage Report

Created: 2026-11-13 17:38

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/net.cpp
Line
Count
Source
1
// Copyright (c) 2009-2010 Satoshi Nakamoto
2
// Copyright (c) 2009-present The Bitcoin Core developers
3
// Distributed under the MIT software license, see the accompanying
4
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6
#include <bitcoin-build-config.h> // IWYU pragma: keep
7
8
#include <net.h>
9
10
#include <addrdb.h>
11
#include <addrman.h>
12
#include <banman.h>
13
#include <chainparams.h>
14
#include <common/args.h>
15
#include <common/netif.h>
16
#include <compat/compat.h>
17
#include <consensus/consensus.h>
18
#include <crypto/common.h>
19
#include <crypto/hex_base.h>
20
#include <i2p.h>
21
#include <key.h>
22
#include <logging.h>
23
#include <memusage.h>
24
#include <net_permissions.h>
25
#include <netaddress.h>
26
#include <netbase.h>
27
#include <netgroup.h>
28
#include <node/eviction.h>
29
#include <node/interface_ui.h>
30
#include <prevector.h>
31
#include <protocol.h>
32
#include <pubkey.h>
33
#include <random.h>
34
#include <scheduler.h>
35
#include <serialize.h>
36
#include <span.h>
37
#include <tinyformat.h>
38
#include <util/btcsignals.h>
39
#include <util/fs.h>
40
#include <util/overflow.h>
41
#include <util/sock.h>
42
#include <util/strencodings.h>
43
#include <util/thread.h>
44
#include <util/threadinterrupt.h>
45
#include <util/trace.h>
46
#include <util/translation.h>
47
#include <util/vector.h>
48
49
#include <algorithm>
50
#include <array>
51
#include <compare>
52
#include <cstdint>
53
#include <cstring>
54
#include <exception>
55
#include <functional>
56
#include <ios>
57
#include <list>
58
#include <optional>
59
#include <ranges>
60
#include <ratio>
61
#include <set>
62
#include <string_view>
63
#include <unordered_map>
64
#include <vector>
65
66
TRACEPOINT_SEMAPHORE(net, closed_connection);
67
TRACEPOINT_SEMAPHORE(net, evicted_inbound_connection);
68
TRACEPOINT_SEMAPHORE(net, inbound_connection);
69
TRACEPOINT_SEMAPHORE(net, outbound_connection);
70
TRACEPOINT_SEMAPHORE(net, outbound_message);
71
72
/** Maximum number of block-relay-only anchor connections */
73
static constexpr size_t MAX_BLOCK_RELAY_ONLY_ANCHORS = 2;
74
static_assert (MAX_BLOCK_RELAY_ONLY_ANCHORS <= static_cast<size_t>(MAX_BLOCK_RELAY_ONLY_CONNECTIONS), "MAX_BLOCK_RELAY_ONLY_ANCHORS must not exceed MAX_BLOCK_RELAY_ONLY_CONNECTIONS.");
75
/** Anchor IP address database file name */
76
const char* const ANCHORS_DATABASE_FILENAME = "anchors.dat";
77
78
// How often to dump addresses to peers.dat
79
static constexpr std::chrono::minutes DUMP_PEERS_INTERVAL{15};
80
81
/** Number of DNS seeds to query when the number of connections is low. */
82
static constexpr int DNSSEEDS_TO_QUERY_AT_ONCE = 3;
83
84
/** Minimum number of outbound connections under which we will keep fetching our address seeds. */
85
static constexpr int SEED_OUTBOUND_CONNECTION_THRESHOLD = 2;
86
87
/** How long to delay before querying DNS seeds
88
 *
89
 * If we have more than THRESHOLD entries in addrman, then it's likely
90
 * that we got those addresses from having previously connected to the P2P
91
 * network, and that we'll be able to successfully reconnect to the P2P
92
 * network via contacting one of them. So if that's the case, spend a
93
 * little longer trying to connect to known peers before querying the
94
 * DNS seeds.
95
 */
96
static constexpr std::chrono::seconds DNSSEEDS_DELAY_FEW_PEERS{11};
97
static constexpr std::chrono::minutes DNSSEEDS_DELAY_MANY_PEERS{5};
98
static constexpr int DNSSEEDS_DELAY_PEER_THRESHOLD = 1000; // "many" vs "few" peers
99
100
/** The default timeframe for -maxuploadtarget. 1 day. */
101
static constexpr std::chrono::seconds MAX_UPLOAD_TIMEFRAME{60 * 60 * 24};
102
103
// A random time period (0 to 1 seconds) is added to feeler connections to prevent synchronization.
104
static constexpr auto FEELER_SLEEP_WINDOW{1s};
105
106
/** Frequency to attempt extra connections to reachable networks we're not connected to yet **/
107
static constexpr auto EXTRA_NETWORK_PEER_INTERVAL{5min};
108
109
/** Used to pass flags to the Bind() function */
110
enum BindFlags {
111
    BF_NONE         = 0,
112
    BF_REPORT_ERROR = (1U << 0),
113
    /**
114
     * Do not call AddLocal() for our special addresses, e.g., for incoming
115
     * Tor connections, to prevent gossiping them over the network.
116
     */
117
    BF_DONT_ADVERTISE = (1U << 1),
118
};
119
120
// The set of sockets cannot be modified while waiting
121
// The sleep time needs to be small to avoid new sockets stalling
122
static const uint64_t SELECT_TIMEOUT_MILLISECONDS = 50;
123
124
const std::string NET_MESSAGE_TYPE_OTHER = "*other*";
125
126
static const uint64_t RANDOMIZER_ID_NETGROUP = 0x6c0edd8036ef4036ULL; // SHA256("netgroup")[0:8]
127
static const uint64_t RANDOMIZER_ID_LOCALHOSTNONCE = 0xd93e69e2bbfa5735ULL; // SHA256("localhostnonce")[0:8]
128
static const uint64_t RANDOMIZER_ID_NETWORKKEY = 0x0e8a2b136c592a7dULL; // SHA256("networkkey")[0:8]
129
//
130
// Global state variables
131
//
132
bool fDiscover = true;
133
bool fListen = true;
134
GlobalMutex g_maplocalhost_mutex;
135
std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(g_maplocalhost_mutex);
136
std::string strSubVersion;
137
138
size_t CSerializedNetMsg::GetMemoryUsage() const noexcept
139
585k
{
140
585k
    return sizeof(*this) + memusage::DynamicUsage(m_type) + memusage::DynamicUsage(data);
141
585k
}
142
143
size_t CNetMessage::GetMemoryUsage() const noexcept
144
282k
{
145
282k
    return sizeof(*this) + memusage::DynamicUsage(m_type) + m_recv.GetMemoryUsage();
146
282k
}
147
148
void CConnman::AddAddrFetch(const std::string& strDest)
149
15
{
150
15
    LOCK(m_addr_fetches_mutex);
151
15
    m_addr_fetches.push_back(strDest);
152
15
}
153
154
uint16_t GetListenPort()
155
1.78k
{
156
    // If -bind= is provided with ":port" part, use that (first one if multiple are provided).
157
1.80k
    for (const std::string& bind_arg : gArgs.GetArgs("-bind")) {
158
1.80k
        constexpr uint16_t dummy_port = 0;
159
160
1.80k
        const std::optional<CService> bind_addr{Lookup(bind_arg, dummy_port, /*fAllowLookup=*/false)};
161
1.80k
        if (bind_addr.has_value() && bind_addr->GetPort() != dummy_port) return bind_addr->GetPort();
162
1.80k
    }
163
164
    // Otherwise, if -whitebind= without NetPermissionFlags::NoBan is provided, use that
165
    // (-whitebind= is required to have ":port").
166
1.77k
    for (const std::string& whitebind_arg : gArgs.GetArgs("-whitebind")) {
167
5
        NetWhitebindPermissions whitebind;
168
5
        bilingual_str error;
169
5
        if (NetWhitebindPermissions::TryParse(whitebind_arg, whitebind, error)) {
170
5
            if (!NetPermissions::HasFlag(whitebind.m_flags, NetPermissionFlags::NoBan)) {
171
5
                return whitebind.m_service.GetPort();
172
5
            }
173
5
        }
174
5
    }
175
176
    // Otherwise, if -port= is provided, use that. Otherwise use the default port.
177
1.76k
    return static_cast<uint16_t>(gArgs.GetIntArg("-port", Params().GetDefaultPort()));
178
1.77k
}
179
180
// Determine the "best" local address for a particular peer.
181
[[nodiscard]] static std::optional<CService> GetLocal(const CNode& peer)
182
1.74k
{
183
1.74k
    if (!fListen) return std::nullopt;
184
185
1.74k
    std::optional<CService> addr;
186
1.74k
    int nBestScore = -1;
187
1.74k
    int nBestReachability = -1;
188
1.74k
    {
189
1.74k
        LOCK(g_maplocalhost_mutex);
190
1.74k
        for (const auto& [local_addr, local_service_info] : mapLocalHost) {
191
            // For privacy reasons, don't advertise our privacy-network address
192
            // to other networks and don't advertise our other-network address
193
            // to privacy networks.
194
95
            if (local_addr.GetNetwork() != peer.ConnectedThroughNetwork()
195
95
                && (local_addr.IsPrivacyNet() || peer.IsConnectedThroughPrivacyNet())) {
196
36
                continue;
197
36
            }
198
59
            const int nScore{local_service_info.nScore};
199
59
            const int nReachability{local_addr.GetReachabilityFrom(peer.addr)};
200
59
            if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore)) {
201
42
                addr.emplace(CService{local_addr, local_service_info.nPort});
202
42
                nBestReachability = nReachability;
203
42
                nBestScore = nScore;
204
42
            }
205
59
        }
206
1.74k
    }
207
1.74k
    return addr;
208
1.74k
}
209
210
//! Convert the serialized seeds into usable address objects.
211
static std::vector<CAddress> ConvertSeeds(const std::vector<uint8_t> &vSeedsIn)
212
3
{
213
    // It'll only connect to one or two seed nodes because once it connects,
214
    // it'll get a pile of addresses with newer timestamps.
215
    // Seed nodes are given a random 'last seen time' of between one and two
216
    // weeks ago.
217
3
    const auto one_week{7 * 24h};
218
3
    std::vector<CAddress> vSeedsOut;
219
3
    FastRandomContext rng;
220
3
    ParamsStream s{SpanReader{vSeedsIn}, CAddress::V2_NETWORK};
221
3
    while (!s.empty()) {
222
0
        CService endpoint;
223
0
        s >> endpoint;
224
0
        CAddress addr{endpoint, SeedsAssumedServiceFlags()};
225
0
        addr.nTime = rng.rand_uniform_delay(Now<NodeSeconds>() - one_week, -one_week);
226
0
        LogDebug(BCLog::NET, "Added hardcoded seed: %s\n", addr.ToStringAddrPort());
227
0
        vSeedsOut.push_back(addr);
228
0
    }
229
3
    return vSeedsOut;
230
3
}
231
232
// Determine the "best" local address for a particular peer.
233
// If none, return the unroutable 0.0.0.0 but filled in with
234
// the normal parameters, since the IP may be changed to a useful
235
// one by discovery.
236
CService GetLocalAddress(const CNode& peer)
237
1.74k
{
238
1.74k
    return GetLocal(peer).value_or(CService{CNetAddr(), GetListenPort()});
239
1.74k
}
240
241
static int GetnScore(const CService& addr)
242
0
{
243
0
    LOCK(g_maplocalhost_mutex);
244
0
    const auto it = mapLocalHost.find(addr);
245
0
    return (it != mapLocalHost.end()) ? it->second.nScore : 0;
246
0
}
247
248
// Is our peer's addrLocal potentially useful as an external IP source?
249
[[nodiscard]] static bool IsPeerAddrLocalGood(CNode *pnode)
250
1.72k
{
251
1.72k
    CService addrLocal = pnode->GetAddrLocal();
252
    // Tor/I2P peers can't see our clearnet address and the Tor/I2P address won't fit in addrMe (addrv1). so ignore it.
253
1.72k
    return fDiscover && !pnode->IsConnectedThroughPrivacyNet() &&
254
1.72k
           pnode->addr.IsRoutable() && addrLocal.IsRoutable() &&
255
1.72k
           g_reachable_nets.Contains(addrLocal);
256
1.72k
}
257
258
std::optional<CService> GetLocalAddrForPeer(CNode& node)
259
1.72k
{
260
1.72k
    CService addrLocal{GetLocalAddress(node)};
261
    // If discovery is enabled, sometimes give our peer the address it
262
    // tells us that it sees us as in case it has a better idea of our
263
    // address than we do.
264
1.72k
    FastRandomContext rng;
265
1.72k
    if (IsPeerAddrLocalGood(&node) && (!addrLocal.IsRoutable() ||
266
4
         rng.randbits((GetnScore(addrLocal) > LOCAL_MANUAL) ? 3 : 1) == 0))
267
4
    {
268
4
        if (node.IsInboundConn()) {
269
            // For inbound connections, assume both the address and the port
270
            // as seen from the peer.
271
1
            addrLocal = CService{node.GetAddrLocal()};
272
3
        } else {
273
            // For outbound connections, assume just the address as seen from
274
            // the peer and leave the port in `addrLocal` as returned by
275
            // `GetLocalAddress()` above. The peer has no way to observe our
276
            // listening port when we have initiated the connection.
277
3
            addrLocal.SetIP(node.GetAddrLocal());
278
3
        }
279
4
    }
280
1.72k
    if (addrLocal.IsRoutable()) {
281
28
        LogDebug(BCLog::NET, "Advertising address %s to peer=%d\n", addrLocal.ToStringAddrPort(), node.GetId());
282
28
        return addrLocal;
283
28
    }
284
    // Address is unroutable. Don't advertise.
285
1.69k
    return std::nullopt;
286
1.72k
}
287
288
void ClearLocal()
289
815
{
290
815
    LOCK(g_maplocalhost_mutex);
291
815
    return mapLocalHost.clear();
292
815
}
293
294
// learn a new local address
295
bool AddLocal(const CService& addr_, int nScore, bool add_even_if_unreachable)
296
53
{
297
53
    CService addr{MaybeFlipIPv6toCJDNS(addr_)};
298
299
53
    if (!addr.IsRoutable())
300
18
        return false;
301
302
35
    if (!fDiscover && nScore < LOCAL_MANUAL)
303
1
        return false;
304
305
34
    if (!g_reachable_nets.Contains(addr) && !add_even_if_unreachable)
306
1
        return false;
307
308
33
    if (fLogIPs) {
309
0
        LogInfo("AddLocal(%s,%i)\n", addr.ToStringAddrPort(), nScore);
310
0
    }
311
312
33
    {
313
33
        LOCK(g_maplocalhost_mutex);
314
33
        const auto [it, is_newly_added] = mapLocalHost.emplace(addr, LocalServiceInfo());
315
33
        LocalServiceInfo &info = it->second;
316
33
        if (is_newly_added || nScore >= info.nScore) {
317
33
            info.nScore = SaturatingAdd(nScore, is_newly_added ? 0 : 1);
318
33
            info.nPort = addr.GetPort();
319
33
        }
320
33
    }
321
322
33
    return true;
323
34
}
324
325
bool AddLocal(const CNetAddr& addr, int nScore, bool add_even_if_unreachable)
326
19
{
327
19
    return AddLocal(CService(addr, GetListenPort()), nScore, add_even_if_unreachable);
328
19
}
329
330
void RemoveLocal(const CService& addr)
331
18
{
332
18
    LOCK(g_maplocalhost_mutex);
333
18
    if (fLogIPs) {
334
0
        LogInfo("RemoveLocal(%s)\n", addr.ToStringAddrPort());
335
0
    }
336
337
18
    mapLocalHost.erase(addr);
338
18
}
339
340
/** vote for a local address */
341
bool SeenLocal(const CService& addr)
342
2
{
343
2
    LOCK(g_maplocalhost_mutex);
344
2
    const auto it = mapLocalHost.find(addr);
345
2
    if (it == mapLocalHost.end()) return false;
346
2
    it->second.nScore = SaturatingAdd(it->second.nScore, 1);
347
2
    return true;
348
2
}
349
350
351
/** check whether a given address is potentially local */
352
bool IsLocal(const CService& addr)
353
201
{
354
201
    LOCK(g_maplocalhost_mutex);
355
201
    return mapLocalHost.contains(addr);
356
201
}
357
358
bool CConnman::AlreadyConnectedToHost(std::string_view host) const
359
645
{
360
645
    LOCK(m_nodes_mutex);
361
781
    return std::ranges::any_of(m_nodes, [&host](CNode* node) { return node->m_addr_name == host; });
362
645
}
363
364
bool CConnman::AlreadyConnectedToAddressPort(const CService& addr_port) const
365
693
{
366
693
    LOCK(m_nodes_mutex);
367
1.04k
    return std::ranges::any_of(m_nodes, [&addr_port](CNode* node) { return node->addr == addr_port; });
368
693
}
369
370
bool CConnman::AlreadyConnectedToAddress(const CNetAddr& addr) const
371
70
{
372
70
    LOCK(m_nodes_mutex);
373
353
    return std::ranges::any_of(m_nodes, [&addr](CNode* node) { return node->addr == addr; });
374
70
}
375
376
bool CConnman::CheckIncomingNonce(uint64_t nonce)
377
1.10k
{
378
1.10k
    LOCK(m_nodes_mutex);
379
5.27k
    for (const CNode* pnode : m_nodes) {
380
        // Omit private broadcast connections from this check to prevent this privacy attack:
381
        // - We connect to a peer in an attempt to privately broadcast a transaction. From our
382
        //   VERSION message the peer deducts that this is a short-lived connection for
383
        //   broadcasting a transaction, takes our nonce and delays their VERACK.
384
        // - The peer starts connecting to (clearnet) nodes and sends them a VERSION message
385
        //   which contains our nonce. If the peer manages to connect to us we would disconnect.
386
        // - Upon a disconnect, the peer knows our clearnet address. They go back to the short
387
        //   lived privacy broadcast connection and continue with VERACK.
388
5.27k
        if (!pnode->fSuccessfullyConnected && !pnode->IsInboundConn() && !pnode->IsPrivateBroadcastConn() &&
389
5.27k
            pnode->GetLocalNonce() == nonce)
390
2
            return false;
391
5.27k
    }
392
1.10k
    return true;
393
1.10k
}
394
395
CNode* CConnman::ConnectNode(CAddress addrConnect,
396
                             const char* pszDest,
397
                             bool fCountFailure,
398
                             ConnectionType conn_type,
399
                             bool use_v2transport,
400
                             const std::optional<Proxy>& proxy_override)
401
711
{
402
711
    AssertLockNotHeld(m_nodes_mutex);
403
711
    AssertLockNotHeld(m_unused_i2p_sessions_mutex);
404
711
    assert(conn_type != ConnectionType::INBOUND);
405
406
711
    if (pszDest == nullptr) {
407
56
        if (IsLocal(addrConnect))
408
0
            return nullptr;
409
410
        // Look for an existing connection
411
56
        if (AlreadyConnectedToAddressPort(addrConnect)) {
412
0
            LogInfo("Failed to open new connection to %s, already connected", addrConnect.ToStringAddrPort());
413
0
            return nullptr;
414
0
        }
415
56
    }
416
417
711
    LogDebug(BCLog::NET, "trying %s connection (%s) to %s, lastseen=%.1fhrs\n",
418
711
        use_v2transport ? "v2" : "v1",
419
711
        ConnectionTypeAsString(conn_type),
420
711
        pszDest ? pszDest : addrConnect.ToStringAddrPort(),
421
711
        Ticks<HoursDouble>(pszDest ? 0h : Now<NodeSeconds>() - addrConnect.nTime));
422
423
    // Resolve
424
711
    const uint16_t default_port{pszDest != nullptr ? GetDefaultPort(pszDest) :
425
711
                                                     m_params.GetDefaultPort()};
426
427
    // Collection of addresses to try to connect to: either all dns resolved addresses if a domain name (pszDest) is provided, or addrConnect otherwise.
428
711
    std::vector<CAddress> connect_to{};
429
711
    if (pszDest) {
430
655
        std::vector<CService> resolved{Lookup(pszDest, default_port, fNameLookup && !HaveNameProxy(), 256)};
431
655
        if (!resolved.empty()) {
432
639
            std::shuffle(resolved.begin(), resolved.end(), FastRandomContext());
433
            // If the connection is made by name, it can be the case that the name resolves to more than one address.
434
            // We don't want to connect any more of them if we are already connected to one
435
639
            for (const auto& r : resolved) {
436
639
                addrConnect = CAddress{MaybeFlipIPv6toCJDNS(r), NODE_NONE};
437
639
                if (!addrConnect.IsValid()) {
438
2
                    LogDebug(BCLog::NET, "Resolver returned invalid address %s for %s\n", addrConnect.ToStringAddrPort(), pszDest);
439
2
                    return nullptr;
440
2
                }
441
                // It is possible that we already have a connection to the IP/port pszDest resolved to.
442
                // In that case, drop the connection that was just created.
443
637
                if (AlreadyConnectedToAddressPort(addrConnect)) {
444
10
                    LogInfo("Not opening a connection to %s, already connected to %s\n", pszDest, addrConnect.ToStringAddrPort());
445
10
                    return nullptr;
446
10
                }
447
                // Add the address to the resolved addresses vector so we can try to connect to it later on
448
627
                connect_to.push_back(addrConnect);
449
627
            }
450
639
        } else {
451
            // For resolution via proxy
452
16
            connect_to.push_back(addrConnect);
453
16
        }
454
655
    } else {
455
        // Connect via addrConnect directly
456
56
        connect_to.push_back(addrConnect);
457
56
    }
458
459
    // Connect
460
699
    std::unique_ptr<Sock> sock;
461
699
    CService addr_bind;
462
699
    assert(!addr_bind.IsValid());
463
699
    std::unique_ptr<i2p::sam::Session> i2p_transient_session;
464
465
699
    for (auto& target_addr : connect_to) {
466
699
        if (target_addr.IsValid()) {
467
683
            const std::optional<Proxy> use_proxy{
468
683
                proxy_override.has_value() ? proxy_override : GetProxy(target_addr.GetNetwork()),
469
683
            };
470
683
            bool proxyConnectionFailed = false;
471
472
683
            if (target_addr.IsI2P() && use_proxy) {
473
10
                i2p::Connection conn;
474
10
                bool connected{false};
475
476
                // If an I2P SAM session already exists, normally we would re-use it. But in the case of
477
                // private broadcast we force a new transient session. A Connect() using m_i2p_sam_session
478
                // would use our permanent I2P address as a source address.
479
10
                if (m_i2p_sam_session && conn_type != ConnectionType::PRIVATE_BROADCAST) {
480
3
                    connected = m_i2p_sam_session->Connect(target_addr, conn, proxyConnectionFailed);
481
7
                } else {
482
7
                    {
483
7
                        LOCK(m_unused_i2p_sessions_mutex);
484
7
                        if (m_unused_i2p_sessions.empty()) {
485
2
                            i2p_transient_session =
486
2
                                std::make_unique<i2p::sam::Session>(*use_proxy, m_interrupt_net);
487
5
                        } else {
488
5
                            i2p_transient_session.swap(m_unused_i2p_sessions.front());
489
5
                            m_unused_i2p_sessions.pop();
490
5
                        }
491
7
                    }
492
7
                    connected = i2p_transient_session->Connect(target_addr, conn, proxyConnectionFailed);
493
7
                    if (!connected) {
494
7
                        LOCK(m_unused_i2p_sessions_mutex);
495
7
                        if (m_unused_i2p_sessions.size() < MAX_UNUSED_I2P_SESSIONS_SIZE) {
496
7
                            m_unused_i2p_sessions.emplace(i2p_transient_session.release());
497
7
                        }
498
7
                    }
499
7
                }
500
501
10
                if (connected) {
502
0
                    sock = std::move(conn.sock);
503
0
                    addr_bind = conn.me;
504
0
                }
505
673
            } else if (use_proxy) {
506
94
                LogDebug(BCLog::PROXY, "Using proxy: %s to connect to %s\n", use_proxy->ToString(), target_addr.ToStringAddrPort());
507
94
                sock = ConnectThroughProxy(*use_proxy, target_addr.ToStringAddr(), target_addr.GetPort(), proxyConnectionFailed);
508
579
            } else {
509
                // No proxy needed (none set for target network). Private broadcast connections
510
                // must always use a proxy, otherwise they would leak the originator's IP address.
511
579
                if (Assume(conn_type != ConnectionType::PRIVATE_BROADCAST)) {
512
579
                    sock = ConnectDirectly(target_addr, conn_type == ConnectionType::MANUAL);
513
579
                }
514
579
            }
515
683
            if (!proxyConnectionFailed) {
516
                // If a connection to the node was attempted, and failure (if any) is not caused by a problem connecting to
517
                // the proxy, mark this as an attempt.
518
667
                addrman.get().Attempt(target_addr, fCountFailure);
519
667
            }
520
683
        } else if (pszDest) {
521
16
            if (const auto name_proxy = GetNameProxy()) {
522
14
                std::string host;
523
14
                uint16_t port{default_port};
524
14
                SplitHostPort(pszDest, port, host);
525
14
                bool proxyConnectionFailed;
526
14
                sock = ConnectThroughProxy(*name_proxy, host, port, proxyConnectionFailed);
527
14
            }
528
16
        }
529
        // Check any other resolved address (if any) if we fail to connect
530
699
        if (!sock) {
531
31
            continue;
532
31
        }
533
534
668
        NetPermissionFlags permission_flags = NetPermissionFlags::None;
535
668
        std::vector<NetWhitelistPermissions> whitelist_permissions = conn_type == ConnectionType::MANUAL ? vWhitelistedRangeOutgoing : std::vector<NetWhitelistPermissions>{};
536
668
        AddWhitelistPermissionFlags(permission_flags, target_addr, whitelist_permissions);
537
538
        // Add node
539
668
        NodeId id = GetNewNodeId();
540
668
        uint64_t nonce = GetDeterministicRandomizer(RANDOMIZER_ID_LOCALHOSTNONCE).Write(id).Finalize();
541
668
        if (!addr_bind.IsValid()) {
542
668
            addr_bind = GetBindAddress(*sock);
543
668
        }
544
668
        uint64_t network_id = GetDeterministicRandomizer(RANDOMIZER_ID_NETWORKKEY)
545
668
                            .Write(target_addr.GetNetClass())
546
668
                            .Write(addr_bind.GetAddrBytes())
547
                            // For outbound connections, the port of the bound address is randomly
548
                            // assigned by the OS and would therefore not be useful for seeding.
549
668
                            .Write(0)
550
668
                            .Finalize();
551
668
        CNode* pnode = new CNode(id,
552
668
                                std::move(sock),
553
668
                                target_addr,
554
668
                                CalculateKeyedNetGroup(target_addr),
555
668
                                nonce,
556
668
                                addr_bind,
557
668
                                pszDest ? pszDest : "",
558
668
                                conn_type,
559
668
                                /*inbound_onion=*/false,
560
668
                                network_id,
561
668
                                CNodeOptions{
562
668
                                    .permission_flags = permission_flags,
563
668
                                    .proxy_override = proxy_override,
564
668
                                    .i2p_sam_session = std::move(i2p_transient_session),
565
668
                                    .recv_flood_size = nReceiveFloodSize,
566
668
                                    .use_v2transport = use_v2transport,
567
668
                                });
568
668
        pnode->AddRef();
569
570
        // We're making a new connection, harvest entropy from the time (and our peer count)
571
668
        RandAddEvent((uint32_t)id);
572
573
668
        return pnode;
574
699
    }
575
576
31
    return nullptr;
577
699
}
578
579
void CNode::CloseSocketDisconnect()
580
2.47k
{
581
2.47k
    fDisconnect = true;
582
2.47k
    LOCK(m_sock_mutex);
583
2.47k
    if (m_sock) {
584
1.79k
        LogDebug(BCLog::NET, "Resetting socket for %s", LogPeer());
585
1.79k
        m_sock.reset();
586
587
1.79k
        TRACEPOINT(net, closed_connection,
588
1.79k
            GetId(),
589
1.79k
            m_addr_name.c_str(),
590
1.79k
            ConnectionTypeAsString().c_str(),
591
1.79k
            ConnectedThroughNetwork(),
592
1.79k
            TicksSinceEpoch<std::chrono::seconds>(m_connected));
593
1.79k
    }
594
2.47k
    m_i2p_sam_session.reset();
595
2.47k
}
596
597
1.79k
void CConnman::AddWhitelistPermissionFlags(NetPermissionFlags& flags, std::optional<CNetAddr> addr, const std::vector<NetWhitelistPermissions>& ranges) const {
598
1.79k
    for (const auto& subnet : ranges) {
599
378
        if (addr.has_value() && subnet.m_subnet.Match(addr.value())) {
600
378
            NetPermissions::AddFlag(flags, subnet.m_flags);
601
378
        }
602
378
    }
603
1.79k
    if (NetPermissions::HasFlag(flags, NetPermissionFlags::Implicit)) {
604
5
        NetPermissions::ClearFlag(flags, NetPermissionFlags::Implicit);
605
5
        if (whitelist_forcerelay) NetPermissions::AddFlag(flags, NetPermissionFlags::ForceRelay);
606
5
        if (whitelist_relay) NetPermissions::AddFlag(flags, NetPermissionFlags::Relay);
607
5
        NetPermissions::AddFlag(flags, NetPermissionFlags::Mempool);
608
5
        NetPermissions::AddFlag(flags, NetPermissionFlags::NoBan);
609
5
    }
610
1.79k
}
611
612
CService CNode::GetAddrLocal() const
613
22.5k
{
614
22.5k
    AssertLockNotHeld(m_addr_local_mutex);
615
22.5k
    LOCK(m_addr_local_mutex);
616
22.5k
    return m_addr_local;
617
22.5k
}
618
619
1.72k
void CNode::SetAddrLocal(const CService& addrLocalIn) {
620
1.72k
    AssertLockNotHeld(m_addr_local_mutex);
621
1.72k
    LOCK(m_addr_local_mutex);
622
1.72k
    if (Assume(!m_addr_local.IsValid())) { // Addr local can only be set once during version msg processing
623
1.72k
        m_addr_local = addrLocalIn;
624
1.72k
    }
625
1.72k
}
626
627
Network CNode::ConnectedThroughNetwork() const
628
20.9k
{
629
20.9k
    return m_inbound_onion ? NET_ONION : addr.GetNetClass();
630
20.9k
}
631
632
bool CNode::IsConnectedThroughPrivacyNet() const
633
65
{
634
65
    return m_inbound_onion || addr.IsPrivacyNet();
635
65
}
636
637
#undef X
638
416k
#define X(name) stats.name = name
639
void CNode::CopyStats(CNodeStats& stats)
640
20.8k
{
641
20.8k
    stats.nodeid = this->GetId();
642
20.8k
    X(addr);
643
20.8k
    X(addrBind);
644
20.8k
    stats.m_network = ConnectedThroughNetwork();
645
20.8k
    X(m_last_send);
646
20.8k
    X(m_last_recv);
647
20.8k
    X(m_last_tx_time);
648
20.8k
    X(m_last_block_time);
649
20.8k
    X(m_connected);
650
20.8k
    X(m_addr_name);
651
20.8k
    X(nVersion);
652
20.8k
    {
653
20.8k
        LOCK(m_subver_mutex);
654
20.8k
        X(cleanSubVer);
655
20.8k
    }
656
20.8k
    stats.fInbound = IsInboundConn();
657
20.8k
    X(m_bip152_highbandwidth_to);
658
20.8k
    X(m_bip152_highbandwidth_from);
659
20.8k
    {
660
20.8k
        LOCK(cs_vSend);
661
20.8k
        X(mapSendBytesPerMsgType);
662
20.8k
        X(nSendBytes);
663
20.8k
    }
664
20.8k
    {
665
20.8k
        LOCK(cs_vRecv);
666
20.8k
        X(mapRecvBytesPerMsgType);
667
20.8k
        X(nRecvBytes);
668
20.8k
        Transport::Info info = m_transport->GetInfo();
669
20.8k
        stats.m_transport_type = info.transport_type;
670
20.8k
        if (info.session_id) stats.m_session_id = HexStr(*info.session_id);
671
20.8k
    }
672
20.8k
    X(m_permission_flags);
673
674
20.8k
    X(m_last_ping_time);
675
20.8k
    X(m_min_ping_time);
676
677
    // Leave string empty if addrLocal invalid (not filled in yet)
678
20.8k
    CService addrLocalUnlocked = GetAddrLocal();
679
20.8k
    stats.addrLocal = addrLocalUnlocked.IsValid() ? addrLocalUnlocked.ToStringAddrPort() : "";
680
681
20.8k
    X(m_conn_type);
682
20.8k
}
683
#undef X
684
685
bool CNode::ReceiveMsgBytes(std::span<const uint8_t> msg_bytes, bool& complete)
686
153k
{
687
153k
    complete = false;
688
153k
    const auto time{NodeClock::now()};
689
153k
    LOCK(cs_vRecv);
690
153k
    m_last_recv = time;
691
153k
    nRecvBytes += msg_bytes.size();
692
445k
    while (msg_bytes.size() > 0) {
693
        // absorb network data
694
292k
        if (!m_transport->ReceivedBytes(msg_bytes)) {
695
            // Serious transport problem, disconnect from the peer.
696
10
            return false;
697
10
        }
698
699
292k
        if (m_transport->ReceivedMessageComplete()) {
700
            // decompose a transport agnostic CNetMessage from the deserializer
701
141k
            bool reject_message{false};
702
141k
            CNetMessage msg = m_transport->GetReceivedMessage(time, reject_message);
703
141k
            if (reject_message) {
704
                // Message deserialization failed. Drop the message but don't disconnect the peer.
705
                // store the size of the corrupt message
706
82
                mapRecvBytesPerMsgType.at(NET_MESSAGE_TYPE_OTHER) += msg.m_raw_message_size;
707
82
                continue;
708
82
            }
709
710
            // Store received bytes per message type.
711
            // To prevent a memory DOS, only allow known message types.
712
141k
            auto i = mapRecvBytesPerMsgType.find(msg.m_type);
713
141k
            if (i == mapRecvBytesPerMsgType.end()) {
714
6
                i = mapRecvBytesPerMsgType.find(NET_MESSAGE_TYPE_OTHER);
715
6
            }
716
141k
            assert(i != mapRecvBytesPerMsgType.end());
717
141k
            i->second += msg.m_raw_message_size;
718
719
            // push the message to the process queue,
720
141k
            vRecvMsg.push_back(std::move(msg));
721
722
141k
            complete = true;
723
141k
        }
724
292k
    }
725
726
153k
    return true;
727
153k
}
728
729
std::string CNode::LogPeer() const
730
27.8k
{
731
27.8k
    auto peer_info{strprintf("peer=%d", GetId())};
732
27.8k
    if (fLogIPs) {
733
22
        return strprintf("%s, peeraddr=%s", peer_info, addr.ToStringAddrPort());
734
27.8k
    } else {
735
27.8k
        return peer_info;
736
27.8k
    }
737
27.8k
}
738
739
std::string CNode::DisconnectMsg() const
740
1.69k
{
741
1.69k
    return strprintf("disconnecting %s", LogPeer());
742
1.69k
}
743
744
V1Transport::V1Transport(const NodeId node_id) noexcept
745
1.94k
    : m_magic_bytes{Params().MessageStart()}, m_node_id{node_id}
746
1.94k
{
747
1.94k
    LOCK(m_recv_mutex);
748
1.94k
    Reset();
749
1.94k
}
750
751
Transport::Info V1Transport::GetInfo() const noexcept
752
19.7k
{
753
19.7k
    return {.transport_type = TransportProtocolType::V1, .session_id = {}};
754
19.7k
}
755
756
int V1Transport::readHeader(std::span<const uint8_t> msg_bytes)
757
132k
{
758
132k
    AssertLockHeld(m_recv_mutex);
759
    // copy data to temporary parsing buffer
760
132k
    unsigned int nRemaining = CMessageHeader::HEADER_SIZE - nHdrPos;
761
132k
    unsigned int nCopy = std::min<unsigned int>(nRemaining, msg_bytes.size());
762
763
132k
    memcpy(&hdrbuf[nHdrPos], msg_bytes.data(), nCopy);
764
132k
    nHdrPos += nCopy;
765
766
    // if header incomplete, exit
767
132k
    if (nHdrPos < CMessageHeader::HEADER_SIZE)
768
10
        return nCopy;
769
770
    // deserialize to CMessageHeader
771
132k
    try {
772
132k
        hdrbuf >> hdr;
773
132k
    }
774
132k
    catch (const std::exception&) {
775
0
        LogDebug(BCLog::NET, "Header error: Unable to deserialize, peer=%d\n", m_node_id);
776
0
        return -1;
777
0
    }
778
779
    // Check start string, network magic
780
132k
    if (hdr.pchMessageStart != m_magic_bytes) {
781
2
        LogDebug(BCLog::NET, "Header error: Wrong MessageStart %s received, peer=%d\n", HexStr(hdr.pchMessageStart), m_node_id);
782
2
        return -1;
783
2
    }
784
785
    // reject messages larger than MAX_SIZE or MAX_PROTOCOL_MESSAGE_LENGTH
786
    // NOTE: failing to perform this check previously allowed a malicious peer to make us allocate 32MiB of memory per
787
    // connection. See https://bitcoincore.org/en/2024/07/03/disclose_receive_buffer_oom.
788
132k
    if (hdr.nMessageSize > MAX_SIZE || hdr.nMessageSize > MAX_PROTOCOL_MESSAGE_LENGTH) {
789
3
        LogDebug(BCLog::NET, "Header error: Size too large (%s, %u bytes), peer=%d\n", SanitizeString(hdr.GetMessageType()), hdr.nMessageSize, m_node_id);
790
3
        return -1;
791
3
    }
792
793
    // switch state to reading message data
794
132k
    in_data = true;
795
796
132k
    return nCopy;
797
132k
}
798
799
int V1Transport::readData(std::span<const uint8_t> msg_bytes)
800
150k
{
801
150k
    AssertLockHeld(m_recv_mutex);
802
150k
    unsigned int nRemaining = hdr.nMessageSize - nDataPos;
803
150k
    unsigned int nCopy = std::min<unsigned int>(nRemaining, msg_bytes.size());
804
805
150k
    if (vRecv.size() < nDataPos + nCopy) {
806
        // Allocate up to 256 KiB ahead, but never more than the total message size.
807
131k
        vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024));
808
131k
    }
809
810
150k
    hasher.Write(msg_bytes.first(nCopy));
811
150k
    memcpy(&vRecv[nDataPos], msg_bytes.data(), nCopy);
812
150k
    nDataPos += nCopy;
813
814
150k
    return nCopy;
815
150k
}
816
817
const uint256& V1Transport::GetMessageHash() const
818
132k
{
819
132k
    AssertLockHeld(m_recv_mutex);
820
132k
    assert(CompleteInternal());
821
132k
    if (data_hash.IsNull())
822
132k
        hasher.Finalize(data_hash);
823
132k
    return data_hash;
824
132k
}
825
826
CNetMessage V1Transport::GetReceivedMessage(NodeClock::time_point time, bool& reject_message)
827
132k
{
828
132k
    AssertLockNotHeld(m_recv_mutex);
829
    // Initialize out parameter
830
132k
    reject_message = false;
831
    // decompose a single CNetMessage from the TransportDeserializer
832
132k
    LOCK(m_recv_mutex);
833
132k
    CNetMessage msg(std::move(vRecv));
834
835
    // store message type string, time, and sizes
836
132k
    msg.m_type = hdr.GetMessageType();
837
132k
    msg.m_time = time;
838
132k
    msg.m_message_size = hdr.nMessageSize;
839
132k
    msg.m_raw_message_size = hdr.nMessageSize + CMessageHeader::HEADER_SIZE;
840
841
132k
    uint256 hash = GetMessageHash();
842
843
    // We just received a message off the wire, harvest entropy from the time (and the message checksum)
844
132k
    RandAddEvent(ReadLE32(hash.begin()));
845
846
    // Check checksum and header message type string
847
132k
    if (memcmp(hash.begin(), hdr.pchChecksum, CMessageHeader::CHECKSUM_SIZE) != 0) {
848
1
        LogDebug(BCLog::NET, "Header error: Wrong checksum (%s, %u bytes), expected %s was %s, peer=%d\n",
849
1
                 SanitizeString(msg.m_type), msg.m_message_size,
850
1
                 HexStr(std::span{hash}.first(CMessageHeader::CHECKSUM_SIZE)),
851
1
                 HexStr(hdr.pchChecksum),
852
1
                 m_node_id);
853
1
        reject_message = true;
854
132k
    } else if (!hdr.IsMessageTypeValid()) {
855
81
        LogDebug(BCLog::NET, "Header error: Invalid message type (%s, %u bytes), peer=%d\n",
856
81
                 SanitizeString(hdr.GetMessageType()), msg.m_message_size, m_node_id);
857
81
        reject_message = true;
858
81
    }
859
860
    // Always reset the network deserializer (prepare for the next message)
861
132k
    Reset();
862
132k
    return msg;
863
132k
}
864
865
bool V1Transport::SetMessageToSend(CSerializedNetMsg& msg) noexcept
866
141k
{
867
141k
    AssertLockNotHeld(m_send_mutex);
868
    // Determine whether a new message can be set.
869
141k
    LOCK(m_send_mutex);
870
141k
    if (m_sending_header || m_bytes_sent < m_message_to_send.data.size()) return false;
871
872
    // create dbl-sha256 checksum
873
141k
    uint256 hash = Hash(msg.data);
874
875
    // create header
876
141k
    CMessageHeader hdr(m_magic_bytes, msg.m_type.c_str(), msg.data.size());
877
141k
    memcpy(hdr.pchChecksum, hash.begin(), CMessageHeader::CHECKSUM_SIZE);
878
879
    // serialize header
880
141k
    m_header_to_send.clear();
881
141k
    VectorWriter{m_header_to_send, 0, hdr};
882
883
    // update state
884
141k
    m_message_to_send = std::move(msg);
885
141k
    m_sending_header = true;
886
141k
    m_bytes_sent = 0;
887
141k
    return true;
888
141k
}
889
890
Transport::BytesToSend V1Transport::GetBytesToSend(bool have_next_message) const noexcept
891
975k
{
892
975k
    AssertLockNotHeld(m_send_mutex);
893
975k
    LOCK(m_send_mutex);
894
975k
    if (m_sending_header) {
895
141k
        return {std::span{m_header_to_send}.subspan(m_bytes_sent),
896
                // We have more to send after the header if the message has payload, or if there
897
                // is a next message after that.
898
141k
                have_next_message || !m_message_to_send.data.empty(),
899
141k
                m_message_to_send.m_type
900
141k
               };
901
833k
    } else {
902
833k
        return {std::span{m_message_to_send.data}.subspan(m_bytes_sent),
903
                // We only have more to send after this message's payload if there is another
904
                // message.
905
833k
                have_next_message,
906
833k
                m_message_to_send.m_type
907
833k
               };
908
833k
    }
909
975k
}
910
911
void V1Transport::MarkBytesSent(size_t bytes_sent) noexcept
912
276k
{
913
276k
    AssertLockNotHeld(m_send_mutex);
914
276k
    LOCK(m_send_mutex);
915
276k
    m_bytes_sent += bytes_sent;
916
276k
    if (m_sending_header && m_bytes_sent == m_header_to_send.size()) {
917
        // We're done sending a message's header. Switch to sending its data bytes.
918
141k
        m_sending_header = false;
919
141k
        m_bytes_sent = 0;
920
141k
    } else if (!m_sending_header && m_bytes_sent == m_message_to_send.data.size()) {
921
        // We're done sending a message's data. Wipe the data vector to reduce memory consumption.
922
135k
        ClearShrink(m_message_to_send.data);
923
135k
        m_bytes_sent = 0;
924
135k
    }
925
276k
}
926
927
size_t V1Transport::GetSendMemoryUsage() const noexcept
928
282k
{
929
282k
    AssertLockNotHeld(m_send_mutex);
930
282k
    LOCK(m_send_mutex);
931
    // Don't count sending-side fields besides m_message_to_send, as they're all small and bounded.
932
282k
    return m_message_to_send.GetMemoryUsage();
933
282k
}
934
935
namespace {
936
937
/** List of short messages as defined in BIP324, in order.
938
 *
939
 * Only message types that are actually implemented in this codebase need to be listed, as other
940
 * messages get ignored anyway - whether we know how to decode them or not.
941
 */
942
const std::array<std::string, BIP324_SHORTIDS_IMPLEMENTED> V2_MESSAGE_IDS = {
943
    "", // 12 bytes follow encoding the message type like in V1
944
    NetMsgType::ADDR,
945
    NetMsgType::BLOCK,
946
    NetMsgType::BLOCKTXN,
947
    NetMsgType::CMPCTBLOCK,
948
    NetMsgType::FEEFILTER,
949
    NetMsgType::FILTERADD,
950
    NetMsgType::FILTERCLEAR,
951
    NetMsgType::FILTERLOAD,
952
    NetMsgType::GETBLOCKS,
953
    NetMsgType::GETBLOCKTXN,
954
    NetMsgType::GETDATA,
955
    NetMsgType::GETHEADERS,
956
    NetMsgType::HEADERS,
957
    NetMsgType::INV,
958
    NetMsgType::MEMPOOL,
959
    NetMsgType::MERKLEBLOCK,
960
    NetMsgType::NOTFOUND,
961
    NetMsgType::PING,
962
    NetMsgType::PONG,
963
    NetMsgType::SENDCMPCT,
964
    NetMsgType::TX,
965
    NetMsgType::GETCFILTERS,
966
    NetMsgType::CFILTER,
967
    NetMsgType::GETCFHEADERS,
968
    NetMsgType::CFHEADERS,
969
    NetMsgType::GETCFCHECKPT,
970
    NetMsgType::CFCHECKPT,
971
    NetMsgType::ADDRV2,
972
    "", "", "", // Unimplemented message types 29-31
973
    "", "", "", "", // Unimplemented message types 32-35
974
    "",  // Unimplemented message type 36
975
    NetMsgType::FEATURE,
976
};
977
978
class V2MessageMap
979
{
980
    std::unordered_map<std::string, uint8_t> m_map;
981
982
public:
983
    V2MessageMap() noexcept
984
1.47k
    {
985
56.0k
        for (size_t i = 1; i < std::size(V2_MESSAGE_IDS); ++i) {
986
54.6k
            m_map.emplace(V2_MESSAGE_IDS[i], i);
987
54.6k
        }
988
1.47k
    }
989
990
    std::optional<uint8_t> operator()(const std::string& message_name) const noexcept
991
9.91k
    {
992
9.91k
        auto it = m_map.find(message_name);
993
9.91k
        if (it == m_map.end()) return std::nullopt;
994
8.99k
        return it->second;
995
9.91k
    }
996
};
997
998
const V2MessageMap V2_MESSAGE_MAP;
999
1000
std::vector<uint8_t> GenerateRandomGarbage() noexcept
1001
286
{
1002
286
    std::vector<uint8_t> ret;
1003
286
    FastRandomContext rng;
1004
286
    ret.resize(rng.randrange(V2Transport::MAX_GARBAGE_LEN + 1));
1005
286
    rng.fillrand(MakeWritableByteSpan(ret));
1006
286
    return ret;
1007
286
}
1008
1009
} // namespace
1010
1011
void V2Transport::StartSendingHandshake() noexcept
1012
280
{
1013
280
    AssertLockHeld(m_send_mutex);
1014
280
    Assume(m_send_state == SendState::AWAITING_KEY);
1015
280
    Assume(m_send_buffer.empty());
1016
    // Initialize the send buffer with ellswift pubkey + provided garbage.
1017
280
    m_send_buffer.resize(EllSwiftPubKey::size() + m_send_garbage.size());
1018
280
    std::copy(std::begin(m_cipher.GetOurPubKey()), std::end(m_cipher.GetOurPubKey()), MakeWritableByteSpan(m_send_buffer).begin());
1019
280
    std::copy(m_send_garbage.begin(), m_send_garbage.end(), m_send_buffer.begin() + EllSwiftPubKey::size());
1020
    // We cannot wipe m_send_garbage as it will still be used as AAD later in the handshake.
1021
280
}
1022
1023
V2Transport::V2Transport(NodeId nodeid, bool initiating, const CKey& key, std::span<const std::byte> ent32, std::vector<uint8_t> garbage) noexcept
1024
286
    : m_cipher{key, ent32},
1025
286
      m_initiating{initiating},
1026
286
      m_nodeid{nodeid},
1027
286
      m_v1_fallback{nodeid},
1028
286
      m_recv_state{initiating ? RecvState::KEY : RecvState::KEY_MAYBE_V1},
1029
286
      m_send_garbage{std::move(garbage)},
1030
286
      m_send_state{initiating ? SendState::AWAITING_KEY : SendState::MAYBE_V1}
1031
286
{
1032
286
    Assume(m_send_garbage.size() <= MAX_GARBAGE_LEN);
1033
    // Start sending immediately if we're the initiator of the connection.
1034
286
    if (initiating) {
1035
135
        LOCK(m_send_mutex);
1036
135
        StartSendingHandshake();
1037
135
    }
1038
286
}
1039
1040
V2Transport::V2Transport(NodeId nodeid, bool initiating) noexcept
1041
286
    : V2Transport{nodeid, initiating, GenerateRandomKey(),
1042
286
                  MakeByteSpan(GetRandHash()), GenerateRandomGarbage()} {}
1043
1044
void V2Transport::SetReceiveState(RecvState recv_state) noexcept
1045
19.6k
{
1046
19.6k
    AssertLockHeld(m_recv_mutex);
1047
    // Enforce allowed state transitions.
1048
19.6k
    switch (m_recv_state) {
1049
151
    case RecvState::KEY_MAYBE_V1:
1050
151
        Assume(recv_state == RecvState::KEY || recv_state == RecvState::V1);
1051
151
        break;
1052
271
    case RecvState::KEY:
1053
271
        Assume(recv_state == RecvState::GARB_GARBTERM);
1054
271
        break;
1055
265
    case RecvState::GARB_GARBTERM:
1056
265
        Assume(recv_state == RecvState::VERSION);
1057
265
        break;
1058
263
    case RecvState::VERSION:
1059
263
        Assume(recv_state == RecvState::APP);
1060
263
        break;
1061
9.34k
    case RecvState::APP:
1062
9.34k
        Assume(recv_state == RecvState::APP_READY);
1063
9.34k
        break;
1064
9.34k
    case RecvState::APP_READY:
1065
9.34k
        Assume(recv_state == RecvState::APP);
1066
9.34k
        break;
1067
0
    case RecvState::V1:
1068
0
        Assume(false); // V1 state cannot be left
1069
0
        break;
1070
19.6k
    }
1071
    // Change state.
1072
19.6k
    m_recv_state = recv_state;
1073
19.6k
}
1074
1075
void V2Transport::SetSendState(SendState send_state) noexcept
1076
422
{
1077
422
    AssertLockHeld(m_send_mutex);
1078
    // Enforce allowed state transitions.
1079
422
    switch (m_send_state) {
1080
151
    case SendState::MAYBE_V1:
1081
151
        Assume(send_state == SendState::V1 || send_state == SendState::AWAITING_KEY);
1082
151
        break;
1083
271
    case SendState::AWAITING_KEY:
1084
271
        Assume(send_state == SendState::READY);
1085
271
        break;
1086
0
    case SendState::READY:
1087
0
    case SendState::V1:
1088
0
        Assume(false); // Final states
1089
0
        break;
1090
422
    }
1091
    // Change state.
1092
422
    m_send_state = send_state;
1093
422
}
1094
1095
bool V2Transport::ReceivedMessageComplete() const noexcept
1096
13.0k
{
1097
13.0k
    AssertLockNotHeld(m_recv_mutex);
1098
13.0k
    LOCK(m_recv_mutex);
1099
13.0k
    if (m_recv_state == RecvState::V1) return m_v1_fallback.ReceivedMessageComplete();
1100
1101
12.6k
    return m_recv_state == RecvState::APP_READY;
1102
13.0k
}
1103
1104
void V2Transport::ProcessReceivedMaybeV1Bytes() noexcept
1105
154
{
1106
154
    AssertLockHeld(m_recv_mutex);
1107
154
    AssertLockNotHeld(m_send_mutex);
1108
154
    Assume(m_recv_state == RecvState::KEY_MAYBE_V1);
1109
    // We still have to determine if this is a v1 or v2 connection. The bytes being received could
1110
    // be the beginning of either a v1 packet (network magic + "version\x00\x00\x00\x00\x00"), or
1111
    // of a v2 public key. BIP324 specifies that a mismatch with this 16-byte string should trigger
1112
    // sending of the key.
1113
154
    std::array<uint8_t, V1_PREFIX_LEN> v1_prefix = {0, 0, 0, 0, 'v', 'e', 'r', 's', 'i', 'o', 'n', 0, 0, 0, 0, 0};
1114
154
    std::copy(std::begin(Params().MessageStart()), std::end(Params().MessageStart()), v1_prefix.begin());
1115
154
    Assume(m_recv_buffer.size() <= v1_prefix.size());
1116
154
    if (!std::equal(m_recv_buffer.begin(), m_recv_buffer.end(), v1_prefix.begin())) {
1117
        // Mismatch with v1 prefix, so we can assume a v2 connection.
1118
145
        SetReceiveState(RecvState::KEY); // Convert to KEY state, leaving received bytes around.
1119
        // Transition the sender to AWAITING_KEY state and start sending.
1120
145
        LOCK(m_send_mutex);
1121
145
        SetSendState(SendState::AWAITING_KEY);
1122
145
        StartSendingHandshake();
1123
145
    } else if (m_recv_buffer.size() == v1_prefix.size()) {
1124
        // Full match with the v1 prefix, so fall back to v1 behavior.
1125
6
        LOCK(m_send_mutex);
1126
6
        std::span<const uint8_t> feedback{m_recv_buffer};
1127
        // Feed already received bytes to v1 transport. It should always accept these, because it's
1128
        // less than the size of a v1 header, and these are the first bytes fed to m_v1_fallback.
1129
6
        bool ret = m_v1_fallback.ReceivedBytes(feedback);
1130
6
        Assume(feedback.empty());
1131
6
        Assume(ret);
1132
6
        SetReceiveState(RecvState::V1);
1133
6
        SetSendState(SendState::V1);
1134
        // Reset v2 transport buffers to save memory.
1135
6
        ClearShrink(m_recv_buffer);
1136
6
        ClearShrink(m_send_buffer);
1137
6
    } else {
1138
        // We have not received enough to distinguish v1 from v2 yet. Wait until more bytes come.
1139
3
    }
1140
154
}
1141
1142
bool V2Transport::ProcessReceivedKeyBytes() noexcept
1143
338
{
1144
338
    AssertLockHeld(m_recv_mutex);
1145
338
    AssertLockNotHeld(m_send_mutex);
1146
338
    Assume(m_recv_state == RecvState::KEY);
1147
338
    Assume(m_recv_buffer.size() <= EllSwiftPubKey::size());
1148
1149
    // As a special exception, if bytes 4-16 of the key on a responder connection match the
1150
    // corresponding bytes of a V1 version message, but bytes 0-4 don't match the network magic
1151
    // (if they did, we'd have switched to V1 state already), assume this is a peer from
1152
    // another network, and disconnect them. They will almost certainly disconnect us too when
1153
    // they receive our uniformly random key and garbage, but detecting this case specially
1154
    // means we can log it.
1155
338
    static constexpr std::array<uint8_t, 12> MATCH = {'v', 'e', 'r', 's', 'i', 'o', 'n', 0, 0, 0, 0, 0};
1156
338
    static constexpr size_t OFFSET = std::tuple_size_v<MessageStartChars>;
1157
338
    if (!m_initiating && m_recv_buffer.size() >= OFFSET + MATCH.size()) {
1158
180
        if (std::equal(MATCH.begin(), MATCH.end(), m_recv_buffer.begin() + OFFSET)) {
1159
2
            LogDebug(BCLog::NET, "V2 transport error: V1 peer with wrong MessageStart %s\n",
1160
2
                     HexStr(std::span(m_recv_buffer).first(OFFSET)));
1161
2
            return false;
1162
2
        }
1163
180
    }
1164
1165
336
    if (m_recv_buffer.size() == EllSwiftPubKey::size()) {
1166
        // Other side's key has been fully received, and can now be Diffie-Hellman combined with
1167
        // our key to initialize the encryption ciphers.
1168
1169
        // Initialize the ciphers.
1170
271
        EllSwiftPubKey ellswift(MakeByteSpan(m_recv_buffer));
1171
271
        LOCK(m_send_mutex);
1172
271
        m_cipher.Initialize(ellswift, m_initiating);
1173
1174
        // Switch receiver state to GARB_GARBTERM.
1175
271
        SetReceiveState(RecvState::GARB_GARBTERM);
1176
271
        m_recv_buffer.clear();
1177
1178
        // Switch sender state to READY.
1179
271
        SetSendState(SendState::READY);
1180
1181
        // Append the garbage terminator to the send buffer.
1182
271
        m_send_buffer.resize(m_send_buffer.size() + BIP324Cipher::GARBAGE_TERMINATOR_LEN);
1183
271
        std::copy(m_cipher.GetSendGarbageTerminator().begin(),
1184
271
                  m_cipher.GetSendGarbageTerminator().end(),
1185
271
                  MakeWritableByteSpan(m_send_buffer).last(BIP324Cipher::GARBAGE_TERMINATOR_LEN).begin());
1186
1187
        // Construct version packet in the send buffer, with the sent garbage data as AAD.
1188
271
        m_send_buffer.resize(m_send_buffer.size() + BIP324Cipher::EXPANSION + VERSION_CONTENTS.size());
1189
271
        m_cipher.Encrypt(
1190
271
            /*contents=*/VERSION_CONTENTS,
1191
271
            /*aad=*/MakeByteSpan(m_send_garbage),
1192
271
            /*ignore=*/false,
1193
271
            /*output=*/MakeWritableByteSpan(m_send_buffer).last(BIP324Cipher::EXPANSION + VERSION_CONTENTS.size()));
1194
        // We no longer need the garbage.
1195
271
        ClearShrink(m_send_garbage);
1196
271
    } else {
1197
        // We still have to receive more key bytes.
1198
65
    }
1199
336
    return true;
1200
338
}
1201
1202
bool V2Transport::ProcessReceivedGarbageBytes() noexcept
1203
515k
{
1204
515k
    AssertLockHeld(m_recv_mutex);
1205
515k
    Assume(m_recv_state == RecvState::GARB_GARBTERM);
1206
515k
    Assume(m_recv_buffer.size() <= MAX_GARBAGE_LEN + BIP324Cipher::GARBAGE_TERMINATOR_LEN);
1207
515k
    if (m_recv_buffer.size() >= BIP324Cipher::GARBAGE_TERMINATOR_LEN) {
1208
511k
        if (std::ranges::equal(MakeByteSpan(m_recv_buffer).last(BIP324Cipher::GARBAGE_TERMINATOR_LEN), m_cipher.GetReceiveGarbageTerminator())) {
1209
            // Garbage terminator received. Store garbage to authenticate it as AAD later.
1210
265
            m_recv_aad = std::move(m_recv_buffer);
1211
265
            m_recv_aad.resize(m_recv_aad.size() - BIP324Cipher::GARBAGE_TERMINATOR_LEN);
1212
265
            m_recv_buffer.clear();
1213
265
            SetReceiveState(RecvState::VERSION);
1214
511k
        } else if (m_recv_buffer.size() == MAX_GARBAGE_LEN + BIP324Cipher::GARBAGE_TERMINATOR_LEN) {
1215
            // We've reached the maximum length for garbage + garbage terminator, and the
1216
            // terminator still does not match. Abort.
1217
4
            LogDebug(BCLog::NET, "V2 transport error: missing garbage terminator, peer=%d\n", m_nodeid);
1218
4
            return false;
1219
511k
        } else {
1220
            // We still need to receive more garbage and/or garbage terminator bytes.
1221
511k
        }
1222
511k
    } else {
1223
        // We have less than GARBAGE_TERMINATOR_LEN (16) bytes, so we certainly need to receive
1224
        // more first.
1225
4.06k
    }
1226
515k
    return true;
1227
515k
}
1228
1229
bool V2Transport::ProcessReceivedPacketBytes() noexcept
1230
128k
{
1231
128k
    AssertLockHeld(m_recv_mutex);
1232
128k
    Assume(m_recv_state == RecvState::VERSION || m_recv_state == RecvState::APP);
1233
1234
    // The maximum permitted contents length for a packet, consisting of:
1235
    // - 0x00 byte: indicating long message type encoding
1236
    // - 12 bytes of message type
1237
    // - payload
1238
128k
    static constexpr size_t MAX_CONTENTS_LEN =
1239
128k
        1 + CMessageHeader::MESSAGE_TYPE_SIZE +
1240
128k
        std::min<size_t>(MAX_SIZE, MAX_PROTOCOL_MESSAGE_LENGTH);
1241
1242
128k
    if (m_recv_buffer.size() == BIP324Cipher::LENGTH_LEN) {
1243
        // Length descriptor received.
1244
63.4k
        m_recv_len = m_cipher.DecryptLength(MakeByteSpan(m_recv_buffer));
1245
63.4k
        if (m_recv_len > MAX_CONTENTS_LEN) {
1246
10
            LogDebug(BCLog::NET, "V2 transport error: packet too large (%u bytes), peer=%d\n", m_recv_len, m_nodeid);
1247
10
            return false;
1248
10
        }
1249
65.0k
    } else if (m_recv_buffer.size() > BIP324Cipher::LENGTH_LEN && m_recv_buffer.size() == m_recv_len + BIP324Cipher::EXPANSION) {
1250
        // Ciphertext received, decrypt it into m_recv_decode_buffer.
1251
        // Note that it is impossible to reach this branch without hitting the branch above first,
1252
        // as GetMaxBytesToProcess only allows up to LENGTH_LEN into the buffer before that point.
1253
63.4k
        m_recv_decode_buffer.resize(m_recv_len);
1254
63.4k
        bool ignore{false};
1255
63.4k
        bool ret = m_cipher.Decrypt(
1256
63.4k
            /*input=*/MakeByteSpan(m_recv_buffer).subspan(BIP324Cipher::LENGTH_LEN),
1257
63.4k
            /*aad=*/MakeByteSpan(m_recv_aad),
1258
63.4k
            /*ignore=*/ignore,
1259
63.4k
            /*contents=*/MakeWritableByteSpan(m_recv_decode_buffer));
1260
63.4k
        if (!ret) {
1261
12
            LogDebug(BCLog::NET, "V2 transport error: packet decryption failure (%u bytes), peer=%d\n", m_recv_len, m_nodeid);
1262
12
            return false;
1263
12
        }
1264
        // We have decrypted a valid packet with the AAD we expected, so clear the expected AAD.
1265
63.4k
        ClearShrink(m_recv_aad);
1266
        // Feed the last 4 bytes of the Poly1305 authentication tag (and its timing) into our RNG.
1267
63.4k
        RandAddEvent(ReadLE32(m_recv_buffer.data() + m_recv_buffer.size() - 4));
1268
1269
        // At this point we have a valid packet decrypted into m_recv_decode_buffer. If it's not a
1270
        // decoy, which we simply ignore, use the current state to decide what to do with it.
1271
63.4k
        if (!ignore) {
1272
9.61k
            switch (m_recv_state) {
1273
263
            case RecvState::VERSION:
1274
                // Version message received; transition to application phase. The contents is
1275
                // ignored, but can be used for future extensions.
1276
263
                SetReceiveState(RecvState::APP);
1277
263
                break;
1278
9.34k
            case RecvState::APP:
1279
                // Application message decrypted correctly. It can be extracted using GetMessage().
1280
9.34k
                SetReceiveState(RecvState::APP_READY);
1281
9.34k
                break;
1282
0
            default:
1283
                // Any other state is invalid (this function should not have been called).
1284
0
                Assume(false);
1285
9.61k
            }
1286
9.61k
        }
1287
        // Wipe the receive buffer where the next packet will be received into.
1288
63.4k
        ClearShrink(m_recv_buffer);
1289
        // In all but APP_READY state, we can wipe the decoded contents.
1290
63.4k
        if (m_recv_state != RecvState::APP_READY) ClearShrink(m_recv_decode_buffer);
1291
63.4k
    } else {
1292
        // We either have less than 3 bytes, so we don't know the packet's length yet, or more
1293
        // than 3 bytes but less than the packet's full ciphertext. Wait until those arrive.
1294
1.51k
    }
1295
128k
    return true;
1296
128k
}
1297
1298
size_t V2Transport::GetMaxBytesToProcess() noexcept
1299
645k
{
1300
645k
    AssertLockHeld(m_recv_mutex);
1301
645k
    switch (m_recv_state) {
1302
154
    case RecvState::KEY_MAYBE_V1:
1303
        // During the KEY_MAYBE_V1 state we do not allow more than the length of v1 prefix into the
1304
        // receive buffer.
1305
154
        Assume(m_recv_buffer.size() <= V1_PREFIX_LEN);
1306
        // As long as we're not sure if this is a v1 or v2 connection, don't receive more than what
1307
        // is strictly necessary to distinguish the two (16 bytes). If we permitted more than
1308
        // the v1 header size (24 bytes), we may not be able to feed the already-received bytes
1309
        // back into the m_v1_fallback V1 transport.
1310
154
        return V1_PREFIX_LEN - m_recv_buffer.size();
1311
338
    case RecvState::KEY:
1312
        // During the KEY state, we only allow the 64-byte key into the receive buffer.
1313
338
        Assume(m_recv_buffer.size() <= EllSwiftPubKey::size());
1314
        // As long as we have not received the other side's public key, don't receive more than
1315
        // that (64 bytes), as garbage follows, and locating the garbage terminator requires the
1316
        // key exchange first.
1317
338
        return EllSwiftPubKey::size() - m_recv_buffer.size();
1318
515k
    case RecvState::GARB_GARBTERM:
1319
        // Process garbage bytes one by one (because terminator may appear anywhere).
1320
515k
        return 1;
1321
2.19k
    case RecvState::VERSION:
1322
128k
    case RecvState::APP:
1323
        // These three states all involve decoding a packet. Process the length descriptor first,
1324
        // so that we know where the current packet ends (and we don't process bytes from the next
1325
        // packet or decoy yet). Then, process the ciphertext bytes of the current packet.
1326
128k
        if (m_recv_buffer.size() < BIP324Cipher::LENGTH_LEN) {
1327
63.5k
            return BIP324Cipher::LENGTH_LEN - m_recv_buffer.size();
1328
64.9k
        } else {
1329
            // Note that BIP324Cipher::EXPANSION is the total difference between contents size
1330
            // and encoded packet size, which includes the 3 bytes due to the packet length.
1331
            // When transitioning from receiving the packet length to receiving its ciphertext,
1332
            // the encrypted packet length is left in the receive buffer.
1333
64.9k
            return BIP324Cipher::EXPANSION + m_recv_len - m_recv_buffer.size();
1334
64.9k
        }
1335
1.03k
    case RecvState::APP_READY:
1336
        // No bytes can be processed until GetMessage() is called.
1337
1.03k
        return 0;
1338
0
    case RecvState::V1:
1339
        // Not allowed (must be dealt with by the caller).
1340
0
        Assume(false);
1341
0
        return 0;
1342
645k
    }
1343
0
    Assume(false); // unreachable
1344
0
    return 0;
1345
645k
}
1346
1347
bool V2Transport::ReceivedBytes(std::span<const uint8_t>& msg_bytes) noexcept
1348
12.3k
{
1349
12.3k
    AssertLockNotHeld(m_recv_mutex);
1350
    /** How many bytes to allocate in the receive buffer at most above what is received so far. */
1351
12.3k
    static constexpr size_t MAX_RESERVE_AHEAD = 256 * 1024;
1352
1353
12.3k
    LOCK(m_recv_mutex);
1354
12.3k
    if (m_recv_state == RecvState::V1) return m_v1_fallback.ReceivedBytes(msg_bytes);
1355
1356
    // Process the provided bytes in msg_bytes in a loop. In each iteration a nonzero number of
1357
    // bytes (decided by GetMaxBytesToProcess) are taken from the beginning om msg_bytes, and
1358
    // appended to m_recv_buffer. Then, depending on the receiver state, one of the
1359
    // ProcessReceived*Bytes functions is called to process the bytes in that buffer.
1360
656k
    while (!msg_bytes.empty()) {
1361
        // Decide how many bytes to copy from msg_bytes to m_recv_buffer.
1362
645k
        size_t max_read = GetMaxBytesToProcess();
1363
1364
        // Reserve space in the buffer if there is not enough.
1365
645k
        if (m_recv_buffer.size() + std::min(msg_bytes.size(), max_read) > m_recv_buffer.capacity()) {
1366
127k
            switch (m_recv_state) {
1367
151
            case RecvState::KEY_MAYBE_V1:
1368
279
            case RecvState::KEY:
1369
279
            case RecvState::GARB_GARBTERM:
1370
                // During the initial states (key/garbage), allocate once to fit the maximum (4111
1371
                // bytes).
1372
279
                m_recv_buffer.reserve(MAX_GARBAGE_LEN + BIP324Cipher::GARBAGE_TERMINATOR_LEN);
1373
279
                break;
1374
1.82k
            case RecvState::VERSION:
1375
127k
            case RecvState::APP: {
1376
                // During states where a packet is being received, as much as is expected but never
1377
                // more than MAX_RESERVE_AHEAD bytes in addition to what is received so far.
1378
                // This means attackers that want to cause us to waste allocated memory are limited
1379
                // to MAX_RESERVE_AHEAD above the largest allowed message contents size, and to
1380
                // MAX_RESERVE_AHEAD more than they've actually sent us.
1381
127k
                size_t alloc_add = std::min(max_read, msg_bytes.size() + MAX_RESERVE_AHEAD);
1382
127k
                m_recv_buffer.reserve(m_recv_buffer.size() + alloc_add);
1383
127k
                break;
1384
1.82k
            }
1385
0
            case RecvState::APP_READY:
1386
                // The buffer is empty in this state.
1387
0
                Assume(m_recv_buffer.empty());
1388
0
                break;
1389
0
            case RecvState::V1:
1390
                // Should have bailed out above.
1391
0
                Assume(false);
1392
0
                break;
1393
127k
            }
1394
127k
        }
1395
1396
        // Can't read more than provided input.
1397
645k
        max_read = std::min(msg_bytes.size(), max_read);
1398
        // Copy data to buffer.
1399
645k
        m_recv_buffer.insert(m_recv_buffer.end(), UCharCast(msg_bytes.data()), UCharCast(msg_bytes.data() + max_read));
1400
645k
        msg_bytes = msg_bytes.subspan(max_read);
1401
1402
        // Process data in the buffer.
1403
645k
        switch (m_recv_state) {
1404
154
        case RecvState::KEY_MAYBE_V1:
1405
154
            ProcessReceivedMaybeV1Bytes();
1406
154
            if (m_recv_state == RecvState::V1) return true;
1407
148
            break;
1408
1409
338
        case RecvState::KEY:
1410
338
            if (!ProcessReceivedKeyBytes()) return false;
1411
336
            break;
1412
1413
515k
        case RecvState::GARB_GARBTERM:
1414
515k
            if (!ProcessReceivedGarbageBytes()) return false;
1415
515k
            break;
1416
1417
515k
        case RecvState::VERSION:
1418
128k
        case RecvState::APP:
1419
128k
            if (!ProcessReceivedPacketBytes()) return false;
1420
128k
            break;
1421
1422
128k
        case RecvState::APP_READY:
1423
1.03k
            return true;
1424
1425
0
        case RecvState::V1:
1426
            // We should have bailed out before.
1427
0
            Assume(false);
1428
0
            break;
1429
645k
        }
1430
        // Make sure we have made progress before continuing.
1431
644k
        Assume(max_read > 0);
1432
644k
    }
1433
1434
10.8k
    return true;
1435
11.9k
}
1436
1437
std::optional<std::string> V2Transport::GetMessageType(std::span<const uint8_t>& contents) noexcept
1438
9.34k
{
1439
9.34k
    if (contents.size() == 0) return std::nullopt; // Empty contents
1440
9.34k
    uint8_t first_byte = contents[0];
1441
9.34k
    contents = contents.subspan(1); // Strip first byte.
1442
1443
9.34k
    if (first_byte != 0) {
1444
        // Short (1 byte) encoding.
1445
8.39k
        if (first_byte < std::size(V2_MESSAGE_IDS)) {
1446
            // Valid short message id.
1447
8.39k
            return V2_MESSAGE_IDS[first_byte];
1448
8.39k
        } else {
1449
            // Unknown short message id.
1450
1
            return std::nullopt;
1451
1
        }
1452
8.39k
    }
1453
1454
952
    if (contents.size() < CMessageHeader::MESSAGE_TYPE_SIZE) {
1455
10
        return std::nullopt; // Long encoding needs 12 message type bytes.
1456
10
    }
1457
1458
942
    size_t msg_type_len{0};
1459
8.39k
    while (msg_type_len < CMessageHeader::MESSAGE_TYPE_SIZE && contents[msg_type_len] != 0) {
1460
        // Verify that message type bytes before the first 0x00 are in range. BIP324 specifies the
1461
        // long message type encoding as "an ASCII message type (as in the v1 P2P protocol)".
1462
7.46k
        if (contents[msg_type_len] < ' ' || contents[msg_type_len] > 0x7E) {
1463
10
            return {};
1464
10
        }
1465
7.45k
        ++msg_type_len;
1466
7.45k
    }
1467
932
    std::string ret{reinterpret_cast<const char*>(contents.data()), msg_type_len};
1468
4.57k
    while (msg_type_len < CMessageHeader::MESSAGE_TYPE_SIZE) {
1469
        // Verify that message type bytes after the first 0x00 are also 0x00.
1470
3.68k
        if (contents[msg_type_len] != 0) return {};
1471
3.63k
        ++msg_type_len;
1472
3.63k
    }
1473
    // Strip message type bytes of contents.
1474
882
    contents = contents.subspan(CMessageHeader::MESSAGE_TYPE_SIZE);
1475
882
    return ret;
1476
932
}
1477
1478
CNetMessage V2Transport::GetReceivedMessage(NodeClock::time_point time, bool& reject_message) noexcept
1479
9.56k
{
1480
9.56k
    AssertLockNotHeld(m_recv_mutex);
1481
9.56k
    LOCK(m_recv_mutex);
1482
9.56k
    if (m_recv_state == RecvState::V1) return m_v1_fallback.GetReceivedMessage(time, reject_message);
1483
1484
9.34k
    Assume(m_recv_state == RecvState::APP_READY);
1485
9.34k
    std::span<const uint8_t> contents{m_recv_decode_buffer};
1486
9.34k
    auto msg_type = GetMessageType(contents);
1487
9.34k
    CNetMessage msg{DataStream{}};
1488
    // Note that BIP324Cipher::EXPANSION also includes the length descriptor size.
1489
9.34k
    msg.m_raw_message_size = m_recv_decode_buffer.size() + BIP324Cipher::EXPANSION;
1490
9.34k
    if (msg_type) {
1491
9.27k
        reject_message = false;
1492
9.27k
        msg.m_type = std::move(*msg_type);
1493
9.27k
        msg.m_time = time;
1494
9.27k
        msg.m_message_size = contents.size();
1495
9.27k
        msg.m_recv.resize(contents.size());
1496
9.27k
        std::copy(contents.begin(), contents.end(), UCharCast(msg.m_recv.data()));
1497
9.27k
    } else {
1498
71
        LogDebug(BCLog::NET, "V2 transport error: invalid message type (%u bytes contents), peer=%d\n", m_recv_decode_buffer.size(), m_nodeid);
1499
71
        reject_message = true;
1500
71
    }
1501
9.34k
    ClearShrink(m_recv_decode_buffer);
1502
9.34k
    SetReceiveState(RecvState::APP);
1503
1504
9.34k
    return msg;
1505
9.56k
}
1506
1507
bool V2Transport::SetMessageToSend(CSerializedNetMsg& msg) noexcept
1508
10.3k
{
1509
10.3k
    AssertLockNotHeld(m_send_mutex);
1510
10.3k
    LOCK(m_send_mutex);
1511
10.3k
    if (m_send_state == SendState::V1) return m_v1_fallback.SetMessageToSend(msg);
1512
    // We only allow adding a new message to be sent when in the READY state (so the packet cipher
1513
    // is available) and the send buffer is empty. This limits the number of messages in the send
1514
    // buffer to just one, and leaves the responsibility for queueing them up to the caller.
1515
10.0k
    if (!(m_send_state == SendState::READY && m_send_buffer.empty())) return false;
1516
    // Construct contents (encoding message type + payload).
1517
9.91k
    std::vector<uint8_t> contents;
1518
9.91k
    auto short_message_id = V2_MESSAGE_MAP(msg.m_type);
1519
9.91k
    if (short_message_id) {
1520
8.99k
        contents.resize(1 + msg.data.size());
1521
8.99k
        contents[0] = *short_message_id;
1522
8.99k
        std::copy(msg.data.begin(), msg.data.end(), contents.begin() + 1);
1523
8.99k
    } else {
1524
        // Initialize with zeroes, and then write the message type string starting at offset 1.
1525
        // This means contents[0] and the unused positions in contents[1..13] remain 0x00.
1526
926
        contents.resize(1 + CMessageHeader::MESSAGE_TYPE_SIZE + msg.data.size(), 0);
1527
926
        std::copy(msg.m_type.begin(), msg.m_type.end(), contents.data() + 1);
1528
926
        std::copy(msg.data.begin(), msg.data.end(), contents.begin() + 1 + CMessageHeader::MESSAGE_TYPE_SIZE);
1529
926
    }
1530
    // Construct ciphertext in send buffer.
1531
9.91k
    m_send_buffer.resize(contents.size() + BIP324Cipher::EXPANSION);
1532
9.91k
    m_cipher.Encrypt(MakeByteSpan(contents), {}, false, MakeWritableByteSpan(m_send_buffer));
1533
9.91k
    m_send_type = msg.m_type;
1534
    // Release memory
1535
9.91k
    ClearShrink(msg.data);
1536
9.91k
    return true;
1537
10.0k
}
1538
1539
Transport::BytesToSend V2Transport::GetBytesToSend(bool have_next_message) const noexcept
1540
67.2k
{
1541
67.2k
    AssertLockNotHeld(m_send_mutex);
1542
67.2k
    LOCK(m_send_mutex);
1543
67.2k
    if (m_send_state == SendState::V1) return m_v1_fallback.GetBytesToSend(have_next_message);
1544
1545
64.0k
    if (m_send_state == SendState::MAYBE_V1) Assume(m_send_buffer.empty());
1546
64.0k
    Assume(m_send_pos <= m_send_buffer.size());
1547
64.0k
    return {
1548
64.0k
        std::span{m_send_buffer}.subspan(m_send_pos),
1549
        // We only have more to send after the current m_send_buffer if there is a (next)
1550
        // message to be sent, and we're capable of sending packets. */
1551
64.0k
        have_next_message && m_send_state == SendState::READY,
1552
64.0k
        m_send_type
1553
64.0k
    };
1554
67.2k
}
1555
1556
void V2Transport::MarkBytesSent(size_t bytes_sent) noexcept
1557
11.8k
{
1558
11.8k
    AssertLockNotHeld(m_send_mutex);
1559
11.8k
    LOCK(m_send_mutex);
1560
11.8k
    if (m_send_state == SendState::V1) return m_v1_fallback.MarkBytesSent(bytes_sent);
1561
1562
11.0k
    if (m_send_state == SendState::AWAITING_KEY && m_send_pos == 0 && bytes_sent > 0) {
1563
137
        LogDebug(BCLog::NET, "start sending v2 handshake to peer=%d\n", m_nodeid);
1564
137
    }
1565
1566
11.0k
    m_send_pos += bytes_sent;
1567
11.0k
    Assume(m_send_pos <= m_send_buffer.size());
1568
11.0k
    if (m_send_pos >= CMessageHeader::HEADER_SIZE) {
1569
10.9k
        m_sent_v1_header_worth = true;
1570
10.9k
    }
1571
    // Wipe the buffer when everything is sent.
1572
11.0k
    if (m_send_pos == m_send_buffer.size()) {
1573
10.3k
        m_send_pos = 0;
1574
10.3k
        ClearShrink(m_send_buffer);
1575
10.3k
    }
1576
11.0k
}
1577
1578
bool V2Transport::ShouldReconnectV1() const noexcept
1579
152
{
1580
152
    AssertLockNotHeld(m_send_mutex);
1581
152
    AssertLockNotHeld(m_recv_mutex);
1582
    // Only outgoing connections need reconnection.
1583
152
    if (!m_initiating) return false;
1584
1585
75
    LOCK(m_recv_mutex);
1586
    // We only reconnect in the very first state and when the receive buffer is empty. Together
1587
    // these conditions imply nothing has been received so far.
1588
75
    if (m_recv_state != RecvState::KEY) return false;
1589
7
    if (!m_recv_buffer.empty()) return false;
1590
    // Check if we've sent enough for the other side to disconnect us (if it was V1).
1591
7
    LOCK(m_send_mutex);
1592
7
    return m_sent_v1_header_worth;
1593
7
}
1594
1595
size_t V2Transport::GetSendMemoryUsage() const noexcept
1596
20.7k
{
1597
20.7k
    AssertLockNotHeld(m_send_mutex);
1598
20.7k
    LOCK(m_send_mutex);
1599
20.7k
    if (m_send_state == SendState::V1) return m_v1_fallback.GetSendMemoryUsage();
1600
1601
19.9k
    return sizeof(m_send_buffer) + memusage::DynamicUsage(m_send_buffer);
1602
20.7k
}
1603
1604
Transport::Info V2Transport::GetInfo() const noexcept
1605
2.92k
{
1606
2.92k
    AssertLockNotHeld(m_recv_mutex);
1607
2.92k
    LOCK(m_recv_mutex);
1608
2.92k
    if (m_recv_state == RecvState::V1) return m_v1_fallback.GetInfo();
1609
1610
2.86k
    Transport::Info info;
1611
1612
    // Do not report v2 and session ID until the version packet has been received
1613
    // and verified (confirming that the other side very likely has the same keys as us).
1614
2.86k
    if (m_recv_state != RecvState::KEY_MAYBE_V1 && m_recv_state != RecvState::KEY &&
1615
2.86k
        m_recv_state != RecvState::GARB_GARBTERM && m_recv_state != RecvState::VERSION) {
1616
2.79k
        info.transport_type = TransportProtocolType::V2;
1617
2.79k
        info.session_id = uint256(MakeUCharSpan(m_cipher.GetSessionID()));
1618
2.79k
    } else {
1619
71
        info.transport_type = TransportProtocolType::DETECTING;
1620
71
    }
1621
1622
2.86k
    return info;
1623
2.92k
}
1624
1625
std::pair<size_t, bool> CConnman::SocketSendData(CNode& node) const
1626
151k
{
1627
151k
    auto it = node.vSendMsg.begin();
1628
151k
    size_t nSentSize = 0;
1629
151k
    bool data_left{false}; //!< second return value (whether unsent data remains)
1630
151k
    std::optional<bool> expected_more;
1631
1632
438k
    while (true) {
1633
438k
        if (it != node.vSendMsg.end()) {
1634
            // If possible, move one message from the send queue to the transport. This fails when
1635
            // there is an existing message still being sent, or (for v2 transports) when the
1636
            // handshake has not yet completed.
1637
151k
            size_t memusage = it->GetMemoryUsage();
1638
151k
            if (node.m_transport->SetMessageToSend(*it)) {
1639
                // Update memory usage of send buffer (as *it will be deleted).
1640
151k
                node.m_send_memusage -= memusage;
1641
151k
                ++it;
1642
151k
            }
1643
151k
        }
1644
438k
        const auto& [data, more, msg_type] = node.m_transport->GetBytesToSend(it != node.vSendMsg.end());
1645
        // We rely on the 'more' value returned by GetBytesToSend to correctly predict whether more
1646
        // bytes are still to be sent, to correctly set the MSG_MORE flag. As a sanity check,
1647
        // verify that the previously returned 'more' was correct.
1648
438k
        if (expected_more.has_value()) Assume(!data.empty() == *expected_more);
1649
438k
        expected_more = more;
1650
438k
        data_left = !data.empty(); // will be overwritten on next loop if all of data gets sent
1651
438k
        int nBytes = 0;
1652
438k
        if (!data.empty()) {
1653
287k
            LOCK(node.m_sock_mutex);
1654
            // There is no socket in case we've already disconnected, or in test cases without
1655
            // real connections. In these cases, we bail out immediately and just leave things
1656
            // in the send queue and transport.
1657
287k
            if (!node.m_sock) {
1658
30
                break;
1659
30
            }
1660
286k
            int flags = MSG_NOSIGNAL | MSG_DONTWAIT;
1661
286k
#ifdef MSG_MORE
1662
286k
            if (more) {
1663
135k
                flags |= MSG_MORE;
1664
135k
            }
1665
286k
#endif
1666
286k
            nBytes = node.m_sock->Send(data.data(), data.size(), flags);
1667
286k
        }
1668
438k
        if (nBytes > 0) {
1669
286k
            node.m_last_send = NodeClock::now();
1670
286k
            node.nSendBytes += nBytes;
1671
            // Notify transport that bytes have been processed.
1672
286k
            node.m_transport->MarkBytesSent(nBytes);
1673
            // Update statistics per message type.
1674
286k
            if (!msg_type.empty()) { // don't report v2 handshake bytes for now
1675
286k
                node.AccountForSentBytes(msg_type, nBytes);
1676
286k
            }
1677
286k
            nSentSize += nBytes;
1678
286k
            if ((size_t)nBytes != data.size()) {
1679
                // could not send full message; stop sending more
1680
10
                break;
1681
10
            }
1682
286k
        } else {
1683
151k
            if (nBytes < 0) {
1684
                // error
1685
4
                int nErr = WSAGetLastError();
1686
4
                if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) {
1687
4
                    LogDebug(BCLog::NET, "socket send error, %s: %s", node.DisconnectMsg(), NetworkErrorString(nErr));
1688
4
                    node.CloseSocketDisconnect();
1689
4
                }
1690
4
            }
1691
151k
            break;
1692
151k
        }
1693
438k
    }
1694
1695
151k
    const bool pause_send{node.m_send_memusage + node.m_transport->GetSendMemoryUsage() > nSendBufferMaxSize};
1696
151k
    if (pause_send && !node.fPauseSend) {
1697
0
        node.m_pause_send_since = NodeClock::now();
1698
0
    }
1699
151k
    node.fPauseSend = pause_send;
1700
1701
151k
    if (it == node.vSendMsg.end()) {
1702
151k
        assert(node.m_send_memusage == 0);
1703
151k
    }
1704
151k
    node.vSendMsg.erase(node.vSendMsg.begin(), it);
1705
151k
    return {nSentSize, data_left};
1706
151k
}
1707
1708
/** Try to find an inbound connection to evict.
1709
 *  Extreme care must be taken to avoid opening the node to attacker
1710
 *   triggered network partitioning.
1711
 *  The strategy used here is to protect a small number of peers
1712
 *   for each of several distinct characteristics which are difficult
1713
 *   to forge.  In order to partition a node the attacker must be
1714
 *   simultaneously better at all of them than honest peers.
1715
 */
1716
bool CConnman::AttemptToEvictConnection(bool evict_tx_relay_peer_only, std::optional<NodeId> protect_peer)
1717
7
{
1718
7
    AssertLockNotHeld(m_nodes_mutex);
1719
1720
7
    std::vector<NodeEvictionCandidate> vEvictionCandidates;
1721
7
    {
1722
1723
7
        LOCK(m_nodes_mutex);
1724
53
        for (const CNode* node : m_nodes) {
1725
53
            if (node->fDisconnect)
1726
0
                continue;
1727
53
            if (protect_peer.has_value() && node->GetId() == protect_peer) {
1728
4
                continue;
1729
4
            }
1730
49
            if (evict_tx_relay_peer_only && !node->m_relays_txs) {
1731
21
                continue;
1732
21
            }
1733
28
            NodeEvictionCandidate candidate{
1734
28
                .id = node->GetId(),
1735
28
                .m_connected = node->m_connected,
1736
28
                .m_min_ping_time = node->m_min_ping_time,
1737
28
                .m_last_block_time = node->m_last_block_time,
1738
28
                .m_last_tx_time = node->m_last_tx_time,
1739
28
                .fRelevantServices = node->m_has_all_wanted_services,
1740
28
                .m_relay_txs = node->m_relays_txs.load(),
1741
28
                .fBloomFilter = node->m_bloom_filter_loaded.load(),
1742
28
                .nKeyedNetGroup = node->nKeyedNetGroup,
1743
28
                .prefer_evict = node->m_prefer_evict,
1744
28
                .m_is_local = node->addr.IsLocal(),
1745
28
                .m_network = node->ConnectedThroughNetwork(),
1746
28
                .m_noban = node->HasPermission(NetPermissionFlags::NoBan),
1747
28
                .m_conn_type = node->m_conn_type,
1748
28
            };
1749
28
            vEvictionCandidates.push_back(candidate);
1750
28
        }
1751
7
    }
1752
7
    const std::optional<NodeId> node_id_to_evict = SelectNodeToEvict(std::move(vEvictionCandidates));
1753
7
    if (!node_id_to_evict) {
1754
6
        return false;
1755
6
    }
1756
1
    LOCK(m_nodes_mutex);
1757
1
    for (CNode* pnode : m_nodes) {
1758
1
        if (pnode->GetId() == *node_id_to_evict) {
1759
1
            LogDebug(BCLog::NET, "selected %s connection for eviction, %s", pnode->ConnectionTypeAsString(), pnode->DisconnectMsg());
1760
1
            TRACEPOINT(net, evicted_inbound_connection,
1761
1
                pnode->GetId(),
1762
1
                pnode->m_addr_name.c_str(),
1763
1
                pnode->ConnectionTypeAsString().c_str(),
1764
1
                pnode->ConnectedThroughNetwork(),
1765
1
                TicksSinceEpoch<std::chrono::seconds>(pnode->m_connected));
1766
1
            pnode->fDisconnect = true;
1767
1
            return true;
1768
1
        }
1769
1
    }
1770
0
    return false;
1771
1
}
1772
1773
1.12k
void CConnman::AcceptConnection(const ListenSocket& hListenSocket) {
1774
1.12k
    AssertLockNotHeld(m_nodes_mutex);
1775
1776
1.12k
    struct sockaddr_storage sockaddr;
1777
1.12k
    socklen_t len = sizeof(sockaddr);
1778
1.12k
    auto sock = hListenSocket.sock->Accept((struct sockaddr*)&sockaddr, &len);
1779
1780
1.12k
    if (!sock) {
1781
0
        const int nErr = WSAGetLastError();
1782
0
        if (nErr != WSAEWOULDBLOCK) {
1783
0
            LogInfo("socket error accept failed: %s\n", NetworkErrorString(nErr));
1784
0
        }
1785
0
        return;
1786
0
    }
1787
1788
1.12k
    CService addr;
1789
1.12k
    if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr, len)) {
1790
0
        LogWarning("Unknown socket family\n");
1791
1.12k
    } else {
1792
1.12k
        addr = MaybeFlipIPv6toCJDNS(addr);
1793
1.12k
    }
1794
1795
1.12k
    const CService addr_bind{MaybeFlipIPv6toCJDNS(GetBindAddress(*sock))};
1796
1797
1.12k
    NetPermissionFlags permission_flags = NetPermissionFlags::None;
1798
1.12k
    hListenSocket.AddSocketPermissionFlags(permission_flags);
1799
1800
1.12k
    CreateNodeFromAcceptedSocket(std::move(sock), permission_flags, addr_bind, addr);
1801
1.12k
}
1802
1803
void CConnman::CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock,
1804
                                            NetPermissionFlags permission_flags,
1805
                                            const CService& addr_bind,
1806
                                            const CService& addr)
1807
1.12k
{
1808
1.12k
    AssertLockNotHeld(m_nodes_mutex);
1809
1810
1.12k
    int nInbound = 0;
1811
1812
1.12k
    const bool inbound_onion = std::find(m_onion_binds.begin(), m_onion_binds.end(), addr_bind) != m_onion_binds.end();
1813
1814
    // Tor inbound connections do not reveal the peer's actual network address.
1815
    // Therefore do not apply address-based whitelist permissions to them.
1816
1.12k
    AddWhitelistPermissionFlags(permission_flags, inbound_onion ? std::optional<CNetAddr>{} : addr, vWhitelistedRangeIncoming);
1817
1818
1.12k
    {
1819
1.12k
        LOCK(m_nodes_mutex);
1820
4.19k
        for (const CNode* pnode : m_nodes) {
1821
4.19k
            if (pnode->IsInboundConn()) nInbound++;
1822
4.19k
        }
1823
1.12k
    }
1824
1825
1.12k
    if (!fNetworkActive) {
1826
0
        LogDebug(BCLog::NET, "connection from %s dropped: not accepting new connections\n", addr.ToStringAddrPort());
1827
0
        return;
1828
0
    }
1829
1830
1.12k
    if (!sock->IsSelectable()) {
1831
0
        LogInfo("connection from %s dropped: non-selectable socket\n", addr.ToStringAddrPort());
1832
0
        return;
1833
0
    }
1834
1835
    // According to the internet TCP_NODELAY is not carried into accepted sockets
1836
    // on all platforms.  Set it again here just to be sure.
1837
1.12k
    const int on{1};
1838
1.12k
    if (sock->SetSockOpt(IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) == SOCKET_ERROR) {
1839
0
        LogDebug(BCLog::NET, "connection from %s: unable to set TCP_NODELAY, continuing anyway\n",
1840
0
                 addr.ToStringAddrPort());
1841
0
    }
1842
1843
    // Don't accept connections from banned peers.
1844
1.12k
    bool banned = m_banman && m_banman->IsBanned(addr);
1845
1.12k
    if (!NetPermissions::HasFlag(permission_flags, NetPermissionFlags::NoBan) && banned)
1846
3
    {
1847
3
        LogDebug(BCLog::NET, "connection from %s dropped (banned)\n", addr.ToStringAddrPort());
1848
3
        return;
1849
3
    }
1850
1851
    // Only accept connections from discouraged peers if our inbound slots aren't (almost) full.
1852
1.12k
    bool discouraged = m_banman && m_banman->IsDiscouraged(addr);
1853
1.12k
    if (!NetPermissions::HasFlag(permission_flags, NetPermissionFlags::NoBan) && nInbound + 1 >= m_max_inbound && discouraged)
1854
0
    {
1855
0
        LogDebug(BCLog::NET, "connection from %s dropped (discouraged)\n", addr.ToStringAddrPort());
1856
0
        return;
1857
0
    }
1858
1859
1.12k
    if (nInbound >= m_max_inbound)
1860
1
    {
1861
1
        if (!AttemptToEvictConnection(/*evict_tx_relay_peer_only=*/false)) {
1862
            // No connection to evict, disconnect the new connection
1863
1
            LogDebug(BCLog::NET, "failed to find an eviction candidate - connection dropped (full)\n");
1864
1
            return;
1865
1
        }
1866
1
    }
1867
1868
1.12k
    NodeId id = GetNewNodeId();
1869
1.12k
    uint64_t nonce = GetDeterministicRandomizer(RANDOMIZER_ID_LOCALHOSTNONCE).Write(id).Finalize();
1870
1871
    // The V2Transport transparently falls back to V1 behavior when an incoming V1 connection is
1872
    // detected, so use it whenever we signal NODE_P2P_V2.
1873
1.12k
    ServiceFlags local_services = GetLocalServices();
1874
1.12k
    const bool use_v2transport(local_services & NODE_P2P_V2);
1875
1876
1.12k
    uint64_t network_id = GetDeterministicRandomizer(RANDOMIZER_ID_NETWORKKEY)
1877
1.12k
                        .Write(inbound_onion ? NET_ONION : addr.GetNetClass())
1878
1.12k
                        .Write(addr_bind.GetAddrBytes())
1879
1.12k
                        .Write(addr_bind.GetPort()) // inbound connections use bind port
1880
1.12k
                        .Finalize();
1881
1.12k
    CNode* pnode = new CNode(id,
1882
1.12k
                             std::move(sock),
1883
1.12k
                             CAddress{addr, NODE_NONE},
1884
1.12k
                             CalculateKeyedNetGroup(addr),
1885
1.12k
                             nonce,
1886
1.12k
                             addr_bind,
1887
1.12k
                             /*addrNameIn=*/"",
1888
1.12k
                             ConnectionType::INBOUND,
1889
1.12k
                             inbound_onion,
1890
1.12k
                             network_id,
1891
1.12k
                             CNodeOptions{
1892
1.12k
                                 .permission_flags = permission_flags,
1893
1.12k
                                 .prefer_evict = discouraged,
1894
1.12k
                                 .recv_flood_size = nReceiveFloodSize,
1895
1.12k
                                 .use_v2transport = use_v2transport,
1896
1.12k
                             });
1897
1.12k
    pnode->AddRef();
1898
1.12k
    m_msgproc->InitializeNode(*pnode, local_services);
1899
1.12k
    {
1900
1.12k
        LOCK(m_nodes_mutex);
1901
1.12k
        m_nodes.push_back(pnode);
1902
1.12k
    }
1903
1.12k
    LogDebug(BCLog::NET, "connection from %s accepted\n", addr.ToStringAddrPort());
1904
1.12k
    TRACEPOINT(net, inbound_connection,
1905
1.12k
        pnode->GetId(),
1906
1.12k
        pnode->m_addr_name.c_str(),
1907
1.12k
        pnode->ConnectionTypeAsString().c_str(),
1908
1.12k
        pnode->ConnectedThroughNetwork(),
1909
1.12k
        GetNodeCount(ConnectionDirection::In));
1910
1911
    // We received a new connection, harvest entropy from the time (and our peer count)
1912
1.12k
    RandAddEvent((uint32_t)id);
1913
1.12k
}
1914
1915
bool CConnman::AddConnection(const std::string& address, ConnectionType conn_type, bool use_v2transport = false)
1916
170
{
1917
170
    AssertLockNotHeld(m_nodes_mutex);
1918
170
    AssertLockNotHeld(m_unused_i2p_sessions_mutex);
1919
170
    std::optional<int> max_connections;
1920
170
    switch (conn_type) {
1921
0
    case ConnectionType::INBOUND:
1922
0
    case ConnectionType::PRIVATE_BROADCAST:
1923
0
        return false;
1924
    // no separate per-type limit for MANUAL because semAddnode limits them
1925
4
    case ConnectionType::MANUAL:
1926
4
        break;
1927
109
    case ConnectionType::OUTBOUND_FULL_RELAY:
1928
109
        max_connections = m_max_outbound_full_relay;
1929
109
        break;
1930
37
    case ConnectionType::BLOCK_RELAY:
1931
37
        max_connections = m_max_outbound_block_relay;
1932
37
        break;
1933
    // no limit for ADDR_FETCH because -seednode has no limit either
1934
15
    case ConnectionType::ADDR_FETCH:
1935
15
        break;
1936
    // no limit for FEELER connections since they're short-lived
1937
5
    case ConnectionType::FEELER:
1938
5
        break;
1939
170
    } // no default case, so the compiler can warn about missing cases
1940
1941
    // Count existing connections
1942
170
    int existing_connections = WITH_LOCK(m_nodes_mutex,
1943
170
                                         return std::count_if(m_nodes.begin(), m_nodes.end(), [conn_type](CNode* node) { return node->m_conn_type == conn_type; }););
1944
1945
    // Max connections of specified type already exist
1946
170
    if (max_connections != std::nullopt && existing_connections >= max_connections) return false;
1947
1948
    // Max total automatic outbound or manual connections already exist
1949
170
    CountingSemaphoreGrant<> grant(conn_type == ConnectionType::MANUAL ? *semAddnode : *semOutbound, true);
1950
170
    if (!grant) return false;
1951
1952
170
    OpenNetworkConnection(/*addrConnect=*/CAddress{},
1953
170
                          /*fCountFailure=*/false,
1954
170
                          /*grant_outbound=*/std::move(grant),
1955
170
                          /*pszDest=*/address.c_str(),
1956
170
                          /*conn_type=*/conn_type,
1957
170
                          /*use_v2transport=*/use_v2transport,
1958
170
                          /*proxy_override=*/std::nullopt);
1959
170
    return true;
1960
170
}
1961
1962
void CConnman::DisconnectNodes()
1963
285k
{
1964
285k
    AssertLockNotHeld(m_nodes_mutex);
1965
285k
    AssertLockNotHeld(m_reconnections_mutex);
1966
1967
    // Use a temporary variable to accumulate desired reconnections, so we don't need
1968
    // m_reconnections_mutex while holding m_nodes_mutex.
1969
285k
    decltype(m_reconnections) reconnections_to_add;
1970
1971
285k
    {
1972
285k
        LOCK(m_nodes_mutex);
1973
1974
285k
        const bool network_active{fNetworkActive};
1975
285k
        if (!network_active) {
1976
            // Disconnect any connected nodes
1977
141
            for (CNode* pnode : m_nodes) {
1978
14
                if (!pnode->fDisconnect) {
1979
14
                    LogDebug(BCLog::NET, "Network not active, %s", pnode->DisconnectMsg());
1980
14
                    pnode->fDisconnect = true;
1981
14
                }
1982
14
            }
1983
141
        }
1984
1985
        // Disconnect unused nodes
1986
285k
        std::vector<CNode*> nodes_copy = m_nodes;
1987
285k
        for (CNode* pnode : nodes_copy)
1988
447k
        {
1989
447k
            if (pnode->fDisconnect)
1990
1.01k
            {
1991
                // remove from m_nodes
1992
1.01k
                std::erase(m_nodes, pnode);
1993
1994
                // Add to reconnection list if appropriate. We don't reconnect right here, because
1995
                // the creation of a connection is a blocking operation (up to several seconds),
1996
                // and we don't want to hold up the socket handler thread for that long.
1997
1.01k
                if (network_active && pnode->m_transport->ShouldReconnectV1()) {
1998
7
                    reconnections_to_add.push_back({
1999
7
                        .proxy_override = pnode->m_proxy_override,
2000
7
                        .addr_connect = pnode->addr,
2001
7
                        .grant = std::move(pnode->grantOutbound),
2002
7
                        .destination = pnode->m_dest,
2003
7
                        .conn_type = pnode->m_conn_type,
2004
7
                        .use_v2transport = false});
2005
7
                    LogDebug(BCLog::NET, "retrying with v1 transport protocol for peer=%d\n", pnode->GetId());
2006
7
                }
2007
2008
                // release outbound grant (if any)
2009
1.01k
                pnode->grantOutbound.Release();
2010
2011
                // close socket and cleanup
2012
1.01k
                pnode->CloseSocketDisconnect();
2013
2014
                // update connection count by network
2015
1.01k
                if (pnode->IsManualOrFullOutboundConn()) --m_network_conn_counts[pnode->addr.GetNetwork()];
2016
2017
                // hold in disconnected pool until all refs are released
2018
1.01k
                pnode->Release();
2019
1.01k
                m_nodes_disconnected.push_back(pnode);
2020
1.01k
            }
2021
447k
        }
2022
285k
    }
2023
285k
    {
2024
        // Delete disconnected nodes
2025
285k
        std::list<CNode*> nodes_disconnected_copy = m_nodes_disconnected;
2026
285k
        for (CNode* pnode : nodes_disconnected_copy)
2027
1.07k
        {
2028
            // Destroy the object only after other threads have stopped using it.
2029
1.07k
            if (pnode->GetRefCount() <= 0) {
2030
1.01k
                std::erase(m_nodes_disconnected, pnode);
2031
1.01k
                DeleteNode(pnode);
2032
1.01k
            }
2033
1.07k
        }
2034
285k
    }
2035
285k
    {
2036
        // Move entries from reconnections_to_add to m_reconnections.
2037
285k
        LOCK(m_reconnections_mutex);
2038
285k
        m_reconnections.splice(m_reconnections.end(), std::move(reconnections_to_add));
2039
285k
    }
2040
285k
}
2041
2042
void CConnman::NotifyNumConnectionsChanged()
2043
285k
{
2044
285k
    AssertLockNotHeld(m_nodes_mutex);
2045
2046
285k
    size_t nodes_size;
2047
285k
    {
2048
285k
        LOCK(m_nodes_mutex);
2049
285k
        nodes_size = m_nodes.size();
2050
285k
    }
2051
285k
    if(nodes_size != nPrevNodeCount) {
2052
2.53k
        nPrevNodeCount = nodes_size;
2053
2.53k
        if (m_client_interface) {
2054
2.53k
            m_client_interface->NotifyNumConnectionsChanged(nodes_size);
2055
2.53k
        }
2056
2.53k
    }
2057
285k
}
2058
2059
bool CConnman::ShouldRunInactivityChecks(const CNode& node, NodeClock::time_point now) const
2060
622k
{
2061
622k
    return node.m_connected + m_peer_connect_timeout < now;
2062
622k
}
2063
2064
bool CConnman::InactivityCheck(const CNode& node, NodeClock::time_point now) const
2065
444k
{
2066
    // Tests that see disconnects after using mocktime can start nodes with a
2067
    // large timeout. For example, -peertimeout=999999999.
2068
444k
    const auto last_send{node.m_last_send.load()};
2069
444k
    const auto last_recv{node.m_last_recv.load()};
2070
2071
444k
    if (!ShouldRunInactivityChecks(node, now)) return false;
2072
2073
106
    bool has_received{last_recv > NodeClock::epoch};
2074
106
    bool has_sent{last_send > NodeClock::epoch};
2075
2076
106
    if (!has_received || !has_sent) {
2077
3
        std::string has_never;
2078
3
        if (!has_received) has_never += ", never received from peer";
2079
3
        if (!has_sent) has_never += ", never sent to peer";
2080
3
        LogDebug(BCLog::NET,
2081
3
            "socket no message in first %i seconds%s, %s",
2082
3
            count_seconds(m_peer_connect_timeout),
2083
3
            has_never,
2084
3
            node.DisconnectMsg()
2085
3
        );
2086
3
        return true;
2087
3
    }
2088
2089
103
    if (now > last_send + TIMEOUT_INTERVAL) {
2090
0
        LogDebug(BCLog::NET,
2091
0
            "socket sending timeout: %is, %s", Ticks<std::chrono::seconds>(now - last_send),
2092
0
            node.DisconnectMsg()
2093
0
        );
2094
0
        return true;
2095
0
    }
2096
2097
103
    if (now > last_recv + TIMEOUT_INTERVAL) {
2098
0
        LogDebug(BCLog::NET,
2099
0
            "socket receive timeout: %is, %s", Ticks<std::chrono::seconds>(now - last_recv),
2100
0
            node.DisconnectMsg()
2101
0
        );
2102
0
        return true;
2103
0
    }
2104
2105
103
    if (node.fPauseSend) {
2106
0
        const auto last_pause{node.m_pause_send_since.load()};
2107
0
        if (now > last_pause + TIMEOUT_INTERVAL) {
2108
0
            LogDebug(BCLog::NET,
2109
0
                "send buffer full for %is, %s", Ticks<std::chrono::seconds>(now - last_pause),
2110
0
                node.DisconnectMsg()
2111
0
            );
2112
0
            return true;
2113
0
        }
2114
0
    }
2115
2116
103
    if (!node.fSuccessfullyConnected) {
2117
9
        if (node.m_transport->GetInfo().transport_type == TransportProtocolType::DETECTING) {
2118
2
            LogDebug(BCLog::NET, "V2 handshake timeout, %s", node.DisconnectMsg());
2119
7
        } else {
2120
7
            LogDebug(BCLog::NET, "version handshake timeout, %s", node.DisconnectMsg());
2121
7
        }
2122
9
        return true;
2123
9
    }
2124
2125
94
    return false;
2126
103
}
2127
2128
Sock::EventsPerSock CConnman::GenerateWaitSockets(std::span<CNode* const> nodes)
2129
285k
{
2130
285k
    Sock::EventsPerSock events_per_sock;
2131
2132
286k
    for (const ListenSocket& hListenSocket : vhListenSocket) {
2133
286k
        events_per_sock.emplace(hListenSocket.sock, Sock::Events{Sock::RecvEvent});
2134
286k
    }
2135
2136
446k
    for (CNode* pnode : nodes) {
2137
446k
        bool select_recv = !pnode->fPauseRecv;
2138
446k
        bool select_send;
2139
446k
        {
2140
446k
            LOCK(pnode->cs_vSend);
2141
            // Sending is possible if either there are bytes to send right now, or if there will be
2142
            // once a potential message from vSendMsg is handed to the transport. GetBytesToSend
2143
            // determines both of these in a single call.
2144
446k
            const auto& [to_send, more, _msg_type] = pnode->m_transport->GetBytesToSend(!pnode->vSendMsg.empty());
2145
446k
            select_send = !to_send.empty() || more;
2146
446k
        }
2147
446k
        if (!select_recv && !select_send) continue;
2148
2149
445k
        LOCK(pnode->m_sock_mutex);
2150
445k
        if (pnode->m_sock) {
2151
444k
            Sock::Event event = (select_send ? Sock::SendEvent : 0) | (select_recv ? Sock::RecvEvent : 0);
2152
444k
            events_per_sock.emplace(pnode->m_sock, Sock::Events{event});
2153
444k
        }
2154
445k
    }
2155
2156
285k
    return events_per_sock;
2157
285k
}
2158
2159
void CConnman::SocketHandler()
2160
285k
{
2161
285k
    AssertLockNotHeld(m_nodes_mutex);
2162
285k
    AssertLockNotHeld(m_total_bytes_sent_mutex);
2163
2164
285k
    Sock::EventsPerSock events_per_sock;
2165
2166
285k
    {
2167
285k
        const NodesSnapshot snap{*this, /*shuffle=*/false};
2168
2169
285k
        const auto timeout = std::chrono::milliseconds(SELECT_TIMEOUT_MILLISECONDS);
2170
2171
        // Check for the readiness of the already connected sockets and the
2172
        // listening sockets in one call ("readiness" as in poll(2) or
2173
        // select(2)). If none are ready, wait for a short while and return
2174
        // empty sets.
2175
285k
        events_per_sock = GenerateWaitSockets(snap.Nodes());
2176
285k
        if (events_per_sock.empty() || !events_per_sock.begin()->first->WaitMany(timeout, events_per_sock)) {
2177
219
            m_interrupt_net->sleep_for(timeout);
2178
219
        }
2179
2180
        // Service (send/receive) each of the already connected nodes.
2181
285k
        SocketHandlerConnected(snap.Nodes(), events_per_sock);
2182
285k
    }
2183
2184
    // Accept new connections from listening sockets.
2185
285k
    SocketHandlerListening(events_per_sock);
2186
285k
}
2187
2188
void CConnman::SocketHandlerConnected(const std::vector<CNode*>& nodes,
2189
                                      const Sock::EventsPerSock& events_per_sock)
2190
285k
{
2191
285k
    AssertLockNotHeld(m_total_bytes_sent_mutex);
2192
2193
285k
    const auto now{NodeClock::now()};
2194
2195
445k
    for (CNode* pnode : nodes) {
2196
445k
        if (m_interrupt_net->interrupted()) {
2197
418
            return;
2198
418
        }
2199
2200
        //
2201
        // Receive
2202
        //
2203
445k
        bool recvSet = false;
2204
445k
        bool sendSet = false;
2205
445k
        bool errorSet = false;
2206
445k
        {
2207
445k
            LOCK(pnode->m_sock_mutex);
2208
445k
            if (!pnode->m_sock) {
2209
1.19k
                continue;
2210
1.19k
            }
2211
444k
            const auto it = events_per_sock.find(pnode->m_sock);
2212
444k
            if (it != events_per_sock.end()) {
2213
443k
                recvSet = it->second.occurred & Sock::RecvEvent;
2214
443k
                sendSet = it->second.occurred & Sock::SendEvent;
2215
443k
                errorSet = it->second.occurred & Sock::ErrorEvent;
2216
443k
            }
2217
444k
        }
2218
2219
444k
        if (sendSet) {
2220
            // Send data
2221
304
            auto [bytes_sent, data_left] = WITH_LOCK(pnode->cs_vSend, return SocketSendData(*pnode));
2222
304
            if (bytes_sent) {
2223
301
                RecordBytesSent(bytes_sent);
2224
2225
                // If both receiving and (non-optimistic) sending were possible, we first attempt
2226
                // sending. If that succeeds, but does not fully drain the send queue, do not
2227
                // attempt to receive. This avoids needlessly queueing data if the remote peer
2228
                // is slow at receiving data, by means of TCP flow control. We only do this when
2229
                // sending actually succeeded to make sure progress is always made; otherwise a
2230
                // deadlock would be possible when both sides have data to send, but neither is
2231
                // receiving.
2232
301
                if (data_left) recvSet = false;
2233
301
            }
2234
304
        }
2235
2236
444k
        if (recvSet || errorSet)
2237
153k
        {
2238
            // typical socket buffer is 8K-64K
2239
153k
            uint8_t pchBuf[0x10000];
2240
153k
            int nBytes = 0;
2241
153k
            {
2242
153k
                LOCK(pnode->m_sock_mutex);
2243
153k
                if (!pnode->m_sock) {
2244
3
                    continue;
2245
3
                }
2246
153k
                nBytes = pnode->m_sock->Recv(pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
2247
153k
            }
2248
153k
            if (nBytes > 0)
2249
153k
            {
2250
153k
                bool notify = false;
2251
153k
                if (!pnode->ReceiveMsgBytes({pchBuf, (size_t)nBytes}, notify)) {
2252
10
                    LogDebug(BCLog::NET,
2253
10
                        "receiving message bytes failed, %s",
2254
10
                        pnode->DisconnectMsg()
2255
10
                    );
2256
10
                    pnode->CloseSocketDisconnect();
2257
10
                }
2258
153k
                RecordBytesRecv(nBytes);
2259
153k
                if (notify) {
2260
130k
                    pnode->MarkReceivedMsgsForProcessing();
2261
130k
                    WakeMessageHandler();
2262
130k
                }
2263
153k
            }
2264
648
            else if (nBytes == 0)
2265
642
            {
2266
                // socket closed gracefully
2267
642
                if (!pnode->fDisconnect) {
2268
642
                    LogDebug(BCLog::NET, "socket closed, %s", pnode->DisconnectMsg());
2269
642
                }
2270
642
                pnode->CloseSocketDisconnect();
2271
642
            }
2272
6
            else if (nBytes < 0)
2273
6
            {
2274
                // error
2275
6
                int nErr = WSAGetLastError();
2276
6
                if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
2277
6
                {
2278
6
                    if (!pnode->fDisconnect) {
2279
6
                        LogDebug(BCLog::NET, "socket recv error, %s: %s", pnode->DisconnectMsg(), NetworkErrorString(nErr));
2280
6
                    }
2281
6
                    pnode->CloseSocketDisconnect();
2282
6
                }
2283
6
            }
2284
153k
        }
2285
2286
444k
        if (InactivityCheck(*pnode, now)) pnode->fDisconnect = true;
2287
444k
    }
2288
285k
}
2289
2290
void CConnman::SocketHandlerListening(const Sock::EventsPerSock& events_per_sock)
2291
285k
{
2292
285k
    AssertLockNotHeld(m_nodes_mutex);
2293
2294
286k
    for (const ListenSocket& listen_socket : vhListenSocket) {
2295
286k
        if (m_interrupt_net->interrupted()) {
2296
1.07k
            return;
2297
1.07k
        }
2298
285k
        const auto it = events_per_sock.find(listen_socket.sock);
2299
285k
        if (it != events_per_sock.end() && it->second.occurred & Sock::RecvEvent) {
2300
1.12k
            AcceptConnection(listen_socket);
2301
1.12k
        }
2302
285k
    }
2303
285k
}
2304
2305
void CConnman::ThreadSocketHandler()
2306
1.10k
{
2307
1.10k
    AssertLockNotHeld(m_total_bytes_sent_mutex);
2308
2309
286k
    while (!m_interrupt_net->interrupted()) {
2310
285k
        DisconnectNodes();
2311
285k
        NotifyNumConnectionsChanged();
2312
285k
        SocketHandler();
2313
285k
    }
2314
1.10k
}
2315
2316
void CConnman::WakeMessageHandler()
2317
202k
{
2318
202k
    {
2319
202k
        LOCK(mutexMsgProc);
2320
202k
        fMsgProcWake = true;
2321
202k
    }
2322
202k
    condMsgProc.notify_one();
2323
202k
}
2324
2325
void CConnman::ThreadDNSAddressSeed()
2326
13
{
2327
13
    int outbound_connection_count = 0;
2328
2329
13
    if (!gArgs.GetArgs("-seednode").empty()) {
2330
0
        auto start = NodeClock::now();
2331
0
        constexpr std::chrono::seconds SEEDNODE_TIMEOUT = 30s;
2332
0
        LogInfo("-seednode enabled. Trying the provided seeds for %d seconds before defaulting to the dnsseeds.\n", SEEDNODE_TIMEOUT.count());
2333
0
        while (!m_interrupt_net->interrupted()) {
2334
0
            if (!m_interrupt_net->sleep_for(500ms)) {
2335
0
                return;
2336
0
            }
2337
2338
            // Abort if we have spent enough time without reaching our target.
2339
            // Giving seed nodes 30 seconds so this does not become a race against fixedseeds (which triggers after 1 min)
2340
0
            if (NodeClock::now() > start + SEEDNODE_TIMEOUT) {
2341
0
                LogInfo("Couldn't connect to enough peers via seed nodes. Handing fetch logic to the DNS seeds.\n");
2342
0
                break;
2343
0
            }
2344
2345
0
            outbound_connection_count = GetFullOutboundConnCount();
2346
0
            if (outbound_connection_count >= SEED_OUTBOUND_CONNECTION_THRESHOLD) {
2347
0
                LogInfo("P2P peers available. Finished fetching data from seed nodes.\n");
2348
0
                break;
2349
0
            }
2350
0
        }
2351
0
    }
2352
2353
13
    FastRandomContext rng;
2354
13
    std::vector<std::string> seeds = m_params.DNSSeeds();
2355
13
    std::shuffle(seeds.begin(), seeds.end(), rng);
2356
13
    int seeds_right_now = 0; // Number of seeds left before testing if we have enough connections
2357
2358
13
    if (gArgs.GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED)) {
2359
        // When -forcednsseed is provided, query all.
2360
1
        seeds_right_now = seeds.size();
2361
12
    } else if (addrman.get().Size() == 0) {
2362
        // If we have no known peers, query all.
2363
        // This will occur on the first run, or if peers.dat has been
2364
        // deleted.
2365
7
        seeds_right_now = seeds.size();
2366
7
    }
2367
2368
    // Proceed with dnsseeds if seednodes hasn't reached the target or if forcednsseed is set
2369
13
    if (outbound_connection_count < SEED_OUTBOUND_CONNECTION_THRESHOLD || seeds_right_now) {
2370
        // goal: only query DNS seed if address need is acute
2371
        // * If we have a reasonable number of peers in addrman, spend
2372
        //   some time trying them first. This improves user privacy by
2373
        //   creating fewer identifying DNS requests, reduces trust by
2374
        //   giving seeds less influence on the network topology, and
2375
        //   reduces traffic to the seeds.
2376
        // * When querying DNS seeds query a few at once, this ensures
2377
        //   that we don't give DNS seeds the ability to eclipse nodes
2378
        //   that query them.
2379
        // * If we continue having problems, eventually query all the
2380
        //   DNS seeds, and if that fails too, also try the fixed seeds.
2381
        //   (done in ThreadOpenConnections)
2382
13
        int found = 0;
2383
13
        const std::chrono::seconds seeds_wait_time = (addrman.get().Size() >= DNSSEEDS_DELAY_PEER_THRESHOLD ? DNSSEEDS_DELAY_MANY_PEERS : DNSSEEDS_DELAY_FEW_PEERS);
2384
2385
13
        for (const std::string& seed : seeds) {
2386
13
            if (seeds_right_now == 0) {
2387
5
                seeds_right_now += DNSSEEDS_TO_QUERY_AT_ONCE;
2388
2389
5
                if (addrman.get().Size() > 0) {
2390
5
                    LogInfo("Waiting %d seconds before querying DNS seeds.\n", seeds_wait_time.count());
2391
5
                    std::chrono::seconds to_wait = seeds_wait_time;
2392
6
                    while (to_wait.count() > 0) {
2393
                        // if sleeping for the MANY_PEERS interval, wake up
2394
                        // early to see if we have enough peers and can stop
2395
                        // this thread entirely freeing up its resources
2396
5
                        std::chrono::seconds w = std::min(DNSSEEDS_DELAY_FEW_PEERS, to_wait);
2397
5
                        if (!m_interrupt_net->sleep_for(w)) return;
2398
2
                        to_wait -= w;
2399
2400
2
                        if (GetFullOutboundConnCount() >= SEED_OUTBOUND_CONNECTION_THRESHOLD) {
2401
1
                            if (found > 0) {
2402
0
                                LogInfo("%d addresses found from DNS seeds\n", found);
2403
0
                                LogInfo("P2P peers available. Finished DNS seeding.\n");
2404
1
                            } else {
2405
1
                                LogInfo("P2P peers available. Skipped DNS seeding.\n");
2406
1
                            }
2407
1
                            return;
2408
1
                        }
2409
2
                    }
2410
5
                }
2411
5
            }
2412
2413
9
            if (m_interrupt_net->interrupted()) return;
2414
2415
            // hold off on querying seeds if P2P network deactivated
2416
9
            if (!fNetworkActive) {
2417
0
                LogInfo("Waiting for network to be reactivated before querying DNS seeds.\n");
2418
0
                do {
2419
0
                    if (!m_interrupt_net->sleep_for(1s)) return;
2420
0
                } while (!fNetworkActive);
2421
0
            }
2422
2423
9
            LogInfo("Loading addresses from DNS seed %s\n", seed);
2424
            // If -proxy is in use, we make an ADDR_FETCH connection to the DNS resolved peer address
2425
            // for the base dns seed domain in chainparams
2426
9
            if (HaveNameProxy()) {
2427
9
                AddAddrFetch(seed);
2428
9
            } else {
2429
0
                std::vector<CAddress> vAdd;
2430
0
                constexpr ServiceFlags requiredServiceBits{SeedsServiceFlags()};
2431
0
                std::string host = strprintf("x%x.%s", requiredServiceBits, seed);
2432
0
                CNetAddr resolveSource;
2433
0
                if (!resolveSource.SetInternal(host)) {
2434
0
                    continue;
2435
0
                }
2436
                // Limit number of IPs learned from a single DNS seed. This limit exists to prevent the results from
2437
                // one DNS seed from dominating AddrMan. Note that the number of results from a UDP DNS query is
2438
                // bounded to 33 already, but it is possible for it to use TCP where a larger number of results can be
2439
                // returned.
2440
0
                unsigned int nMaxIPs = 32;
2441
0
                const auto addresses{LookupHost(host, nMaxIPs, true)};
2442
0
                if (!addresses.empty()) {
2443
0
                    for (const CNetAddr& ip : addresses) {
2444
0
                        CAddress addr = CAddress(CService(ip, m_params.GetDefaultPort()), SeedsAssumedServiceFlags());
2445
0
                        addr.nTime = rng.rand_uniform_delay(Now<NodeSeconds>() - 3 * 24h, -4 * 24h); // use a random age between 3 and 7 days old
2446
0
                        vAdd.push_back(addr);
2447
0
                        found++;
2448
0
                    }
2449
0
                    addrman.get().Add(vAdd, resolveSource);
2450
0
                } else {
2451
                    // If the seed does not support a subdomain with our desired service bits,
2452
                    // we make an ADDR_FETCH connection to the DNS resolved peer address for the
2453
                    // base dns seed domain in chainparams
2454
0
                    AddAddrFetch(seed);
2455
0
                }
2456
0
            }
2457
9
            --seeds_right_now;
2458
9
        }
2459
9
        LogInfo("%d addresses found from DNS seeds\n", found);
2460
9
    } else {
2461
0
        LogInfo("Skipping DNS seeds. Enough peers have been found\n");
2462
0
    }
2463
13
}
2464
2465
void CConnman::DumpAddresses()
2466
1.11k
{
2467
1.11k
    const auto start{SteadyClock::now()};
2468
2469
1.11k
    DumpPeerAddresses(::gArgs, addrman);
2470
2471
1.11k
    LogDebug(BCLog::NET, "Flushed %d addresses to peers.dat %dms",
2472
1.11k
             addrman.get().Size(), Ticks<std::chrono::milliseconds>(SteadyClock::now() - start));
2473
1.11k
}
2474
2475
void CConnman::ProcessAddrFetch()
2476
221
{
2477
221
    AssertLockNotHeld(m_nodes_mutex);
2478
221
    AssertLockNotHeld(m_unused_i2p_sessions_mutex);
2479
221
    std::string strDest;
2480
221
    {
2481
221
        LOCK(m_addr_fetches_mutex);
2482
221
        if (m_addr_fetches.empty())
2483
214
            return;
2484
7
        strDest = m_addr_fetches.front();
2485
7
        m_addr_fetches.pop_front();
2486
7
    }
2487
    // Attempt v2 connection if we support v2 - we'll reconnect with v1 if our
2488
    // peer doesn't support it or immediately disconnects us for another reason.
2489
0
    const bool use_v2transport(GetLocalServices() & NODE_P2P_V2);
2490
7
    CAddress addr;
2491
7
    CountingSemaphoreGrant<> grant(*semOutbound, /*fTry=*/true);
2492
7
    if (grant) {
2493
7
        OpenNetworkConnection(/*addrConnect=*/addr,
2494
7
                              /*fCountFailure=*/false,
2495
7
                              /*grant_outbound=*/std::move(grant),
2496
7
                              /*pszDest=*/strDest.c_str(),
2497
7
                              /*conn_type=*/ConnectionType::ADDR_FETCH,
2498
7
                              /*use_v2transport=*/use_v2transport,
2499
7
                              /*proxy_override=*/std::nullopt);
2500
7
    }
2501
7
}
2502
2503
bool CConnman::GetTryNewOutboundPeer() const
2504
136
{
2505
136
    return m_try_another_outbound_peer;
2506
136
}
2507
2508
void CConnman::SetTryNewOutboundPeer(bool flag)
2509
1.40k
{
2510
1.40k
    m_try_another_outbound_peer = flag;
2511
1.40k
    LogDebug(BCLog::NET, "setting try another outbound peer=%s\n", flag ? "true" : "false");
2512
1.40k
}
2513
2514
void CConnman::StartExtraBlockRelayPeers()
2515
37
{
2516
37
    LogDebug(BCLog::NET, "enabling extra block-relay-only peers\n");
2517
37
    m_start_extra_block_relay_peers = true;
2518
37
}
2519
2520
// Return the number of outbound connections that are full relay (not blocks only)
2521
int CConnman::GetFullOutboundConnCount() const
2522
2
{
2523
2
    AssertLockNotHeld(m_nodes_mutex);
2524
2525
2
    int nRelevant = 0;
2526
2
    {
2527
2
        LOCK(m_nodes_mutex);
2528
4
        for (const CNode* pnode : m_nodes) {
2529
4
            if (pnode->fSuccessfullyConnected && pnode->IsFullOutboundConn()) ++nRelevant;
2530
4
        }
2531
2
    }
2532
2
    return nRelevant;
2533
2
}
2534
2535
// Return the number of peers we have over our outbound connection limit
2536
// Exclude peers that are marked for disconnect, or are going to be
2537
// disconnected soon (eg ADDR_FETCH and FEELER)
2538
// Also exclude peers that haven't finished initial connection handshake yet
2539
// (so that we don't decide we're over our desired connection limit, and then
2540
// evict some peer that has finished the handshake)
2541
int CConnman::GetExtraFullOutboundCount() const
2542
141
{
2543
141
    AssertLockNotHeld(m_nodes_mutex);
2544
2545
141
    int full_outbound_peers = 0;
2546
141
    {
2547
141
        LOCK(m_nodes_mutex);
2548
248
        for (const CNode* pnode : m_nodes) {
2549
248
            if (pnode->fSuccessfullyConnected && !pnode->fDisconnect && pnode->IsFullOutboundConn()) {
2550
62
                ++full_outbound_peers;
2551
62
            }
2552
248
        }
2553
141
    }
2554
141
    return std::max(full_outbound_peers - m_max_outbound_full_relay, 0);
2555
141
}
2556
2557
int CConnman::GetExtraBlockRelayCount() const
2558
141
{
2559
141
    AssertLockNotHeld(m_nodes_mutex);
2560
2561
141
    int block_relay_peers = 0;
2562
141
    {
2563
141
        LOCK(m_nodes_mutex);
2564
248
        for (const CNode* pnode : m_nodes) {
2565
248
            if (pnode->fSuccessfullyConnected && !pnode->fDisconnect && pnode->IsBlockOnlyConn()) {
2566
13
                ++block_relay_peers;
2567
13
            }
2568
248
        }
2569
141
    }
2570
141
    return std::max(block_relay_peers - m_max_outbound_block_relay, 0);
2571
141
}
2572
2573
bool CConnman::EvictTxPeerIfFull(std::optional<NodeId> protect_peer)
2574
1.09k
{
2575
1.09k
    int tx_inbound_peers{0};
2576
1.09k
    {
2577
1.09k
        LOCK(m_nodes_mutex);
2578
5.05k
        for (const CNode* pnode : m_nodes) {
2579
5.05k
            if (!pnode->fDisconnect && pnode->IsInboundConn() && pnode->m_relays_txs) {
2580
4.81k
                ++tx_inbound_peers;
2581
4.81k
            }
2582
5.05k
        }
2583
1.09k
    }
2584
1.09k
    if (tx_inbound_peers > m_max_inbound_full_relay) {
2585
6
        return AttemptToEvictConnection(/*evict_tx_relay_peer_only=*/true, protect_peer);
2586
6
    }
2587
1.08k
    return true;
2588
1.09k
}
2589
2590
std::unordered_set<Network> CConnman::GetReachableEmptyNetworks() const
2591
186
{
2592
186
    std::unordered_set<Network> networks{};
2593
1.48k
    for (int n = 0; n < NET_MAX; n++) {
2594
1.30k
        enum Network net = (enum Network)n;
2595
1.30k
        if (net == NET_UNROUTABLE || net == NET_INTERNAL) continue;
2596
930
        if (g_reachable_nets.Contains(net) && addrman.get().Size(net, std::nullopt) == 0) {
2597
417
            networks.insert(net);
2598
417
        }
2599
930
    }
2600
186
    return networks;
2601
186
}
2602
2603
bool CConnman::MultipleManualOrFullOutboundConns(Network net) const
2604
38
{
2605
38
    AssertLockHeld(m_nodes_mutex);
2606
38
    return m_network_conn_counts[net] > 1;
2607
38
}
2608
2609
bool CConnman::MaybePickPreferredNetwork(std::optional<Network>& network)
2610
1
{
2611
1
    AssertLockNotHeld(m_nodes_mutex);
2612
2613
1
    std::array<Network, 5> nets{NET_IPV4, NET_IPV6, NET_ONION, NET_I2P, NET_CJDNS};
2614
1
    std::shuffle(nets.begin(), nets.end(), FastRandomContext());
2615
2616
1
    LOCK(m_nodes_mutex);
2617
1
    for (const auto net : nets) {
2618
1
        if (g_reachable_nets.Contains(net) && m_network_conn_counts[net] == 0 && addrman.get().Size(net) != 0) {
2619
1
            network = net;
2620
1
            return true;
2621
1
        }
2622
1
    }
2623
2624
0
    return false;
2625
1
}
2626
2627
void CConnman::ThreadOpenConnections(const std::vector<std::string> connect, std::span<const std::string> seed_nodes)
2628
46
{
2629
46
    AssertLockNotHeld(m_nodes_mutex);
2630
46
    AssertLockNotHeld(m_reconnections_mutex);
2631
46
    AssertLockNotHeld(m_unused_i2p_sessions_mutex);
2632
46
    AssertLockNotHeld(m_anchors_mutex);
2633
46
    FastRandomContext rng;
2634
    // Connect to specific addresses
2635
46
    if (!connect.empty())
2636
5
    {
2637
        // Attempt v2 connection if we support v2 - we'll reconnect with v1 if our
2638
        // peer doesn't support it or immediately disconnects us for another reason.
2639
5
        const bool use_v2transport(GetLocalServices() & NODE_P2P_V2);
2640
5
        for (int64_t nLoop = 0;; nLoop++)
2641
5
        {
2642
5
            for (const std::string& strAddr : connect)
2643
7
            {
2644
7
                OpenNetworkConnection(/*addrConnect=*/CAddress{CService{}, NODE_NONE},
2645
7
                                      /*fCountFailure=*/false,
2646
7
                                      /*grant_outbound=*/{},
2647
7
                                      /*pszDest=*/strAddr.c_str(),
2648
7
                                      /*conn_type=*/ConnectionType::MANUAL,
2649
7
                                      /*use_v2transport=*/use_v2transport,
2650
7
                                      /*proxy_override=*/std::nullopt);
2651
7
                for (int i = 0; i < 10 && i < nLoop; i++)
2652
0
                {
2653
0
                    if (!m_interrupt_net->sleep_for(500ms)) {
2654
0
                        return;
2655
0
                    }
2656
0
                }
2657
7
            }
2658
5
            if (!m_interrupt_net->sleep_for(500ms)) {
2659
5
                return;
2660
5
            }
2661
0
            PerformReconnections();
2662
0
        }
2663
5
    }
2664
2665
    // Initiate network connections
2666
41
    auto start = GetTime<std::chrono::microseconds>();
2667
2668
    // Minimum time before next feeler connection (in microseconds).
2669
41
    auto next_feeler = start + rng.rand_exp_duration(FEELER_INTERVAL);
2670
41
    auto next_extra_block_relay = start + rng.rand_exp_duration(EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL);
2671
41
    auto next_extra_network_peer{start + rng.rand_exp_duration(EXTRA_NETWORK_PEER_INTERVAL)};
2672
41
    const bool dnsseed = gArgs.GetBoolArg("-dnsseed", DEFAULT_DNSSEED);
2673
41
    bool add_fixed_seeds = gArgs.GetBoolArg("-fixedseeds", DEFAULT_FIXEDSEEDS);
2674
41
    const bool use_seednodes{!gArgs.GetArgs("-seednode").empty()};
2675
2676
41
    auto seed_node_timer = NodeClock::now();
2677
41
    bool add_addr_fetch{addrman.get().Size() == 0 && !seed_nodes.empty()};
2678
41
    constexpr std::chrono::seconds ADD_NEXT_SEEDNODE = 10s;
2679
2680
41
    if (!add_fixed_seeds) {
2681
36
        LogInfo("Fixed seeds are disabled\n");
2682
36
    }
2683
2684
227
    while (!m_interrupt_net->interrupted()) {
2685
221
        if (add_addr_fetch) {
2686
6
            add_addr_fetch = false;
2687
6
            const auto& seed{SpanPopBack(seed_nodes)};
2688
6
            AddAddrFetch(seed);
2689
2690
6
            if (addrman.get().Size() == 0) {
2691
5
                LogInfo("Empty addrman, adding seednode (%s) to addrfetch\n", seed);
2692
5
            } else {
2693
1
                LogInfo("Couldn't connect to peers from addrman after %d seconds. Adding seednode (%s) to addrfetch\n", ADD_NEXT_SEEDNODE.count(), seed);
2694
1
            }
2695
6
        }
2696
2697
221
        ProcessAddrFetch();
2698
2699
221
        if (!m_interrupt_net->sleep_for(500ms)) {
2700
35
            return;
2701
35
        }
2702
2703
186
        PerformReconnections();
2704
2705
186
        CountingSemaphoreGrant<> grant(*semOutbound);
2706
186
        if (m_interrupt_net->interrupted()) {
2707
0
            return;
2708
0
        }
2709
2710
186
        const std::unordered_set<Network> fixed_seed_networks{GetReachableEmptyNetworks()};
2711
186
        if (add_fixed_seeds && !fixed_seed_networks.empty()) {
2712
            // When the node starts with an empty peers.dat, there are a few other sources of peers before
2713
            // we fallback on to fixed seeds: -dnsseed, -seednode, -addnode
2714
            // If none of those are available, we fallback on to fixed seeds immediately, else we allow
2715
            // 60 seconds for any of those sources to populate addrman.
2716
3
            bool add_fixed_seeds_now = false;
2717
            // It is cheapest to check if enough time has passed first.
2718
3
            if (GetTime<std::chrono::seconds>() > start + std::chrono::minutes{1}) {
2719
2
                add_fixed_seeds_now = true;
2720
2
                LogInfo("Adding fixed seeds as 60 seconds have passed and addrman is empty for at least one reachable network\n");
2721
2
            }
2722
2723
            // Perform cheap checks before locking a mutex.
2724
1
            else if (!dnsseed && !use_seednodes) {
2725
1
                LOCK(m_added_nodes_mutex);
2726
1
                if (m_added_node_params.empty()) {
2727
1
                    add_fixed_seeds_now = true;
2728
1
                    LogInfo("Adding fixed seeds as -dnsseed=0 (or IPv4/IPv6 connections are disabled via -onlynet) and neither -addnode nor -seednode are provided\n");
2729
1
                }
2730
1
            }
2731
2732
3
            if (add_fixed_seeds_now) {
2733
3
                std::vector<CAddress> seed_addrs{ConvertSeeds(m_params.FixedSeeds())};
2734
                // We will not make outgoing connections to peers that are unreachable
2735
                // (e.g. because of -onlynet configuration).
2736
                // Therefore, we do not add them to addrman in the first place.
2737
                // In case previously unreachable networks become reachable
2738
                // (e.g. in case of -onlynet changes by the user), fixed seeds will
2739
                // be loaded only for networks for which we have no addresses.
2740
3
                std::erase_if(seed_addrs, [&fixed_seed_networks](const CAddress& addr) { return !fixed_seed_networks.contains(addr.GetNetwork()); });
2741
3
                CNetAddr local;
2742
3
                local.SetInternal("fixedseeds");
2743
3
                addrman.get().Add(seed_addrs, local);
2744
3
                add_fixed_seeds = false;
2745
3
                LogInfo("Added %d fixed seeds from reachable networks.\n", seed_addrs.size());
2746
3
            }
2747
3
        }
2748
2749
        //
2750
        // Choose an address to connect to based on most recently seen
2751
        //
2752
186
        CAddress addrConnect;
2753
2754
        // Only connect out to one peer per ipv4/ipv6 network group (/16 for IPv4).
2755
186
        int nOutboundFullRelay = 0;
2756
186
        int nOutboundBlockRelay = 0;
2757
186
        int outbound_privacy_network_peers = 0;
2758
186
        std::set<std::vector<unsigned char>> outbound_ipv46_peer_netgroups;
2759
2760
186
        {
2761
186
            LOCK(m_nodes_mutex);
2762
800
            for (const CNode* pnode : m_nodes) {
2763
800
                if (pnode->IsFullOutboundConn()) nOutboundFullRelay++;
2764
800
                if (pnode->IsBlockOnlyConn()) nOutboundBlockRelay++;
2765
2766
                // Make sure our persistent outbound slots to ipv4/ipv6 peers belong to different netgroups.
2767
800
                switch (pnode->m_conn_type) {
2768
                    // We currently don't take inbound connections into account. Since they are
2769
                    // free to make, an attacker could make them to prevent us from connecting to
2770
                    // certain peers.
2771
2
                    case ConnectionType::INBOUND:
2772
                    // Short-lived outbound connections should not affect how we select outbound
2773
                    // peers from addrman.
2774
14
                    case ConnectionType::ADDR_FETCH:
2775
14
                    case ConnectionType::FEELER:
2776
32
                    case ConnectionType::PRIVATE_BROADCAST:
2777
32
                        break;
2778
3
                    case ConnectionType::MANUAL:
2779
622
                    case ConnectionType::OUTBOUND_FULL_RELAY:
2780
768
                    case ConnectionType::BLOCK_RELAY:
2781
768
                        const CAddress address{pnode->addr};
2782
768
                        if (address.IsTor() || address.IsI2P() || address.IsCJDNS()) {
2783
                            // Since our addrman-groups for these networks are
2784
                            // random, without relation to the route we
2785
                            // take to connect to these peers or to the
2786
                            // difficulty in obtaining addresses with diverse
2787
                            // groups, we don't worry about diversity with
2788
                            // respect to our addrman groups when connecting to
2789
                            // these networks.
2790
3
                            ++outbound_privacy_network_peers;
2791
765
                        } else {
2792
765
                            outbound_ipv46_peer_netgroups.insert(m_netgroupman.GetGroup(address));
2793
765
                        }
2794
800
                } // no default case, so the compiler can warn about missing cases
2795
800
            }
2796
186
        }
2797
2798
186
        if (!seed_nodes.empty() && nOutboundFullRelay < SEED_OUTBOUND_CONNECTION_THRESHOLD) {
2799
4
            if (NodeClock::now() > seed_node_timer + ADD_NEXT_SEEDNODE) {
2800
3
                seed_node_timer = NodeClock::now();
2801
3
                add_addr_fetch = true;
2802
3
            }
2803
4
        }
2804
2805
186
        ConnectionType conn_type = ConnectionType::OUTBOUND_FULL_RELAY;
2806
186
        auto now = GetTime<std::chrono::microseconds>();
2807
186
        bool anchor = false;
2808
186
        bool fFeeler = false;
2809
186
        std::optional<Network> preferred_net;
2810
2811
        // Determine what type of connection to open. Opening
2812
        // BLOCK_RELAY connections to addresses from anchors.dat gets the highest
2813
        // priority. Then we open OUTBOUND_FULL_RELAY priority until we
2814
        // meet our full-relay capacity. Then we open BLOCK_RELAY connection
2815
        // until we hit our block-relay-only peer limit.
2816
        // GetTryNewOutboundPeer() gets set when a stale tip is detected, so we
2817
        // try opening an additional OUTBOUND_FULL_RELAY connection. If none of
2818
        // these conditions are met, check to see if it's time to try an extra
2819
        // block-relay-only peer (to confirm our tip is current, see below) or the next_feeler
2820
        // timer to decide if we should open a FEELER.
2821
2822
        // Only consume anchors while the network is active; otherwise they would be
2823
        // popped and then dropped by OpenNetworkConnection(), losing them for the
2824
        // next activation and for the dump at shutdown.
2825
186
        const bool have_anchors{fNetworkActive && WITH_LOCK(m_anchors_mutex, return !m_anchors.empty())};
2826
186
        if (have_anchors && (nOutboundBlockRelay < m_max_outbound_block_relay)) {
2827
2
            conn_type = ConnectionType::BLOCK_RELAY;
2828
2
            anchor = true;
2829
184
        } else if (nOutboundFullRelay < m_max_outbound_full_relay) {
2830
            // OUTBOUND_FULL_RELAY
2831
111
        } else if (nOutboundBlockRelay < m_max_outbound_block_relay) {
2832
2
            conn_type = ConnectionType::BLOCK_RELAY;
2833
71
        } else if (GetTryNewOutboundPeer()) {
2834
            // OUTBOUND_FULL_RELAY
2835
71
        } else if (now > next_extra_block_relay && m_start_extra_block_relay_peers) {
2836
            // Periodically connect to a peer (using regular outbound selection
2837
            // methodology from addrman) and stay connected long enough to sync
2838
            // headers, but not much else.
2839
            //
2840
            // Then disconnect the peer, if we haven't learned anything new.
2841
            //
2842
            // The idea is to make eclipse attacks very difficult to pull off,
2843
            // because every few minutes we're finding a new peer to learn headers
2844
            // from.
2845
            //
2846
            // This is similar to the logic for trying extra outbound (full-relay)
2847
            // peers, except:
2848
            // - we do this all the time on an exponential timer, rather than just when
2849
            //   our tip is stale
2850
            // - we potentially disconnect our next-youngest block-relay-only peer, if our
2851
            //   newest block-relay-only peer delivers a block more recently.
2852
            //   See the eviction logic in net_processing.cpp.
2853
            //
2854
            // Because we can promote these connections to block-relay-only
2855
            // connections, they do not get their own ConnectionType enum
2856
            // (similar to how we deal with extra outbound peers).
2857
2
            next_extra_block_relay = now + rng.rand_exp_duration(EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL);
2858
2
            conn_type = ConnectionType::BLOCK_RELAY;
2859
69
        } else if (now > next_feeler) {
2860
2
            next_feeler = now + rng.rand_exp_duration(FEELER_INTERVAL);
2861
2
            conn_type = ConnectionType::FEELER;
2862
2
            fFeeler = true;
2863
67
        } else if (nOutboundFullRelay == m_max_outbound_full_relay &&
2864
67
                   m_max_outbound_full_relay == MAX_OUTBOUND_FULL_RELAY_CONNECTIONS &&
2865
67
                   now > next_extra_network_peer &&
2866
67
                   MaybePickPreferredNetwork(preferred_net)) {
2867
            // Full outbound connection management: Attempt to get at least one
2868
            // outbound peer from each reachable network by making extra connections
2869
            // and then protecting "only" peers from a network during outbound eviction.
2870
            // This is not attempted if the user changed -maxconnections to a value
2871
            // so low that less than MAX_OUTBOUND_FULL_RELAY_CONNECTIONS are made,
2872
            // to prevent interactions with otherwise protected outbound peers.
2873
1
            next_extra_network_peer = now + rng.rand_exp_duration(EXTRA_NETWORK_PEER_INTERVAL);
2874
66
        } else {
2875
            // skip to next iteration of while loop
2876
66
            continue;
2877
66
        }
2878
2879
120
        addrman.get().ResolveCollisions();
2880
2881
120
        const auto current_time{NodeClock::now()};
2882
120
        int nTries = 0;
2883
120
        const auto reachable_nets{g_reachable_nets.All()};
2884
2885
139
        while (!m_interrupt_net->interrupted()) {
2886
138
            if (anchor) {
2887
2
                std::optional<CAddress> anchor_addr;
2888
2
                {
2889
2
                    LOCK(m_anchors_mutex);
2890
2
                    if (!m_anchors.empty()) {
2891
2
                        anchor_addr = m_anchors.back();
2892
2
                        m_anchors.pop_back();
2893
2
                    }
2894
2
                }
2895
2
                if (anchor_addr) {
2896
2
                    if (!anchor_addr->IsValid() || IsLocal(*anchor_addr) || !g_reachable_nets.Contains(*anchor_addr) ||
2897
2
                        !m_msgproc->HasAllDesirableServiceFlags(anchor_addr->nServices) ||
2898
2
                        outbound_ipv46_peer_netgroups.contains(m_netgroupman.GetGroup(*anchor_addr))) continue;
2899
2
                    addrConnect = *anchor_addr;
2900
2
                    LogDebug(BCLog::NET, "Trying to make an anchor connection to %s\n", addrConnect.ToStringAddrPort());
2901
2
                    break;
2902
2
                }
2903
2
            }
2904
2905
            // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
2906
            // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
2907
            // already-connected network ranges, ...) before trying new addrman addresses.
2908
136
            nTries++;
2909
136
            if (nTries > 100)
2910
0
                break;
2911
2912
136
            CAddress addr;
2913
136
            NodeSeconds addr_last_try{0s};
2914
2915
136
            if (fFeeler) {
2916
                // First, try to get a tried table collision address. This returns
2917
                // an empty (invalid) address if there are no collisions to try.
2918
2
                std::tie(addr, addr_last_try) = addrman.get().SelectTriedCollision();
2919
2920
2
                if (!addr.IsValid()) {
2921
                    // No tried table collisions. Select a new table address
2922
                    // for our feeler.
2923
2
                    std::tie(addr, addr_last_try) = addrman.get().Select(true, reachable_nets);
2924
2
                } else if (AlreadyConnectedToAddress(addr)) {
2925
                    // If test-before-evict logic would have us connect to a
2926
                    // peer that we're already connected to, just mark that
2927
                    // address as Good(). We won't be able to initiate the
2928
                    // connection anyway, so this avoids inadvertently evicting
2929
                    // a currently-connected peer.
2930
0
                    addrman.get().Good(addr);
2931
                    // Select a new table address for our feeler instead.
2932
0
                    std::tie(addr, addr_last_try) = addrman.get().Select(true, reachable_nets);
2933
0
                }
2934
134
            } else {
2935
                // Not a feeler
2936
                // If preferred_net has a value set, pick an extra outbound
2937
                // peer from that network. The eviction logic in net_processing
2938
                // ensures that a peer from another network will be evicted.
2939
134
                std::tie(addr, addr_last_try) = preferred_net.has_value()
2940
134
                    ? addrman.get().Select(false, {*preferred_net})
2941
134
                    : addrman.get().Select(false, reachable_nets);
2942
134
            }
2943
2944
            // Require outbound IPv4/IPv6 connections, other than feelers, to be to distinct network groups
2945
136
            if (!fFeeler && outbound_ipv46_peer_netgroups.contains(m_netgroupman.GetGroup(addr))) {
2946
8
                continue;
2947
8
            }
2948
2949
            // if we selected an invalid or local address, restart
2950
128
            if (!addr.IsValid() || IsLocal(addr)) {
2951
95
                break;
2952
95
            }
2953
2954
33
            if (!g_reachable_nets.Contains(addr)) {
2955
0
                continue;
2956
0
            }
2957
2958
            // only consider very recently tried nodes after 30 failed attempts
2959
33
            if (current_time - addr_last_try < 10min && nTries < 30) {
2960
11
                continue;
2961
11
            }
2962
2963
            // for non-feelers, require all the services we'll want,
2964
            // for feelers, only require they be a full node (only because most
2965
            // SPV clients don't have a good address DB available)
2966
22
            if (!fFeeler && !m_msgproc->HasAllDesirableServiceFlags(addr.nServices)) {
2967
0
                continue;
2968
22
            } else if (fFeeler && !MayHaveUsefulAddressDB(addr.nServices)) {
2969
0
                continue;
2970
0
            }
2971
2972
            // Do not connect to bad ports, unless 50 invalid addresses have been selected already.
2973
22
            if (nTries < 50 && (addr.IsIPv4() || addr.IsIPv6()) && IsBadPort(addr.GetPort())) {
2974
0
                continue;
2975
0
            }
2976
2977
            // Do not make automatic outbound connections to addnode peers, to
2978
            // not use our limited outbound slots for them and to ensure
2979
            // addnode connections benefit from their intended protections.
2980
22
            if (AddedNodesContain(addr)) {
2981
0
                LogDebug(BCLog::NET, "Not making automatic %s%s connection to %s peer selected for manual (addnode) connection%s\n",
2982
0
                              preferred_net.has_value() ? "network-specific " : "",
2983
0
                              ConnectionTypeAsString(conn_type), GetNetworkName(addr.GetNetwork()),
2984
0
                              fLogIPs ? strprintf(": %s", addr.ToStringAddrPort()) : "");
2985
0
                continue;
2986
0
            }
2987
2988
22
            addrConnect = addr;
2989
22
            break;
2990
22
        }
2991
2992
120
        if (addrConnect.IsValid()) {
2993
24
            if (fFeeler) {
2994
                // Add small amount of random noise before connection to avoid synchronization.
2995
2
                if (!m_interrupt_net->sleep_for(rng.rand_uniform_duration<CThreadInterrupt::Clock>(FEELER_SLEEP_WINDOW))) {
2996
0
                    return;
2997
0
                }
2998
2
                LogDebug(BCLog::NET, "Making feeler connection to %s\n", addrConnect.ToStringAddrPort());
2999
2
            }
3000
3001
24
            if (preferred_net != std::nullopt) LogDebug(BCLog::NET, "Making network specific connection to %s on %s.\n", addrConnect.ToStringAddrPort(), GetNetworkName(preferred_net.value()));
3002
3003
            // Record addrman failure attempts when node has at least 2 persistent outbound connections to peers with
3004
            // different netgroups in ipv4/ipv6 networks + all peers in Tor/I2P/CJDNS networks.
3005
            // Don't record addrman failure attempts when node is offline. This can be identified since all local
3006
            // network connections (if any) belong in the same netgroup, and the size of `outbound_ipv46_peer_netgroups` would only be 1.
3007
24
            const bool count_failures{((int)outbound_ipv46_peer_netgroups.size() + outbound_privacy_network_peers) >= std::min(m_max_automatic_connections - 1, 2)};
3008
            // Use BIP324 transport when both us and them have NODE_V2_P2P set.
3009
24
            const bool use_v2transport(addrConnect.nServices & GetLocalServices() & NODE_P2P_V2);
3010
24
            OpenNetworkConnection(/*addrConnect=*/addrConnect,
3011
24
                                  /*fCountFailure=*/count_failures,
3012
24
                                  /*grant_outbound=*/std::move(grant),
3013
24
                                  /*pszDest=*/nullptr,
3014
24
                                  /*conn_type=*/conn_type,
3015
24
                                  /*use_v2transport=*/use_v2transport,
3016
24
                                  /*proxy_override=*/std::nullopt);
3017
24
        }
3018
120
    }
3019
41
}
3020
3021
std::vector<CAddress> CConnman::GetCurrentBlockRelayOnlyConns() const
3022
53
{
3023
53
    AssertLockNotHeld(m_nodes_mutex);
3024
53
    std::vector<CAddress> ret;
3025
53
    LOCK(m_nodes_mutex);
3026
53
    for (const CNode* pnode : m_nodes) {
3027
53
        if (pnode->IsBlockOnlyConn()) {
3028
8
            ret.push_back(pnode->addr);
3029
8
        }
3030
53
    }
3031
3032
53
    return ret;
3033
53
}
3034
3035
std::vector<AddedNodeInfo> CConnman::GetAddedNodeInfo(bool include_connected) const
3036
4.53k
{
3037
4.53k
    AssertLockNotHeld(m_nodes_mutex);
3038
3039
4.53k
    std::vector<AddedNodeInfo> ret;
3040
3041
4.53k
    std::list<AddedNodeParams> lAddresses(0);
3042
4.53k
    {
3043
4.53k
        LOCK(m_added_nodes_mutex);
3044
4.53k
        ret.reserve(m_added_node_params.size());
3045
4.53k
        std::copy(m_added_node_params.cbegin(), m_added_node_params.cend(), std::back_inserter(lAddresses));
3046
4.53k
    }
3047
3048
3049
    // Build a map of all already connected addresses (by IP:port and by name) to inbound/outbound and resolved CService
3050
4.53k
    std::map<CService, bool> mapConnected;
3051
4.53k
    std::map<std::string, std::pair<bool, CService>> mapConnectedByName;
3052
4.53k
    {
3053
4.53k
        LOCK(m_nodes_mutex);
3054
4.53k
        for (const CNode* pnode : m_nodes) {
3055
4.47k
            if (pnode->addr.IsValid()) {
3056
4.47k
                mapConnected[pnode->addr] = pnode->IsInboundConn();
3057
4.47k
            }
3058
4.47k
            std::string addrName{pnode->m_addr_name};
3059
4.47k
            if (!addrName.empty()) {
3060
4.47k
                mapConnectedByName[std::move(addrName)] = std::make_pair(pnode->IsInboundConn(), static_cast<const CService&>(pnode->addr));
3061
4.47k
            }
3062
4.47k
        }
3063
4.53k
    }
3064
3065
4.53k
    for (const auto& addr : lAddresses) {
3066
37
        CService service{MaybeFlipIPv6toCJDNS(LookupNumeric(addr.m_added_node, GetDefaultPort(addr.m_added_node)))};
3067
37
        AddedNodeInfo addedNode{addr, CService(), false, false};
3068
37
        if (service.IsValid()) {
3069
            // strAddNode is an IP:port
3070
33
            auto it = mapConnected.find(service);
3071
33
            if (it != mapConnected.end()) {
3072
15
                if (!include_connected) {
3073
5
                    continue;
3074
5
                }
3075
10
                addedNode.resolvedAddress = service;
3076
10
                addedNode.fConnected = true;
3077
10
                addedNode.fInbound = it->second;
3078
10
            }
3079
33
        } else {
3080
            // strAddNode is a name
3081
4
            auto it = mapConnectedByName.find(addr.m_added_node);
3082
4
            if (it != mapConnectedByName.end()) {
3083
0
                if (!include_connected) {
3084
0
                    continue;
3085
0
                }
3086
0
                addedNode.resolvedAddress = it->second.second;
3087
0
                addedNode.fConnected = true;
3088
0
                addedNode.fInbound = it->second.first;
3089
0
            }
3090
4
        }
3091
32
        ret.emplace_back(std::move(addedNode));
3092
32
    }
3093
3094
4.53k
    return ret;
3095
4.53k
}
3096
3097
void CConnman::ThreadOpenAddedConnections()
3098
1.10k
{
3099
1.10k
    AssertLockNotHeld(m_nodes_mutex);
3100
1.10k
    AssertLockNotHeld(m_reconnections_mutex);
3101
1.10k
    AssertLockNotHeld(m_unused_i2p_sessions_mutex);
3102
3103
4.51k
    while (true)
3104
4.51k
    {
3105
4.51k
        CountingSemaphoreGrant<> grant(*semAddnode);
3106
4.51k
        std::vector<AddedNodeInfo> vInfo = GetAddedNodeInfo(/*include_connected=*/false);
3107
4.51k
        bool tried = false;
3108
4.51k
        for (const AddedNodeInfo& info : vInfo) {
3109
5
            if (!grant) {
3110
                // If we've used up our semaphore and need a new one, let's not wait here since while we are waiting
3111
                // the addednodeinfo state might change.
3112
0
                break;
3113
0
            }
3114
5
            tried = true;
3115
5
            OpenNetworkConnection(/*addrConnect=*/CAddress{CService{}, NODE_NONE},
3116
5
                                  /*fCountFailure=*/false,
3117
5
                                  /*grant_outbound=*/std::move(grant),
3118
5
                                  /*pszDest=*/info.m_params.m_added_node.c_str(),
3119
5
                                  /*conn_type=*/ConnectionType::MANUAL,
3120
5
                                  /*use_v2transport=*/info.m_params.m_use_v2transport,
3121
5
                                  /*proxy_override=*/std::nullopt);
3122
5
            if (!m_interrupt_net->sleep_for(500ms)) return;
3123
3
            grant = CountingSemaphoreGrant<>(*semAddnode, /*fTry=*/true);
3124
3
        }
3125
        // See if any reconnections are desired.
3126
4.51k
        PerformReconnections();
3127
        // Retry every 60 seconds if a connection was attempted, otherwise two seconds
3128
4.51k
        if (!m_interrupt_net->sleep_for(tried ? 60s : 2s)) {
3129
1.10k
            return;
3130
1.10k
        }
3131
4.51k
    }
3132
1.10k
}
3133
3134
// if successful, this moves the passed grant to the constructed node
3135
bool CConnman::OpenNetworkConnection(const CAddress& addrConnect,
3136
                                     bool fCountFailure,
3137
                                     CountingSemaphoreGrant<>&& grant_outbound,
3138
                                     const char* pszDest,
3139
                                     ConnectionType conn_type,
3140
                                     bool use_v2transport,
3141
                                     const std::optional<Proxy>& proxy_override)
3142
714
{
3143
714
    AssertLockNotHeld(m_nodes_mutex);
3144
714
    AssertLockNotHeld(m_unused_i2p_sessions_mutex);
3145
714
    assert(conn_type != ConnectionType::INBOUND);
3146
3147
    //
3148
    // Initiate outbound network connection
3149
    //
3150
714
    if (m_interrupt_net->interrupted()) {
3151
1
        return false;
3152
1
    }
3153
713
    if (!fNetworkActive) {
3154
4
        return false;
3155
4
    }
3156
709
    if (!pszDest) {
3157
64
        bool banned_or_discouraged = m_banman && (m_banman->IsDiscouraged(addrConnect) || m_banman->IsBanned(addrConnect));
3158
64
        if (IsLocal(addrConnect) || banned_or_discouraged || AlreadyConnectedToAddress(addrConnect)) {
3159
8
            return false;
3160
8
        }
3161
645
    } else if (AlreadyConnectedToHost(pszDest)) {
3162
0
        return false;
3163
0
    }
3164
3165
701
    CNode* pnode = ConnectNode(addrConnect, pszDest, fCountFailure, conn_type, use_v2transport, proxy_override);
3166
3167
701
    if (!pnode)
3168
33
        return false;
3169
668
    pnode->grantOutbound = std::move(grant_outbound);
3170
3171
668
    m_msgproc->InitializeNode(*pnode, m_local_services);
3172
668
    {
3173
668
        LOCK(m_nodes_mutex);
3174
668
        m_nodes.push_back(pnode);
3175
3176
        // update connection count by network
3177
668
        if (pnode->IsManualOrFullOutboundConn()) ++m_network_conn_counts[pnode->addr.GetNetwork()];
3178
668
    }
3179
3180
668
    TRACEPOINT(net, outbound_connection,
3181
668
        pnode->GetId(),
3182
668
        pnode->m_addr_name.c_str(),
3183
668
        pnode->ConnectionTypeAsString().c_str(),
3184
668
        pnode->ConnectedThroughNetwork(),
3185
668
        GetNodeCount(ConnectionDirection::Out));
3186
3187
668
    return true;
3188
701
}
3189
3190
std::optional<Network> CConnman::PrivateBroadcast::PickNetwork(std::optional<Proxy>& proxy) const
3191
340
{
3192
340
    prevector<4, Network> nets;
3193
340
    std::optional<Proxy> clearnet_proxy;
3194
340
    proxy.reset();
3195
340
    if (g_reachable_nets.Contains(NET_ONION)) {
3196
340
        nets.push_back(NET_ONION);
3197
3198
340
        clearnet_proxy = ProxyForIPv4or6();
3199
340
        if (clearnet_proxy.has_value()) {
3200
46
            if (g_reachable_nets.Contains(NET_IPV4)) {
3201
46
                nets.push_back(NET_IPV4);
3202
46
            }
3203
46
            if (g_reachable_nets.Contains(NET_IPV6)) {
3204
46
                nets.push_back(NET_IPV6);
3205
46
            }
3206
46
        }
3207
340
    }
3208
340
    if (g_reachable_nets.Contains(NET_I2P)) {
3209
212
        nets.push_back(NET_I2P);
3210
212
    }
3211
3212
340
    if (nets.empty()) {
3213
0
        return std::nullopt;
3214
0
    }
3215
3216
340
    const Network net{nets[FastRandomContext{}.randrange(nets.size())]};
3217
340
    if (net == NET_IPV4 || net == NET_IPV6) {
3218
28
        proxy = clearnet_proxy;
3219
28
    }
3220
340
    return net;
3221
340
}
3222
3223
size_t CConnman::PrivateBroadcast::NumToOpen() const
3224
14
{
3225
14
    return m_num_to_open;
3226
14
}
3227
3228
void CConnman::PrivateBroadcast::NumToOpenAdd(size_t n)
3229
12.6k
{
3230
12.6k
    m_num_to_open += n;
3231
12.6k
    m_num_to_open.notify_all();
3232
12.6k
}
3233
3234
size_t CConnman::PrivateBroadcast::NumToOpenSub(size_t n)
3235
26
{
3236
26
    size_t current_value{m_num_to_open.load()};
3237
26
    size_t new_value;
3238
26
    do {
3239
26
        new_value = current_value > n ? current_value - n : 0;
3240
26
    } while (!m_num_to_open.compare_exchange_strong(current_value, new_value));
3241
26
    return new_value;
3242
26
}
3243
3244
void CConnman::PrivateBroadcast::NumToOpenWait() const
3245
345
{
3246
345
    m_num_to_open.wait(0);
3247
345
}
3248
3249
std::optional<Proxy> CConnman::PrivateBroadcast::ProxyForIPv4or6() const
3250
340
{
3251
340
    if (m_outbound_tor_ok_at_least_once.load()) {
3252
46
        if (const auto tor_proxy = GetProxy(NET_ONION)) {
3253
46
            return tor_proxy;
3254
46
        }
3255
46
    }
3256
294
    return std::nullopt;
3257
340
}
3258
3259
Mutex NetEventsInterface::g_msgproc_mutex;
3260
3261
void CConnman::ThreadMessageHandler()
3262
1.10k
{
3263
1.10k
    AssertLockNotHeld(m_nodes_mutex);
3264
3265
1.10k
    LOCK(NetEventsInterface::g_msgproc_mutex);
3266
3267
219k
    while (!flagInterruptMsgProc)
3268
217k
    {
3269
217k
        bool fMoreWork = false;
3270
3271
217k
        {
3272
            // Randomize the order in which we process messages from/to our peers.
3273
            // This prevents attacks in which an attacker exploits having multiple
3274
            // consecutive connections in the m_nodes list.
3275
217k
            const NodesSnapshot snap{*this, /*shuffle=*/true};
3276
3277
316k
            for (CNode* pnode : snap.Nodes()) {
3278
316k
                if (pnode->fDisconnect)
3279
98
                    continue;
3280
3281
                // Receive messages
3282
316k
                bool fMoreNodeWork{m_msgproc->ProcessMessages(*pnode, flagInterruptMsgProc)};
3283
316k
                fMoreWork |= (fMoreNodeWork && !pnode->fPauseSend);
3284
316k
                if (flagInterruptMsgProc)
3285
6
                    return;
3286
                // Send messages
3287
316k
                m_msgproc->SendMessages(*pnode);
3288
3289
316k
                if (flagInterruptMsgProc)
3290
1
                    return;
3291
316k
            }
3292
217k
        }
3293
3294
217k
        WAIT_LOCK(mutexMsgProc, lock);
3295
217k
        if (!fMoreWork) {
3296
272k
            condMsgProc.wait_until(lock, std::chrono::steady_clock::now() + std::chrono::milliseconds(100), [this]() EXCLUSIVE_LOCKS_REQUIRED(mutexMsgProc) { return fMsgProcWake; });
3297
147k
        }
3298
217k
        fMsgProcWake = false;
3299
217k
    }
3300
1.10k
}
3301
3302
void CConnman::ThreadI2PAcceptIncoming()
3303
5
{
3304
5
    AssertLockNotHeld(m_nodes_mutex);
3305
3306
5
    static constexpr auto err_wait_begin = 1s;
3307
5
    static constexpr auto err_wait_cap = 5min;
3308
5
    auto err_wait = err_wait_begin;
3309
3310
5
    bool advertising_listen_addr = false;
3311
5
    i2p::Connection conn;
3312
3313
22
    auto SleepOnFailure = [&]() {
3314
22
        m_interrupt_net->sleep_for(err_wait);
3315
22
        if (err_wait < err_wait_cap) {
3316
22
            err_wait += 1s;
3317
22
        }
3318
22
    };
3319
3320
27
    while (!m_interrupt_net->interrupted()) {
3321
3322
22
        if (!m_i2p_sam_session->Listen(conn)) {
3323
22
            if (advertising_listen_addr && conn.me.IsValid()) {
3324
0
                RemoveLocal(conn.me);
3325
0
                advertising_listen_addr = false;
3326
0
            }
3327
22
            SleepOnFailure();
3328
22
            continue;
3329
22
        }
3330
3331
0
        if (!advertising_listen_addr) {
3332
0
            AddLocal(conn.me, LOCAL_MANUAL);
3333
0
            advertising_listen_addr = true;
3334
0
        }
3335
3336
0
        if (!m_i2p_sam_session->Accept(conn)) {
3337
0
            SleepOnFailure();
3338
0
            continue;
3339
0
        }
3340
3341
0
        CreateNodeFromAcceptedSocket(std::move(conn.sock), NetPermissionFlags::None, conn.me, conn.peer);
3342
3343
0
        err_wait = err_wait_begin;
3344
0
    }
3345
5
}
3346
3347
void CConnman::ThreadPrivateBroadcast()
3348
7
{
3349
7
    AssertLockNotHeld(m_nodes_mutex);
3350
7
    AssertLockNotHeld(m_unused_i2p_sessions_mutex);
3351
3352
7
    size_t addrman_num_bad_addresses{0};
3353
347
    while (!m_interrupt_net->interrupted()) {
3354
3355
345
        if (!fNetworkActive) {
3356
0
            m_interrupt_net->sleep_for(5s);
3357
0
            continue;
3358
0
        }
3359
3360
345
        CountingSemaphoreGrant<> conn_max_grant{m_private_broadcast.m_sem_conn_max}; // Would block if too many are opened.
3361
3362
345
        m_private_broadcast.NumToOpenWait();
3363
3364
345
        if (m_interrupt_net->interrupted()) {
3365
5
            break;
3366
5
        }
3367
3368
340
        std::optional<Proxy> proxy;
3369
340
        const std::optional<Network> net{m_private_broadcast.PickNetwork(proxy)};
3370
340
        if (!net.has_value()) {
3371
0
            LogWarning("Unable to open -privatebroadcast connections: neither Tor nor I2P is reachable");
3372
0
            m_interrupt_net->sleep_for(5s);
3373
0
            continue;
3374
0
        }
3375
3376
340
        const auto [addr, _] = addrman.get().Select(/*new_only=*/false, {net.value()});
3377
3378
340
        if (!addr.IsValid() || IsLocal(addr)) {
3379
303
            ++addrman_num_bad_addresses;
3380
303
            if (addrman_num_bad_addresses > 100) {
3381
89
                LogDebug(BCLog::PRIVBROADCAST, "Connections needed but addrman keeps returning bad addresses, will retry");
3382
89
                m_interrupt_net->sleep_for(500ms);
3383
89
            }
3384
303
            continue;
3385
303
        }
3386
37
        addrman_num_bad_addresses = 0;
3387
3388
37
        auto target_str{addr.ToStringAddrPort()};
3389
37
        if (proxy.has_value()) {
3390
14
            target_str += " through the proxy at " + proxy->ToString();
3391
14
        }
3392
3393
37
        const bool use_v2transport(addr.nServices & GetLocalServices() & NODE_P2P_V2);
3394
3395
37
        if (OpenNetworkConnection(addr,
3396
37
                                  /*fCountFailure=*/true,
3397
37
                                  std::move(conn_max_grant),
3398
37
                                  /*pszDest=*/nullptr,
3399
37
                                  ConnectionType::PRIVATE_BROADCAST,
3400
37
                                  use_v2transport,
3401
37
                                  proxy)) {
3402
23
            const size_t remaining{m_private_broadcast.NumToOpenSub(1)};
3403
23
            LogDebug(BCLog::PRIVBROADCAST, "Socket connected to %s; remaining connections to open: %d", target_str, remaining);
3404
23
        } else {
3405
14
            const size_t remaining{m_private_broadcast.NumToOpen()};
3406
14
            if (remaining == 0) {
3407
0
                LogDebug(BCLog::PRIVBROADCAST, "Failed to connect to %s, will not retry, no more connections needed", target_str);
3408
14
            } else {
3409
14
                LogDebug(BCLog::PRIVBROADCAST, "Failed to connect to %s, will retry to a different address; remaining connections to open: %d", target_str, remaining);
3410
14
                m_interrupt_net->sleep_for(100ms); // Prevent busy loop if OpenNetworkConnection() fails fast repeatedly.
3411
14
            }
3412
14
        }
3413
37
    }
3414
7
}
3415
3416
bool CConnman::BindListenPort(const CService& addrBind, bilingual_str& strError, NetPermissionFlags permissions)
3417
1.11k
{
3418
1.11k
    int nOne = 1;
3419
3420
    // Create socket for listening for incoming connections
3421
1.11k
    struct sockaddr_storage sockaddr;
3422
1.11k
    socklen_t len = sizeof(sockaddr);
3423
1.11k
    if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
3424
0
    {
3425
0
        strError = Untranslated(strprintf("Bind address family for %s not supported", addrBind.ToStringAddrPort()));
3426
0
        LogError("%s\n", strError.original);
3427
0
        return false;
3428
0
    }
3429
3430
1.11k
    std::unique_ptr<Sock> sock = CreateSock(addrBind.GetSAFamily(), SOCK_STREAM, IPPROTO_TCP);
3431
1.11k
    if (!sock) {
3432
0
        strError = Untranslated(strprintf("Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError())));
3433
0
        LogError("%s\n", strError.original);
3434
0
        return false;
3435
0
    }
3436
3437
#ifdef WIN32
3438
    // Prevent another process from binding to the same address and port,
3439
    // which could allow it to intercept incoming P2P connections. On Windows,
3440
    // SO_REUSEADDR is NOT exclusive, so another process running under the same
3441
    // user account could bind to the same port.
3442
    if (sock->SetSockOpt(SOL_SOCKET, SO_EXCLUSIVEADDRUSE, &nOne, sizeof(int)) == SOCKET_ERROR) {
3443
        strError = Untranslated(strprintf("Error setting SO_EXCLUSIVEADDRUSE on socket: %s", NetworkErrorString(WSAGetLastError())));
3444
        LogError("%s\n", strError.original);
3445
        return false;
3446
    }
3447
#else
3448
    // Allow binding if the port is still in TIME_WAIT state after
3449
    // the program was closed and restarted.
3450
1.11k
    if (sock->SetSockOpt(SOL_SOCKET, SO_REUSEADDR, &nOne, sizeof(int)) == SOCKET_ERROR) {
3451
0
        strError = Untranslated(strprintf("Error setting SO_REUSEADDR on socket: %s, continuing anyway", NetworkErrorString(WSAGetLastError())));
3452
0
        LogInfo("%s\n", strError.original);
3453
0
    }
3454
1.11k
#endif
3455
3456
    // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
3457
    // and enable it by default or not. Try to enable it, if possible.
3458
1.11k
    if (addrBind.IsIPv6()) {
3459
4
#ifdef IPV6_V6ONLY
3460
4
        if (sock->SetSockOpt(IPPROTO_IPV6, IPV6_V6ONLY, &nOne, sizeof(int)) == SOCKET_ERROR) {
3461
0
            strError = Untranslated(strprintf("Error setting IPV6_V6ONLY on socket: %s, continuing anyway", NetworkErrorString(WSAGetLastError())));
3462
0
            LogInfo("%s\n", strError.original);
3463
0
        }
3464
4
#endif
3465
#ifdef WIN32
3466
        int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED;
3467
        if (sock->SetSockOpt(IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, &nProtLevel, sizeof(int)) == SOCKET_ERROR) {
3468
            strError = Untranslated(strprintf("Error setting IPV6_PROTECTION_LEVEL on socket: %s, continuing anyway", NetworkErrorString(WSAGetLastError())));
3469
            LogInfo("%s\n", strError.original);
3470
        }
3471
#endif
3472
4
    }
3473
3474
1.11k
    if (sock->Bind(reinterpret_cast<struct sockaddr*>(&sockaddr), len) == SOCKET_ERROR) {
3475
12
        int nErr = WSAGetLastError();
3476
12
        if (nErr == WSAEADDRINUSE)
3477
1
            strError = strprintf(_("Unable to bind to %s on this computer. %s is probably already running."), addrBind.ToStringAddrPort(), CLIENT_NAME);
3478
11
        else
3479
11
            strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToStringAddrPort(), NetworkErrorString(nErr));
3480
12
        LogError("%s\n", strError.original);
3481
12
        return false;
3482
12
    }
3483
1.10k
    LogInfo("Bound to %s\n", addrBind.ToStringAddrPort());
3484
3485
    // Listen for incoming connections
3486
1.10k
    if (sock->Listen(SOMAXCONN) == SOCKET_ERROR)
3487
0
    {
3488
0
        strError = strprintf(_("Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError()));
3489
0
        LogError("%s\n", strError.original);
3490
0
        return false;
3491
0
    }
3492
3493
1.10k
    vhListenSocket.emplace_back(std::move(sock), permissions);
3494
1.10k
    return true;
3495
1.10k
}
3496
3497
void Discover()
3498
38
{
3499
38
    if (!fDiscover)
3500
32
        return;
3501
3502
18
    for (const CNetAddr &addr: GetLocalAddresses()) {
3503
18
        if (AddLocal(addr, LOCAL_IF) && fLogIPs) {
3504
0
            LogInfo("%s: %s\n", __func__, addr.ToStringAddr());
3505
0
        }
3506
18
    }
3507
6
}
3508
3509
void CConnman::SetNetworkActive(bool active)
3510
1.40k
{
3511
1.40k
    LogInfo("%s: %s\n", __func__, active);
3512
3513
1.40k
    if (fNetworkActive == active) {
3514
1.39k
        return;
3515
1.39k
    }
3516
3517
18
    if (!active) {
3518
        // Remember the current block-relay-only peers so they can be retried
3519
        // once the network is re-enabled, or dumped at shutdown. Keep any
3520
        // not-yet-tried anchors if there are no such peers.
3521
12
        auto anchors = GetCurrentBlockRelayOnlyConns();
3522
12
        if (anchors.size() > MAX_BLOCK_RELAY_ONLY_ANCHORS) {
3523
            // Keep the oldest peers, as when saving anchors at shutdown.
3524
0
            anchors.resize(MAX_BLOCK_RELAY_ONLY_ANCHORS);
3525
0
        }
3526
12
        if (!anchors.empty()) {
3527
1
            LOCK(m_anchors_mutex);
3528
1
            m_anchors = std::move(anchors);
3529
1
        }
3530
12
    }
3531
3532
18
    fNetworkActive = active;
3533
3534
18
    if (m_client_interface) {
3535
11
        m_client_interface->NotifyNetworkActiveChanged(fNetworkActive);
3536
11
    }
3537
18
}
3538
3539
CConnman::CConnman(uint64_t nSeed0In,
3540
                   uint64_t nSeed1In,
3541
                   AddrMan& addrman_in,
3542
                   const NetGroupManager& netgroupman,
3543
                   const CChainParams& params,
3544
                   bool network_active,
3545
                   std::shared_ptr<CThreadInterrupt> interrupt_net)
3546
1.39k
    : addrman(addrman_in)
3547
1.39k
    , m_netgroupman{netgroupman}
3548
1.39k
    , nSeed0(nSeed0In)
3549
1.39k
    , nSeed1(nSeed1In)
3550
1.39k
    , m_interrupt_net{interrupt_net}
3551
1.39k
    , m_params(params)
3552
1.39k
{
3553
1.39k
    SetTryNewOutboundPeer(false);
3554
3555
1.39k
    Options connOptions;
3556
1.39k
    Init(connOptions);
3557
1.39k
    SetNetworkActive(network_active);
3558
1.39k
}
3559
3560
NodeId CConnman::GetNewNodeId()
3561
1.79k
{
3562
1.79k
    return nLastNodeId.fetch_add(1, std::memory_order_relaxed);
3563
1.79k
}
3564
3565
uint16_t CConnman::GetDefaultPort(Network net) const
3566
2
{
3567
2
    return net == NET_I2P ? I2P_SAM31_PORT : m_params.GetDefaultPort();
3568
2
}
3569
3570
uint16_t CConnman::GetDefaultPort(const std::string& addr) const
3571
723
{
3572
723
    CNetAddr a;
3573
723
    return a.SetSpecial(addr) ? GetDefaultPort(a.GetNetwork()) : m_params.GetDefaultPort();
3574
723
}
3575
3576
bool CConnman::Bind(const CService& addr_, unsigned int flags, NetPermissionFlags permissions)
3577
1.11k
{
3578
1.11k
    const CService addr{MaybeFlipIPv6toCJDNS(addr_)};
3579
3580
1.11k
    bilingual_str strError;
3581
1.11k
    if (!BindListenPort(addr, strError, permissions)) {
3582
12
        if ((flags & BF_REPORT_ERROR) && m_client_interface) {
3583
12
            m_client_interface->ThreadSafeMessageBox(strError, CClientUIInterface::MSG_ERROR);
3584
12
        }
3585
12
        return false;
3586
12
    }
3587
3588
1.10k
    if (addr.IsRoutable() && fDiscover && !(flags & BF_DONT_ADVERTISE) && !NetPermissions::HasFlag(permissions, NetPermissionFlags::NoBan)) {
3589
0
        AddLocal(addr, LOCAL_BIND);
3590
0
    }
3591
3592
1.10k
    return true;
3593
1.11k
}
3594
3595
bool CConnman::InitBinds(const Options& options)
3596
1.09k
{
3597
1.09k
    for (const auto& addrBind : options.vBinds) {
3598
1.08k
        if (!Bind(addrBind, BF_REPORT_ERROR, NetPermissionFlags::None)) {
3599
10
            return false;
3600
10
        }
3601
1.08k
    }
3602
1.08k
    for (const auto& addrBind : options.vWhiteBinds) {
3603
3
        if (!Bind(addrBind.m_service, BF_REPORT_ERROR, addrBind.m_flags)) {
3604
1
            return false;
3605
1
        }
3606
3
    }
3607
1.08k
    for (const auto& addr_bind : options.onion_binds) {
3608
21
        if (!Bind(addr_bind, BF_REPORT_ERROR | BF_DONT_ADVERTISE, NetPermissionFlags::None)) {
3609
0
            return false;
3610
0
        }
3611
21
    }
3612
1.08k
    if (options.bind_on_any) {
3613
        // Don't consider errors to bind on IPv6 "::" fatal because the host OS
3614
        // may not have IPv6 support and the user did not explicitly ask us to
3615
        // bind on that.
3616
4
        const CService ipv6_any{in6_addr(COMPAT_IN6ADDR_ANY_INIT), GetListenPort()}; // ::
3617
4
        Bind(ipv6_any, BF_NONE, NetPermissionFlags::None);
3618
3619
4
        struct in_addr inaddr_any;
3620
4
        inaddr_any.s_addr = htonl(INADDR_ANY);
3621
4
        const CService ipv4_any{inaddr_any, GetListenPort()}; // 0.0.0.0
3622
4
        if (!Bind(ipv4_any, BF_REPORT_ERROR, NetPermissionFlags::None)) {
3623
1
            return false;
3624
1
        }
3625
4
    }
3626
1.08k
    return true;
3627
1.08k
}
3628
3629
bool CConnman::Start(CScheduler& scheduler, const Options& connOptions)
3630
1.11k
{
3631
1.11k
    AssertLockNotHeld(m_total_bytes_sent_mutex);
3632
1.11k
    Init(connOptions);
3633
3634
1.11k
    if (fListen && !InitBinds(connOptions)) {
3635
12
        if (m_client_interface) {
3636
12
            m_client_interface->ThreadSafeMessageBox(
3637
12
                _("Failed to listen on any port. Use -listen=0 if you want this."),
3638
12
                CClientUIInterface::MSG_ERROR);
3639
12
        }
3640
12
        return false;
3641
12
    }
3642
3643
1.10k
    if (connOptions.m_i2p_accept_incoming) {
3644
1.08k
        if (const auto i2p_sam = GetProxy(NET_I2P)) {
3645
5
            m_i2p_sam_session = std::make_unique<i2p::sam::Session>(gArgs.GetDataDirNet() / "i2p_private_key",
3646
5
                                                                    *i2p_sam, m_interrupt_net);
3647
5
        }
3648
1.08k
    }
3649
3650
    // Randomize the order in which we may query seednode to potentially prevent connecting to the same one every restart (and signal that we have restarted)
3651
1.10k
    std::vector<std::string> seed_nodes = connOptions.vSeedNodes;
3652
1.10k
    if (!seed_nodes.empty()) {
3653
7
        std::shuffle(seed_nodes.begin(), seed_nodes.end(), FastRandomContext{});
3654
7
    }
3655
3656
1.10k
    if (m_use_addrman_outgoing) {
3657
        // Load addresses from anchors.dat
3658
41
        LOCK(m_anchors_mutex);
3659
41
        m_anchors = ReadAnchors(gArgs.GetDataDirNet() / ANCHORS_DATABASE_FILENAME);
3660
41
        if (m_anchors.size() > MAX_BLOCK_RELAY_ONLY_ANCHORS) {
3661
0
            m_anchors.resize(MAX_BLOCK_RELAY_ONLY_ANCHORS);
3662
0
        }
3663
41
        if (fNetworkActive) {
3664
36
            LogInfo("%i block-relay-only anchors will be tried for connections.\n", m_anchors.size());
3665
36
        }
3666
41
    }
3667
3668
1.10k
    if (m_client_interface) {
3669
1.10k
        m_client_interface->InitMessage(_("Starting network threads…"));
3670
1.10k
    }
3671
3672
1.10k
    fAddressesInitialized = true;
3673
3674
1.10k
    if (semOutbound == nullptr) {
3675
        // initialize semaphore
3676
1.10k
        semOutbound = std::make_unique<std::counting_semaphore<>>(std::min(m_max_automatic_outbound, m_max_automatic_connections));
3677
1.10k
    }
3678
1.10k
    if (semAddnode == nullptr) {
3679
        // initialize semaphore
3680
1.10k
        semAddnode = std::make_unique<std::counting_semaphore<>>(m_max_addnode);
3681
1.10k
    }
3682
3683
    //
3684
    // Start threads
3685
    //
3686
1.10k
    assert(m_msgproc);
3687
1.10k
    m_interrupt_net->reset();
3688
1.10k
    flagInterruptMsgProc = false;
3689
3690
1.10k
    {
3691
1.10k
        LOCK(mutexMsgProc);
3692
1.10k
        fMsgProcWake = false;
3693
1.10k
    }
3694
3695
    // Send and receive from sockets, accept connections
3696
1.10k
    threadSocketHandler = std::thread(&util::TraceThread, "net", [this] { ThreadSocketHandler(); });
3697
3698
1.10k
    if (!gArgs.GetBoolArg("-dnsseed", DEFAULT_DNSSEED))
3699
1.10k
        LogInfo("DNS seeding disabled\n");
3700
13
    else
3701
13
        threadDNSAddressSeed = std::thread(&util::TraceThread, "dnsseed", [this] { ThreadDNSAddressSeed(); });
3702
3703
    // Initiate manual connections
3704
1.10k
    threadOpenAddedConnections = std::thread(&util::TraceThread, "addcon", [this] { ThreadOpenAddedConnections(); });
3705
3706
1.10k
    if (connOptions.m_use_addrman_outgoing && !connOptions.m_specified_outgoing.empty()) {
3707
0
        if (m_client_interface) {
3708
0
            m_client_interface->ThreadSafeMessageBox(
3709
0
                _("Cannot provide specific connections and have addrman find outgoing connections at the same time."),
3710
0
                CClientUIInterface::MSG_ERROR);
3711
0
        }
3712
0
        return false;
3713
0
    }
3714
1.10k
    if (connOptions.m_use_addrman_outgoing || !connOptions.m_specified_outgoing.empty()) {
3715
46
        threadOpenConnections = std::thread(
3716
46
            &util::TraceThread, "opencon",
3717
46
            [this, connect = connOptions.m_specified_outgoing, seed_nodes = std::move(seed_nodes)] { ThreadOpenConnections(connect, seed_nodes); });
3718
46
    }
3719
3720
    // Process messages
3721
1.10k
    threadMessageHandler = std::thread(&util::TraceThread, "msghand", [this] { ThreadMessageHandler(); });
3722
3723
1.10k
    if (m_i2p_sam_session) {
3724
5
        threadI2PAcceptIncoming =
3725
5
            std::thread(&util::TraceThread, "i2paccept", [this] { ThreadI2PAcceptIncoming(); });
3726
5
    }
3727
3728
1.10k
    if (gArgs.GetBoolArg("-privatebroadcast", DEFAULT_PRIVATE_BROADCAST)) {
3729
7
        threadPrivateBroadcast =
3730
7
            std::thread(&util::TraceThread, "privbcast", [this] { ThreadPrivateBroadcast(); });
3731
7
    }
3732
3733
    // Dump network addresses
3734
1.10k
    scheduler.scheduleEvery([this] { DumpAddresses(); }, DUMP_PEERS_INTERVAL);
3735
3736
    // Run the ASMap Health check once and then schedule it to run every 24h.
3737
1.10k
    if (m_netgroupman.UsingASMap()) {
3738
7
        ASMapHealthCheck();
3739
7
        scheduler.scheduleEvery([this] { ASMapHealthCheck(); }, ASMAP_HEALTH_CHECK_INTERVAL);
3740
7
    }
3741
3742
1.10k
    return true;
3743
1.10k
}
3744
3745
class CNetCleanup
3746
{
3747
public:
3748
    CNetCleanup() = default;
3749
3750
    ~CNetCleanup()
3751
0
    {
3752
#ifdef WIN32
3753
        // Shutdown Windows Sockets
3754
        WSACleanup();
3755
#endif
3756
0
    }
3757
};
3758
static CNetCleanup instance_of_cnetcleanup;
3759
3760
void CConnman::Interrupt()
3761
2.58k
{
3762
2.58k
    {
3763
2.58k
        LOCK(mutexMsgProc);
3764
2.58k
        flagInterruptMsgProc = true;
3765
2.58k
    }
3766
2.58k
    condMsgProc.notify_all();
3767
3768
2.58k
    (*m_interrupt_net)();
3769
2.58k
    g_socks5_interrupt();
3770
3771
2.58k
    if (semOutbound) {
3772
13.2k
        for (int i=0; i<m_max_automatic_outbound; i++) {
3773
12.1k
            semOutbound->release();
3774
12.1k
        }
3775
1.10k
    }
3776
3777
2.58k
    if (semAddnode) {
3778
9.96k
        for (int i=0; i<m_max_addnode; i++) {
3779
8.85k
            semAddnode->release();
3780
8.85k
        }
3781
1.10k
    }
3782
3783
2.58k
    m_private_broadcast.m_sem_conn_max.release();
3784
2.58k
    m_private_broadcast.NumToOpenAdd(1); // Just unblock NumToOpenWait() to be able to continue with shutdown.
3785
2.58k
}
3786
3787
void CConnman::StopThreads()
3788
2.58k
{
3789
2.58k
    if (threadPrivateBroadcast.joinable()) {
3790
7
        threadPrivateBroadcast.join();
3791
7
    }
3792
2.58k
    if (threadI2PAcceptIncoming.joinable()) {
3793
5
        threadI2PAcceptIncoming.join();
3794
5
    }
3795
2.58k
    if (threadMessageHandler.joinable())
3796
1.10k
        threadMessageHandler.join();
3797
2.58k
    if (threadOpenConnections.joinable())
3798
46
        threadOpenConnections.join();
3799
2.58k
    if (threadOpenAddedConnections.joinable())
3800
1.10k
        threadOpenAddedConnections.join();
3801
2.58k
    if (threadDNSAddressSeed.joinable())
3802
13
        threadDNSAddressSeed.join();
3803
2.58k
    if (threadSocketHandler.joinable())
3804
1.10k
        threadSocketHandler.join();
3805
2.58k
}
3806
3807
void CConnman::StopNodes()
3808
2.58k
{
3809
2.58k
    AssertLockNotHeld(m_nodes_mutex);
3810
2.58k
    AssertLockNotHeld(m_reconnections_mutex);
3811
2.58k
    AssertLockNotHeld(m_anchors_mutex);
3812
3813
2.58k
    if (fAddressesInitialized) {
3814
1.10k
        DumpAddresses();
3815
1.10k
        fAddressesInitialized = false;
3816
3817
1.10k
        if (m_use_addrman_outgoing) {
3818
            // Anchor connections are only dumped during clean shutdown.
3819
41
            std::vector<CAddress> anchors_to_dump = GetCurrentBlockRelayOnlyConns();
3820
41
            {
3821
41
                LOCK(m_anchors_mutex);
3822
41
                if (!fNetworkActive && !m_anchors.empty()) {
3823
2
                    anchors_to_dump = m_anchors;
3824
2
                }
3825
41
            }
3826
41
            if (anchors_to_dump.size() > MAX_BLOCK_RELAY_ONLY_ANCHORS) {
3827
1
                anchors_to_dump.resize(MAX_BLOCK_RELAY_ONLY_ANCHORS);
3828
1
            }
3829
41
            DumpAnchors(gArgs.GetDataDirNet() / ANCHORS_DATABASE_FILENAME, anchors_to_dump);
3830
41
        }
3831
1.10k
    }
3832
3833
    // Delete peer connections.
3834
2.58k
    std::vector<CNode*> nodes;
3835
2.58k
    WITH_LOCK(m_nodes_mutex, nodes.swap(m_nodes));
3836
2.58k
    for (CNode* pnode : nodes) {
3837
794
        LogDebug(BCLog::NET, "Stopping node, %s", pnode->DisconnectMsg());
3838
794
        pnode->CloseSocketDisconnect();
3839
794
        DeleteNode(pnode);
3840
794
    }
3841
3842
2.58k
    for (CNode* pnode : m_nodes_disconnected) {
3843
2
        DeleteNode(pnode);
3844
2
    }
3845
2.58k
    m_nodes_disconnected.clear();
3846
2.58k
    WITH_LOCK(m_reconnections_mutex, m_reconnections.clear());
3847
2.58k
    vhListenSocket.clear();
3848
2.58k
    semOutbound.reset();
3849
2.58k
    semAddnode.reset();
3850
2.58k
}
3851
3852
void CConnman::DeleteNode(CNode* pnode)
3853
1.81k
{
3854
1.81k
    assert(pnode);
3855
1.81k
    m_msgproc->FinalizeNode(*pnode);
3856
1.81k
    delete pnode;
3857
1.81k
}
3858
3859
CConnman::~CConnman()
3860
1.39k
{
3861
1.39k
    Interrupt();
3862
1.39k
    Stop();
3863
1.39k
}
3864
3865
std::vector<CAddress> CConnman::GetAddressesUnsafe(size_t max_addresses, size_t max_pct, std::optional<Network> network, const bool filtered) const
3866
491
{
3867
491
    std::vector<CAddress> addresses = addrman.get().GetAddr(max_addresses, max_pct, network, filtered);
3868
491
    if (m_banman) {
3869
34.4k
        std::erase_if(addresses, [this](const CAddress& addr) { return m_banman->IsDiscouraged(addr) || m_banman->IsBanned(addr); });
3870
491
    }
3871
491
    return addresses;
3872
491
}
3873
3874
std::vector<CAddress> CConnman::GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct)
3875
1.01k
{
3876
1.01k
    uint64_t network_id = requestor.m_network_key;
3877
1.01k
    const auto current_time = GetTime<std::chrono::microseconds>();
3878
1.01k
    auto r = m_addr_response_caches.emplace(network_id, CachedAddrResponse{});
3879
1.01k
    CachedAddrResponse& cache_entry = r.first->second;
3880
1.01k
    if (cache_entry.m_cache_entry_expiration < current_time) { // If emplace() added new one it has expiration 0.
3881
402
        cache_entry.m_addrs_response_cache = GetAddressesUnsafe(max_addresses, max_pct, /*network=*/std::nullopt);
3882
        // Choosing a proper cache lifetime is a trade-off between the privacy leak minimization
3883
        // and the usefulness of ADDR responses to honest users.
3884
        //
3885
        // Longer cache lifetime makes it more difficult for an attacker to scrape
3886
        // enough AddrMan data to maliciously infer something useful.
3887
        // By the time an attacker scraped enough AddrMan records, most of
3888
        // the records should be old enough to not leak topology info by
3889
        // e.g. analyzing real-time changes in timestamps.
3890
        //
3891
        // It takes only several hundred requests to scrape everything from an AddrMan containing 100,000 nodes,
3892
        // so ~24 hours of cache lifetime indeed makes the data less inferable by the time
3893
        // most of it could be scraped (considering that timestamps are updated via
3894
        // ADDR self-announcements and when nodes communicate).
3895
        // We also should be robust to those attacks which may not require scraping *full* victim's AddrMan
3896
        // (because even several timestamps of the same handful of nodes may leak privacy).
3897
        //
3898
        // On the other hand, longer cache lifetime makes ADDR responses
3899
        // outdated and less useful for an honest requestor, e.g. if most nodes
3900
        // in the ADDR response are no longer active.
3901
        //
3902
        // However, the churn in the network is known to be rather low. Since we consider
3903
        // nodes to be "terrible" (see IsTerrible()) if the timestamps are older than 30 days,
3904
        // max. 24 hours of "penalty" due to cache shouldn't make any meaningful difference
3905
        // in terms of the freshness of the response.
3906
402
        cache_entry.m_cache_entry_expiration = current_time +
3907
402
            21h + FastRandomContext().randrange<std::chrono::microseconds>(6h);
3908
402
    }
3909
1.01k
    return cache_entry.m_addrs_response_cache;
3910
1.01k
}
3911
3912
bool CConnman::AddNode(const AddedNodeParams& add)
3913
15
{
3914
15
    const CService resolved(LookupNumeric(add.m_added_node, GetDefaultPort(add.m_added_node)));
3915
15
    const bool resolved_is_valid{resolved.IsValid()};
3916
3917
15
    LOCK(m_added_nodes_mutex);
3918
18
    for (const auto& it : m_added_node_params) {
3919
18
        if (add.m_added_node == it.m_added_node || (resolved_is_valid && resolved == LookupNumeric(it.m_added_node, GetDefaultPort(it.m_added_node)))) return false;
3920
18
    }
3921
3922
9
    m_added_node_params.push_back(add);
3923
9
    return true;
3924
15
}
3925
3926
bool CConnman::RemoveAddedNode(std::string_view node)
3927
4
{
3928
4
    LOCK(m_added_nodes_mutex);
3929
6
    for (auto it = m_added_node_params.begin(); it != m_added_node_params.end(); ++it) {
3930
4
        if (node == it->m_added_node) {
3931
2
            m_added_node_params.erase(it);
3932
2
            return true;
3933
2
        }
3934
4
    }
3935
2
    return false;
3936
4
}
3937
3938
bool CConnman::AddedNodesContain(const CAddress& addr) const
3939
28
{
3940
28
    AssertLockNotHeld(m_added_nodes_mutex);
3941
28
    const std::string addr_str{addr.ToStringAddr()};
3942
28
    const std::string addr_port_str{addr.ToStringAddrPort()};
3943
28
    LOCK(m_added_nodes_mutex);
3944
28
    return (m_added_node_params.size() < 24 // bound the query to a reasonable limit
3945
28
            && std::any_of(m_added_node_params.cbegin(), m_added_node_params.cend(),
3946
28
                           [&](const auto& p) { return p.m_added_node == addr_str || p.m_added_node == addr_port_str; }));
3947
28
}
3948
3949
size_t CConnman::GetNodeCount(ConnectionDirection flags) const
3950
2.89k
{
3951
2.89k
    LOCK(m_nodes_mutex);
3952
2.89k
    if (flags == ConnectionDirection::Both) // Shortcut if we want total
3953
970
        return m_nodes.size();
3954
3955
1.92k
    int nNum = 0;
3956
1.92k
    for (const auto& pnode : m_nodes) {
3957
1.05k
        if (flags & (pnode->IsInboundConn() ? ConnectionDirection::In : ConnectionDirection::Out)) {
3958
526
            nNum++;
3959
526
        }
3960
1.05k
    }
3961
3962
1.92k
    return nNum;
3963
2.89k
}
3964
3965
3966
std::map<CNetAddr, LocalServiceInfo> CConnman::getNetLocalAddresses() const
3967
0
{
3968
0
    LOCK(g_maplocalhost_mutex);
3969
0
    return mapLocalHost;
3970
0
}
3971
3972
uint32_t CConnman::GetMappedAS(const CNetAddr& addr) const
3973
24.2k
{
3974
24.2k
    return m_netgroupman.GetMappedAS(addr);
3975
24.2k
}
3976
3977
void CConnman::GetNodeStats(std::vector<CNodeStats>& vstats) const
3978
11.0k
{
3979
11.0k
    AssertLockNotHeld(m_nodes_mutex);
3980
3981
11.0k
    vstats.clear();
3982
11.0k
    LOCK(m_nodes_mutex);
3983
11.0k
    vstats.reserve(m_nodes.size());
3984
20.8k
    for (CNode* pnode : m_nodes) {
3985
20.8k
        vstats.emplace_back();
3986
20.8k
        pnode->CopyStats(vstats.back());
3987
20.8k
        vstats.back().m_mapped_as = GetMappedAS(pnode->addr);
3988
20.8k
    }
3989
11.0k
}
3990
3991
bool CConnman::DisconnectNode(std::string_view strNode)
3992
4
{
3993
4
    LOCK(m_nodes_mutex);
3994
6
    auto it = std::ranges::find_if(m_nodes, [&strNode](CNode* node) { return node->m_addr_name == strNode; });
3995
4
    if (it != m_nodes.end()) {
3996
2
        CNode* node{*it};
3997
2
        LogDebug(BCLog::NET, "disconnect by address%s match, %s", (fLogIPs ? strprintf("=%s", strNode) : ""), node->DisconnectMsg());
3998
2
        node->fDisconnect = true;
3999
2
        return true;
4000
2
    }
4001
2
    return false;
4002
4
}
4003
4004
bool CConnman::DisconnectNode(const CSubNet& subnet, bool disconnect_private_broadcast)
4005
34
{
4006
34
    AssertLockNotHeld(m_nodes_mutex);
4007
34
    bool disconnected = false;
4008
34
    LOCK(m_nodes_mutex);
4009
34
    for (CNode* pnode : m_nodes) {
4010
17
        if (subnet.Match(pnode->addr) && (disconnect_private_broadcast || !pnode->IsPrivateBroadcastConn())) {
4011
11
            LogDebug(BCLog::NET, "disconnect by subnet%s match, %s", (fLogIPs ? strprintf("=%s", subnet.ToString()) : ""), pnode->DisconnectMsg());
4012
11
            pnode->fDisconnect = true;
4013
11
            disconnected = true;
4014
11
        }
4015
17
    }
4016
34
    return disconnected;
4017
34
}
4018
4019
bool CConnman::DisconnectNode(const CNetAddr& addr)
4020
16
{
4021
16
    AssertLockNotHeld(m_nodes_mutex);
4022
16
    return DisconnectNode(CSubNet(addr));
4023
16
}
4024
4025
bool CConnman::DisconnectNode(NodeId id)
4026
100
{
4027
100
    LOCK(m_nodes_mutex);
4028
160
    for(CNode* pnode : m_nodes) {
4029
160
        if (id == pnode->GetId()) {
4030
100
            LogDebug(BCLog::NET, "disconnect by id, %s", pnode->DisconnectMsg());
4031
100
            pnode->fDisconnect = true;
4032
100
            return true;
4033
100
        }
4034
160
    }
4035
0
    return false;
4036
100
}
4037
4038
void CConnman::RecordBytesRecv(uint64_t bytes)
4039
153k
{
4040
153k
    nTotalBytesRecv += bytes;
4041
153k
}
4042
4043
void CConnman::RecordBytesSent(uint64_t bytes)
4044
151k
{
4045
151k
    AssertLockNotHeld(m_total_bytes_sent_mutex);
4046
151k
    LOCK(m_total_bytes_sent_mutex);
4047
4048
151k
    nTotalBytesSent += bytes;
4049
4050
151k
    const auto now = GetTime<std::chrono::seconds>();
4051
151k
    if (nMaxOutboundCycleStartTime + MAX_UPLOAD_TIMEFRAME < now)
4052
588
    {
4053
        // timeframe expired, reset cycle
4054
588
        nMaxOutboundCycleStartTime = now;
4055
588
        nMaxOutboundTotalBytesSentInCycle = 0;
4056
588
    }
4057
4058
151k
    nMaxOutboundTotalBytesSentInCycle += bytes;
4059
151k
}
4060
4061
uint64_t CConnman::GetMaxOutboundTarget() const
4062
19
{
4063
19
    AssertLockNotHeld(m_total_bytes_sent_mutex);
4064
19
    LOCK(m_total_bytes_sent_mutex);
4065
19
    return nMaxOutboundLimit;
4066
19
}
4067
4068
std::chrono::seconds CConnman::GetMaxOutboundTimeframe() const
4069
19
{
4070
19
    return MAX_UPLOAD_TIMEFRAME;
4071
19
}
4072
4073
std::chrono::seconds CConnman::GetMaxOutboundTimeLeftInCycle() const
4074
19
{
4075
19
    AssertLockNotHeld(m_total_bytes_sent_mutex);
4076
19
    LOCK(m_total_bytes_sent_mutex);
4077
19
    return GetMaxOutboundTimeLeftInCycle_();
4078
19
}
4079
4080
std::chrono::seconds CConnman::GetMaxOutboundTimeLeftInCycle_() const
4081
1.12k
{
4082
1.12k
    AssertLockHeld(m_total_bytes_sent_mutex);
4083
4084
1.12k
    if (nMaxOutboundLimit == 0)
4085
13
        return 0s;
4086
4087
1.11k
    if (nMaxOutboundCycleStartTime.count() == 0)
4088
4
        return MAX_UPLOAD_TIMEFRAME;
4089
4090
1.11k
    const std::chrono::seconds cycleEndTime = nMaxOutboundCycleStartTime + MAX_UPLOAD_TIMEFRAME;
4091
1.11k
    const auto now = GetTime<std::chrono::seconds>();
4092
1.11k
    return (cycleEndTime < now) ? 0s : cycleEndTime - now;
4093
1.11k
}
4094
4095
bool CConnman::OutboundTargetReached(bool historicalBlockServingLimit) const
4096
24.3k
{
4097
24.3k
    AssertLockNotHeld(m_total_bytes_sent_mutex);
4098
24.3k
    LOCK(m_total_bytes_sent_mutex);
4099
24.3k
    if (nMaxOutboundLimit == 0)
4100
23.2k
        return false;
4101
4102
1.11k
    if (historicalBlockServingLimit)
4103
1.10k
    {
4104
        // keep a large enough buffer to at least relay each block once
4105
1.10k
        const std::chrono::seconds timeLeftInCycle = GetMaxOutboundTimeLeftInCycle_();
4106
1.10k
        const uint64_t buffer = timeLeftInCycle / std::chrono::minutes{10} * MAX_BLOCK_SERIALIZED_SIZE;
4107
1.10k
        if (buffer >= nMaxOutboundLimit || nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit - buffer)
4108
827
            return true;
4109
1.10k
    }
4110
8
    else if (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit)
4111
3
        return true;
4112
4113
286
    return false;
4114
1.11k
}
4115
4116
uint64_t CConnman::GetOutboundTargetBytesLeft() const
4117
19
{
4118
19
    AssertLockNotHeld(m_total_bytes_sent_mutex);
4119
19
    LOCK(m_total_bytes_sent_mutex);
4120
19
    if (nMaxOutboundLimit == 0)
4121
13
        return 0;
4122
4123
6
    return (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit) ? 0 : nMaxOutboundLimit - nMaxOutboundTotalBytesSentInCycle;
4124
19
}
4125
4126
uint64_t CConnman::GetTotalBytesRecv() const
4127
19
{
4128
19
    return nTotalBytesRecv;
4129
19
}
4130
4131
uint64_t CConnman::GetTotalBytesSent() const
4132
19
{
4133
19
    AssertLockNotHeld(m_total_bytes_sent_mutex);
4134
19
    LOCK(m_total_bytes_sent_mutex);
4135
19
    return nTotalBytesSent;
4136
19
}
4137
4138
ServiceFlags CConnman::GetLocalServices() const
4139
5.38k
{
4140
5.38k
    return m_local_services;
4141
5.38k
}
4142
4143
static util::NotNullUniquePtr<Transport> MakeTransport(NodeId id, bool use_v2transport, bool inbound) noexcept
4144
1.86k
{
4145
1.86k
    if (use_v2transport) {
4146
211
        return util::NotNull{std::make_unique<V2Transport>(id, /*initiating=*/!inbound)};
4147
1.65k
    } else {
4148
1.65k
        return util::NotNull{std::make_unique<V1Transport>(id)};
4149
1.65k
    }
4150
1.86k
}
4151
4152
CNode::CNode(NodeId idIn,
4153
             std::shared_ptr<Sock> sock,
4154
             const CAddress& addrIn,
4155
             uint64_t nKeyedNetGroupIn,
4156
             uint64_t nLocalHostNonceIn,
4157
             const CService& addrBindIn,
4158
             const std::string& addrNameIn,
4159
             ConnectionType conn_type_in,
4160
             bool inbound_onion,
4161
             uint64_t network_key,
4162
             CNodeOptions&& node_opts)
4163
1.86k
    : m_transport{MakeTransport(idIn, node_opts.use_v2transport, conn_type_in == ConnectionType::INBOUND)},
4164
1.86k
      m_permission_flags{node_opts.permission_flags},
4165
1.86k
      m_sock{sock},
4166
1.86k
      m_connected{NodeClock::now()},
4167
1.86k
      m_proxy_override{std::move(node_opts.proxy_override)},
4168
1.86k
      addr{addrIn},
4169
1.86k
      addrBind{addrBindIn},
4170
1.86k
      m_addr_name{addrNameIn.empty() ? addr.ToStringAddrPort() : addrNameIn},
4171
1.86k
      m_dest(addrNameIn),
4172
1.86k
      m_inbound_onion{inbound_onion},
4173
1.86k
      m_prefer_evict{node_opts.prefer_evict},
4174
1.86k
      nKeyedNetGroup{nKeyedNetGroupIn},
4175
1.86k
      m_network_key{network_key},
4176
1.86k
      m_conn_type{conn_type_in},
4177
1.86k
      id{idIn},
4178
1.86k
      nLocalHostNonce{nLocalHostNonceIn},
4179
1.86k
      m_recv_flood_size{node_opts.recv_flood_size},
4180
1.86k
      m_i2p_sam_session{std::move(node_opts.i2p_sam_session)}
4181
1.86k
{
4182
1.86k
    if (inbound_onion) assert(conn_type_in == ConnectionType::INBOUND);
4183
4184
67.1k
    for (const auto& msg : ALL_NET_MESSAGE_TYPES) {
4185
67.1k
        mapRecvBytesPerMsgType[msg] = 0;
4186
67.1k
    }
4187
1.86k
    mapRecvBytesPerMsgType[NET_MESSAGE_TYPE_OTHER] = 0;
4188
4189
1.86k
    if (fLogIPs) {
4190
9
        LogDebug(BCLog::NET, "Added connection to %s peer=%d\n", m_addr_name, id);
4191
1.85k
    } else {
4192
1.85k
        LogDebug(BCLog::NET, "Added connection peer=%d\n", id);
4193
1.85k
    }
4194
1.86k
}
4195
4196
void CNode::MarkReceivedMsgsForProcessing()
4197
130k
{
4198
130k
    AssertLockNotHeld(m_msg_process_queue_mutex);
4199
4200
130k
    size_t nSizeAdded = 0;
4201
141k
    for (const auto& msg : vRecvMsg) {
4202
        // vRecvMsg contains only completed CNetMessage
4203
        // the single possible partially deserialized message are held by TransportDeserializer
4204
141k
        nSizeAdded += msg.GetMemoryUsage();
4205
141k
    }
4206
4207
130k
    LOCK(m_msg_process_queue_mutex);
4208
130k
    m_msg_process_queue.splice(m_msg_process_queue.end(), vRecvMsg);
4209
130k
    m_msg_process_queue_size += nSizeAdded;
4210
130k
    fPauseRecv = m_msg_process_queue_size > m_recv_flood_size;
4211
130k
}
4212
4213
std::optional<std::pair<CNetMessage, bool>> CNode::PollMessage()
4214
313k
{
4215
313k
    LOCK(m_msg_process_queue_mutex);
4216
313k
    if (m_msg_process_queue.empty()) return std::nullopt;
4217
4218
141k
    std::list<CNetMessage> msgs;
4219
    // Just take one message
4220
141k
    msgs.splice(msgs.begin(), m_msg_process_queue, m_msg_process_queue.begin());
4221
141k
    m_msg_process_queue_size -= msgs.front().GetMemoryUsage();
4222
141k
    fPauseRecv = m_msg_process_queue_size > m_recv_flood_size;
4223
4224
141k
    return std::make_pair(std::move(msgs.front()), !m_msg_process_queue.empty());
4225
313k
}
4226
4227
bool CConnman::NodeFullyConnected(const CNode* pnode)
4228
69.8k
{
4229
69.8k
    return pnode && pnode->fSuccessfullyConnected && !pnode->fDisconnect;
4230
69.8k
}
4231
4232
/// Private broadcast connections only need to send certain message types.
4233
/// Other messages are not needed and may degrade privacy.
4234
static bool IsOutboundMessageAllowedInPrivateBroadcast(std::string_view type) noexcept
4235
101
{
4236
101
    return type == NetMsgType::VERSION ||
4237
101
           type == NetMsgType::VERACK ||
4238
101
           type == NetMsgType::INV ||
4239
101
           type == NetMsgType::TX ||
4240
101
           type == NetMsgType::PING;
4241
101
}
4242
4243
void CConnman::PushMessage(CNode* pnode, CSerializedNetMsg&& msg)
4244
151k
{
4245
151k
    AssertLockNotHeld(m_total_bytes_sent_mutex);
4246
4247
151k
    if (pnode->IsPrivateBroadcastConn() && !IsOutboundMessageAllowedInPrivateBroadcast(msg.m_type)) {
4248
0
        LogDebug(BCLog::PRIVBROADCAST, "Omitting send of message '%s', %s", msg.m_type, pnode->LogPeer());
4249
0
        return;
4250
0
    }
4251
4252
151k
    if (!m_private_broadcast.m_outbound_tor_ok_at_least_once.load() && !pnode->IsInboundConn() &&
4253
151k
        pnode->addr.IsTor() && msg.m_type == NetMsgType::VERACK) {
4254
        // If we are sending the peer VERACK that means we successfully sent
4255
        // and received another message to/from that peer (VERSION).
4256
3
        m_private_broadcast.m_outbound_tor_ok_at_least_once.store(true);
4257
3
    }
4258
4259
151k
    size_t nMessageSize = msg.data.size();
4260
151k
    LogDebug(BCLog::NET, "sending %s (%d bytes) peer=%d\n", msg.m_type, nMessageSize, pnode->GetId());
4261
151k
    if (m_capture_messages) {
4262
20
        CaptureMessage(pnode->addr, msg.m_type, msg.data, /*is_incoming=*/false);
4263
20
    }
4264
4265
151k
    TRACEPOINT(net, outbound_message,
4266
151k
        pnode->GetId(),
4267
151k
        pnode->m_addr_name.c_str(),
4268
151k
        pnode->ConnectionTypeAsString().c_str(),
4269
151k
        msg.m_type.c_str(),
4270
151k
        msg.data.size(),
4271
151k
        msg.data.data()
4272
151k
    );
4273
4274
151k
    size_t nBytesSent = 0;
4275
151k
    {
4276
151k
        LOCK(pnode->cs_vSend);
4277
        // Check if the transport still has unsent bytes, and indicate to it that we're about to
4278
        // give it a message to send.
4279
151k
        const auto& [to_send, more, _msg_type] =
4280
151k
            pnode->m_transport->GetBytesToSend(/*have_next_message=*/true);
4281
151k
        const bool queue_was_empty{to_send.empty() && pnode->vSendMsg.empty()};
4282
4283
        // Update memory usage of send buffer.
4284
151k
        pnode->m_send_memusage += msg.GetMemoryUsage();
4285
151k
        if (pnode->m_send_memusage + pnode->m_transport->GetSendMemoryUsage() > nSendBufferMaxSize && !pnode->fPauseSend) {
4286
1.15k
            pnode->m_pause_send_since = NodeClock::now();
4287
1.15k
            pnode->fPauseSend = true;
4288
1.15k
        }
4289
        // Move message to vSendMsg queue.
4290
151k
        pnode->vSendMsg.push_back(std::move(msg));
4291
4292
        // If there was nothing to send before, and there is now (predicted by the "more" value
4293
        // returned by the GetBytesToSend call above), attempt "optimistic write":
4294
        // because the poll/select loop may pause for SELECT_TIMEOUT_MILLISECONDS before actually
4295
        // doing a send, try sending from the calling thread if the queue was empty before.
4296
        // With a V1Transport, more will always be true here, because adding a message always
4297
        // results in sendable bytes there, but with V2Transport this is not the case (it may
4298
        // still be in the handshake).
4299
151k
        if (queue_was_empty && more) {
4300
151k
            std::tie(nBytesSent, std::ignore) = SocketSendData(*pnode);
4301
151k
        }
4302
151k
    }
4303
151k
    if (nBytesSent) RecordBytesSent(nBytesSent);
4304
151k
}
4305
4306
bool CConnman::ForNode(NodeId id, std::function<bool(CNode* pnode)> func)
4307
426
{
4308
426
    AssertLockNotHeld(m_nodes_mutex);
4309
4310
426
    CNode* found = nullptr;
4311
426
    LOCK(m_nodes_mutex);
4312
693
    for (auto&& pnode : m_nodes) {
4313
693
        if(pnode->GetId() == id) {
4314
387
            found = pnode;
4315
387
            break;
4316
387
        }
4317
693
    }
4318
426
    return found != nullptr && NodeFullyConnected(found) && func(found);
4319
426
}
4320
4321
CSipHasher CConnman::GetDeterministicRandomizer(uint64_t id) const
4322
5.43k
{
4323
5.43k
    return CSipHasher(nSeed0, nSeed1).Write(id);
4324
5.43k
}
4325
4326
uint64_t CConnman::CalculateKeyedNetGroup(const CNetAddr& address) const
4327
1.79k
{
4328
1.79k
    std::vector<unsigned char> vchNetGroup(m_netgroupman.GetGroup(address));
4329
4330
1.79k
    return GetDeterministicRandomizer(RANDOMIZER_ID_NETGROUP).Write(vchNetGroup).Finalize();
4331
1.79k
}
4332
4333
void CConnman::PerformReconnections()
4334
4.70k
{
4335
4.70k
    AssertLockNotHeld(m_nodes_mutex);
4336
4.70k
    AssertLockNotHeld(m_reconnections_mutex);
4337
4.70k
    AssertLockNotHeld(m_unused_i2p_sessions_mutex);
4338
4.70k
    while (true) {
4339
        // Move first element of m_reconnections to todo (avoiding an allocation inside the lock).
4340
4.70k
        decltype(m_reconnections) todo;
4341
4.70k
        {
4342
4.70k
            LOCK(m_reconnections_mutex);
4343
4.70k
            if (m_reconnections.empty()) break;
4344
6
            todo.splice(todo.end(), m_reconnections, m_reconnections.begin());
4345
6
        }
4346
4347
0
        auto& item = *todo.begin();
4348
6
        OpenNetworkConnection(item.addr_connect,
4349
                              // We only reconnect if the first attempt to connect succeeded at
4350
                              // connection time, but then failed after the CNode object was
4351
                              // created. Since we already know connecting is possible, do not
4352
                              // count failure to reconnect.
4353
6
                              /*fCountFailure=*/false,
4354
6
                              std::move(item.grant),
4355
6
                              item.destination.empty() ? nullptr : item.destination.c_str(),
4356
6
                              item.conn_type,
4357
6
                              item.use_v2transport,
4358
6
                              item.proxy_override);
4359
6
    }
4360
4.70k
}
4361
4362
void CConnman::ASMapHealthCheck()
4363
7
{
4364
7
    const std::vector<CAddress> v4_addrs{GetAddressesUnsafe(/*max_addresses=*/0, /*max_pct=*/0, Network::NET_IPV4, /*filtered=*/false)};
4365
7
    const std::vector<CAddress> v6_addrs{GetAddressesUnsafe(/*max_addresses=*/0, /*max_pct=*/0, Network::NET_IPV6, /*filtered=*/false)};
4366
7
    std::vector<CNetAddr> clearnet_addrs;
4367
7
    clearnet_addrs.reserve(v4_addrs.size() + v6_addrs.size());
4368
7
    std::transform(v4_addrs.begin(), v4_addrs.end(), std::back_inserter(clearnet_addrs),
4369
8
        [](const CAddress& addr) { return static_cast<CNetAddr>(addr); });
4370
7
    std::transform(v6_addrs.begin(), v6_addrs.end(), std::back_inserter(clearnet_addrs),
4371
7
        [](const CAddress& addr) { return static_cast<CNetAddr>(addr); });
4372
7
    m_netgroupman.ASMapHealthCheck(clearnet_addrs);
4373
7
}
4374
4375
// Dump binary message to file, with timestamp.
4376
static void CaptureMessageToFile(const CAddress& addr,
4377
                                 const std::string& msg_type,
4378
                                 std::span<const unsigned char> data,
4379
                                 bool is_incoming)
4380
23
{
4381
    // Note: This function captures the message at the time of processing,
4382
    // not at socket receive/send time.
4383
    // This ensures that the messages are always in order from an application
4384
    // layer (processing) perspective.
4385
23
    auto now = GetTime<std::chrono::microseconds>();
4386
4387
    // Windows folder names cannot include a colon
4388
23
    std::string clean_addr = addr.ToStringAddrPort();
4389
23
    std::replace(clean_addr.begin(), clean_addr.end(), ':', '_');
4390
4391
23
    fs::path base_path = gArgs.GetDataDirNet() / "message_capture" / fs::u8path(clean_addr);
4392
23
    fs::create_directories(base_path);
4393
4394
23
    fs::path path = base_path / (is_incoming ? "msgs_recv.dat" : "msgs_sent.dat");
4395
23
    AutoFile f{fsbridge::fopen(path, "ab")};
4396
4397
23
    ser_writedata64(f, now.count());
4398
23
    f << std::span{msg_type};
4399
135
    for (auto i = msg_type.length(); i < CMessageHeader::MESSAGE_TYPE_SIZE; ++i) {
4400
112
        f << uint8_t{'\0'};
4401
112
    }
4402
23
    uint32_t size = data.size();
4403
23
    ser_writedata32(f, size);
4404
23
    f << data;
4405
4406
23
    if (f.fclose() != 0) {
4407
0
        throw std::ios_base::failure(
4408
0
            strprintf("Error closing %s after write, file contents are likely incomplete", fs::PathToString(path)));
4409
0
    }
4410
23
}
4411
4412
std::function<void(const CAddress& addr,
4413
                   const std::string& msg_type,
4414
                   std::span<const unsigned char> data,
4415
                   bool is_incoming)>
4416
    CaptureMessage = CaptureMessageToFile;