Branch data Line data Source code
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 : 591651 : size_t CSerializedNetMsg::GetMemoryUsage() const noexcept
139 : : {
140 [ - + ]: 591651 : return sizeof(*this) + memusage::DynamicUsage(m_type) + memusage::DynamicUsage(data);
141 : : }
142 : :
143 : 293284 : size_t CNetMessage::GetMemoryUsage() const noexcept
144 : : {
145 : 293284 : return sizeof(*this) + memusage::DynamicUsage(m_type) + m_recv.GetMemoryUsage();
146 : : }
147 : :
148 : 15 : void CConnman::AddAddrFetch(const std::string& strDest)
149 : : {
150 : 15 : LOCK(m_addr_fetches_mutex);
151 [ + - ]: 15 : m_addr_fetches.push_back(strDest);
152 : 15 : }
153 : :
154 : 1851 : uint16_t GetListenPort()
155 : : {
156 : : // If -bind= is provided with ":port" part, use that (first one if multiple are provided).
157 [ + - + + ]: 3716 : for (const std::string& bind_arg : gArgs.GetArgs("-bind")) {
158 : 1878 : constexpr uint16_t dummy_port = 0;
159 : :
160 [ + - + - ]: 1878 : const std::optional<CService> bind_addr{Lookup(bind_arg, dummy_port, /*fAllowLookup=*/false)};
161 [ + + + - : 1878 : if (bind_addr.has_value() && bind_addr->GetPort() != dummy_port) return bind_addr->GetPort();
+ + + - ]
162 : 3716 : }
163 : :
164 : : // Otherwise, if -whitebind= without NetPermissionFlags::NoBan is provided, use that
165 : : // (-whitebind= is required to have ":port").
166 [ + - + + ]: 1838 : for (const std::string& whitebind_arg : gArgs.GetArgs("-whitebind")) {
167 [ + - ]: 3 : NetWhitebindPermissions whitebind;
168 [ + - ]: 3 : bilingual_str error;
169 [ + - + - ]: 3 : if (NetWhitebindPermissions::TryParse(whitebind_arg, whitebind, error)) {
170 [ + - ]: 3 : if (!NetPermissions::HasFlag(whitebind.m_flags, NetPermissionFlags::NoBan)) {
171 [ + - ]: 3 : return whitebind.m_service.GetPort();
172 : : }
173 : : }
174 : 3 : }
175 : :
176 : : // Otherwise, if -port= is provided, use that. Otherwise use the default port.
177 : 3670 : return static_cast<uint16_t>(gArgs.GetIntArg("-port", Params().GetDefaultPort()));
178 : : }
179 : :
180 : : // Determine the "best" local address for a particular peer.
181 : 1819 : [[nodiscard]] static std::optional<CService> GetLocal(const CNode& peer)
182 : : {
183 [ - + ]: 1819 : if (!fListen) return std::nullopt;
184 : :
185 : 1819 : std::optional<CService> addr;
186 : 1819 : int nBestScore = -1;
187 : 1819 : int nBestReachability = -1;
188 : 1819 : {
189 [ + - ]: 1819 : LOCK(g_maplocalhost_mutex);
190 [ + - + + ]: 1914 : 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 [ + + + - : 152 : && (local_addr.IsPrivacyNet() || peer.IsConnectedThroughPrivacyNet())) {
+ + ]
196 : 36 : continue;
197 : : }
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 : : }
205 : : }
206 : 0 : }
207 [ + + ]: 1858 : return addr;
208 : 1819 : }
209 : :
210 : : //! Convert the serialized seeds into usable address objects.
211 : 3 : static std::vector<CAddress> ConvertSeeds(const std::vector<uint8_t> &vSeedsIn)
212 : : {
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 : 1819 : CService GetLocalAddress(const CNode& peer)
237 : : {
238 [ + - + - : 1819 : return GetLocal(peer).value_or(CService{CNetAddr(), GetListenPort()});
+ - ]
239 : : }
240 : :
241 : 0 : static int GetnScore(const CService& addr)
242 : : {
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 : 1798 : [[nodiscard]] static bool IsPeerAddrLocalGood(CNode *pnode)
250 : : {
251 : 1798 : 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 [ + - + + : 12 : return fDiscover && !pnode->IsConnectedThroughPrivacyNet() &&
+ - ]
254 [ + + + - : 1812 : pnode->addr.IsRoutable() && addrLocal.IsRoutable() &&
+ - + + -
+ ]
255 [ + - ]: 1802 : g_reachable_nets.Contains(addrLocal);
256 : 1798 : }
257 : :
258 : 1798 : std::optional<CService> GetLocalAddrForPeer(CNode& node)
259 : : {
260 : 1798 : 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 : 1798 : FastRandomContext rng;
265 [ + - + + : 1798 : if (IsPeerAddrLocalGood(&node) && (!addrLocal.IsRoutable() ||
+ - - + -
- ]
266 [ # # # # ]: 0 : rng.randbits((GetnScore(addrLocal) > LOCAL_MANUAL) ? 3 : 1) == 0))
267 : : {
268 [ + + ]: 4 : if (node.IsInboundConn()) {
269 : : // For inbound connections, assume both the address and the port
270 : : // as seen from the peer.
271 [ + - ]: 2 : addrLocal = CService{node.GetAddrLocal()};
272 : : } 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 [ + - + - ]: 6 : addrLocal.SetIP(node.GetAddrLocal());
278 : : }
279 : : }
280 [ + - + + ]: 1798 : if (addrLocal.IsRoutable()) {
281 [ + - + - : 28 : LogDebug(BCLog::NET, "Advertising address %s to peer=%d\n", addrLocal.ToStringAddrPort(), node.GetId());
+ - + - ]
282 : 28 : return addrLocal;
283 : : }
284 : : // Address is unroutable. Don't advertise.
285 : 1770 : return std::nullopt;
286 : 1798 : }
287 : :
288 : 795 : void ClearLocal()
289 : : {
290 : 795 : LOCK(g_maplocalhost_mutex);
291 [ + - ]: 795 : return mapLocalHost.clear();
292 : 795 : }
293 : :
294 : : // learn a new local address
295 : 41 : bool AddLocal(const CService& addr_, int nScore, bool add_even_if_unreachable)
296 : : {
297 : 41 : CService addr{MaybeFlipIPv6toCJDNS(addr_)};
298 : :
299 [ + - + + ]: 41 : if (!addr.IsRoutable())
300 : : return false;
301 : :
302 [ + + + + ]: 35 : if (!fDiscover && nScore < LOCAL_MANUAL)
303 : : return false;
304 : :
305 [ + - + + : 34 : if (!g_reachable_nets.Contains(addr) && !add_even_if_unreachable)
+ + ]
306 : : return false;
307 : :
308 [ - + ]: 33 : if (fLogIPs) {
309 [ # # # # ]: 0 : LogInfo("AddLocal(%s,%i)\n", addr.ToStringAddrPort(), nScore);
310 : : }
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 : : }
320 : 0 : }
321 : :
322 : 33 : return true;
323 : 41 : }
324 : :
325 : 7 : bool AddLocal(const CNetAddr& addr, int nScore, bool add_even_if_unreachable)
326 : : {
327 [ + - ]: 7 : return AddLocal(CService(addr, GetListenPort()), nScore, add_even_if_unreachable);
328 : : }
329 : :
330 : 18 : void RemoveLocal(const CService& addr)
331 : : {
332 : 18 : LOCK(g_maplocalhost_mutex);
333 [ - + ]: 18 : if (fLogIPs) {
334 [ # # # # ]: 0 : LogInfo("RemoveLocal(%s)\n", addr.ToStringAddrPort());
335 : : }
336 : :
337 [ + - + - ]: 18 : mapLocalHost.erase(addr);
338 : 18 : }
339 : :
340 : : /** vote for a local address */
341 : 2 : bool SeenLocal(const CService& addr)
342 : : {
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 : 176 : bool IsLocal(const CService& addr)
353 : : {
354 : 176 : LOCK(g_maplocalhost_mutex);
355 [ + - + - ]: 176 : return mapLocalHost.contains(addr);
356 : 176 : }
357 : :
358 : 684 : bool CConnman::AlreadyConnectedToHost(std::string_view host) const
359 : : {
360 : 684 : LOCK(m_nodes_mutex);
361 [ + - - + ]: 1470 : return std::ranges::any_of(m_nodes, [&host](CNode* node) { return node->m_addr_name == host; });
362 : 684 : }
363 : :
364 : 730 : bool CConnman::AlreadyConnectedToAddressPort(const CService& addr_port) const
365 : : {
366 : 730 : LOCK(m_nodes_mutex);
367 [ + - + - ]: 1778 : return std::ranges::any_of(m_nodes, [&addr_port](CNode* node) { return node->addr == addr_port; });
368 : 730 : }
369 : :
370 : 65 : bool CConnman::AlreadyConnectedToAddress(const CNetAddr& addr) const
371 : : {
372 : 65 : LOCK(m_nodes_mutex);
373 [ + - + - ]: 372 : return std::ranges::any_of(m_nodes, [&addr](CNode* node) { return node->addr == addr; });
374 : 65 : }
375 : :
376 : 1145 : bool CConnman::CheckIncomingNonce(uint64_t nonce)
377 : : {
378 : 1145 : LOCK(m_nodes_mutex);
379 [ + + ]: 6480 : 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 [ + + + + : 5337 : if (!pnode->fSuccessfullyConnected && !pnode->IsInboundConn() && !pnode->IsPrivateBroadcastConn() &&
+ - ]
389 [ - + ]: 2 : pnode->GetLocalNonce() == nonce)
390 : : return false;
391 : : }
392 : : return true;
393 : 1145 : }
394 : :
395 : 748 : 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 : : {
402 : 748 : AssertLockNotHeld(m_nodes_mutex);
403 : 748 : AssertLockNotHeld(m_unused_i2p_sessions_mutex);
404 [ - + ]: 748 : assert(conn_type != ConnectionType::INBOUND);
405 : :
406 [ + + ]: 748 : if (pszDest == nullptr) {
407 [ + - ]: 54 : if (IsLocal(addrConnect))
408 : : return nullptr;
409 : :
410 : : // Look for an existing connection
411 [ - + ]: 54 : if (AlreadyConnectedToAddressPort(addrConnect)) {
412 [ # # ]: 0 : LogInfo("Failed to open new connection to %s, already connected", addrConnect.ToStringAddrPort());
413 : 0 : return nullptr;
414 : : }
415 : : }
416 : :
417 [ + - + + : 1386 : LogDebug(BCLog::NET, "trying %s connection (%s) to %s, lastseen=%.1fhrs\n",
+ + + - +
+ + - ]
418 : : use_v2transport ? "v2" : "v1",
419 : : ConnectionTypeAsString(conn_type),
420 : : pszDest ? pszDest : addrConnect.ToStringAddrPort(),
421 : : Ticks<HoursDouble>(pszDest ? 0h : Now<NodeSeconds>() - addrConnect.nTime));
422 : :
423 : : // Resolve
424 [ + + + - ]: 1442 : const uint16_t default_port{pszDest != nullptr ? GetDefaultPort(pszDest) :
425 : 54 : 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 : 748 : std::vector<CAddress> connect_to{};
429 [ + + ]: 748 : if (pszDest) {
430 [ + - + + : 1466 : std::vector<CService> resolved{Lookup(pszDest, default_port, fNameLookup && !HaveNameProxy(), 256)};
+ - + + +
- + - ]
431 [ + + ]: 694 : if (!resolved.empty()) {
432 : 678 : 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 [ + + ]: 1344 : for (const auto& r : resolved) {
436 [ + - ]: 1356 : addrConnect = CAddress{MaybeFlipIPv6toCJDNS(r), NODE_NONE};
437 [ + - + + ]: 678 : if (!addrConnect.IsValid()) {
438 [ + - + - : 2 : LogDebug(BCLog::NET, "Resolver returned invalid address %s for %s\n", addrConnect.ToStringAddrPort(), pszDest);
+ - + - ]
439 : 2 : return nullptr;
440 : : }
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 [ + - + + ]: 676 : 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 : : }
447 : : // Add the address to the resolved addresses vector so we can try to connect to it later on
448 [ + - ]: 666 : connect_to.push_back(addrConnect);
449 : : }
450 : : } else {
451 : : // For resolution via proxy
452 [ + - ]: 16 : connect_to.push_back(addrConnect);
453 : : }
454 : 694 : } else {
455 : : // Connect via addrConnect directly
456 [ + - ]: 54 : connect_to.push_back(addrConnect);
457 : : }
458 : :
459 : : // Connect
460 : 736 : std::unique_ptr<Sock> sock;
461 [ + - ]: 736 : CService addr_bind;
462 [ + - - + ]: 736 : assert(!addr_bind.IsValid());
463 : 736 : std::unique_ptr<i2p::sam::Session> i2p_transient_session;
464 : :
465 [ + + ]: 762 : for (auto& target_addr : connect_to) {
466 [ + - + + ]: 736 : if (target_addr.IsValid()) {
467 [ + + ]: 720 : const std::optional<Proxy> use_proxy{
468 [ + + ]: 720 : proxy_override.has_value() ? proxy_override : GetProxy(target_addr.GetNetwork()),
469 [ + - + - ]: 710 : };
470 : 720 : bool proxyConnectionFailed = false;
471 : :
472 [ + + - + ]: 720 : if (target_addr.IsI2P() && use_proxy) {
473 [ + - ]: 7 : i2p::Connection conn;
474 : 7 : 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 [ + + + + ]: 7 : if (m_i2p_sam_session && conn_type != ConnectionType::PRIVATE_BROADCAST) {
480 [ + - ]: 3 : connected = m_i2p_sam_session->Connect(target_addr, conn, proxyConnectionFailed);
481 : : } else {
482 : 4 : {
483 [ + - ]: 4 : LOCK(m_unused_i2p_sessions_mutex);
484 [ + + ]: 4 : if (m_unused_i2p_sessions.empty()) {
485 : 2 : i2p_transient_session =
486 [ + - ]: 4 : std::make_unique<i2p::sam::Session>(*use_proxy, m_interrupt_net);
487 : : } else {
488 : 2 : i2p_transient_session.swap(m_unused_i2p_sessions.front());
489 : 2 : m_unused_i2p_sessions.pop();
490 : : }
491 : 0 : }
492 [ + - ]: 4 : connected = i2p_transient_session->Connect(target_addr, conn, proxyConnectionFailed);
493 [ + - ]: 4 : if (!connected) {
494 [ + - ]: 4 : LOCK(m_unused_i2p_sessions_mutex);
495 [ - + + - ]: 4 : if (m_unused_i2p_sessions.size() < MAX_UNUSED_I2P_SESSIONS_SIZE) {
496 [ + - + - ]: 4 : m_unused_i2p_sessions.emplace(i2p_transient_session.release());
497 : : }
498 : 4 : }
499 : : }
500 : :
501 [ - + ]: 7 : if (connected) {
502 : 0 : sock = std::move(conn.sock);
503 : 0 : addr_bind = conn.me;
504 : : }
505 [ + + ]: 720 : } else if (use_proxy) {
506 [ + - + - : 95 : LogDebug(BCLog::PROXY, "Using proxy: %s to connect to %s\n", use_proxy->ToString(), target_addr.ToStringAddrPort());
+ - + - +
- ]
507 [ + - + - : 190 : sock = ConnectThroughProxy(*use_proxy, target_addr.ToStringAddr(), target_addr.GetPort(), proxyConnectionFailed);
+ - ]
508 : : } 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 [ + - ]: 618 : if (Assume(conn_type != ConnectionType::PRIVATE_BROADCAST)) {
512 [ + - ]: 1236 : sock = ConnectDirectly(target_addr, conn_type == ConnectionType::MANUAL);
513 : : }
514 : : }
515 [ + + ]: 720 : 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 [ + - ]: 707 : addrman.get().Attempt(target_addr, fCountFailure);
519 : : }
520 [ + - ]: 736 : } 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 [ + - ]: 28 : sock = ConnectThroughProxy(*name_proxy, host, port, proxyConnectionFailed);
527 : 30 : }
528 : : }
529 : : // Check any other resolved address (if any) if we fail to connect
530 [ + + ]: 736 : if (!sock) {
531 : 26 : continue;
532 : : }
533 : :
534 : 710 : NetPermissionFlags permission_flags = NetPermissionFlags::None;
535 [ + + + - ]: 710 : std::vector<NetWhitelistPermissions> whitelist_permissions = conn_type == ConnectionType::MANUAL ? vWhitelistedRangeOutgoing : std::vector<NetWhitelistPermissions>{};
536 [ + - ]: 710 : AddWhitelistPermissionFlags(permission_flags, target_addr, whitelist_permissions);
537 : :
538 : : // Add node
539 [ + - ]: 710 : NodeId id = GetNewNodeId();
540 [ + - + - : 710 : uint64_t nonce = GetDeterministicRandomizer(RANDOMIZER_ID_LOCALHOSTNONCE).Write(id).Finalize();
+ - ]
541 [ + - + - ]: 710 : if (!addr_bind.IsValid()) {
542 [ + - ]: 1420 : addr_bind = GetBindAddress(*sock);
543 : : }
544 [ + - ]: 710 : uint64_t network_id = GetDeterministicRandomizer(RANDOMIZER_ID_NETWORKKEY)
545 [ + - + - ]: 710 : .Write(target_addr.GetNetClass())
546 [ + - + - ]: 1420 : .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 [ + - ]: 710 : .Write(0)
550 [ + - ]: 710 : .Finalize();
551 : 710 : CNode* pnode = new CNode(id,
552 : 710 : std::move(sock),
553 : : target_addr,
554 : : CalculateKeyedNetGroup(target_addr),
555 : : nonce,
556 : : addr_bind,
557 [ + - ]: 710 : pszDest ? pszDest : "",
558 : : conn_type,
559 : : /*inbound_onion=*/false,
560 : : network_id,
561 [ + - + + ]: 1420 : CNodeOptions{
562 : : .permission_flags = permission_flags,
563 : : .proxy_override = proxy_override,
564 : : .i2p_sam_session = std::move(i2p_transient_session),
565 [ + + ]: 710 : .recv_flood_size = nReceiveFloodSize,
566 : : .use_v2transport = use_v2transport,
567 [ + - + - : 1420 : });
+ - + - +
- ]
568 : 710 : pnode->AddRef();
569 : :
570 : : // We're making a new connection, harvest entropy from the time (and our peer count)
571 : 710 : RandAddEvent((uint32_t)id);
572 : :
573 : 710 : return pnode;
574 : 710 : }
575 : :
576 : : return nullptr;
577 : 748 : }
578 : :
579 : 2574 : void CNode::CloseSocketDisconnect()
580 : : {
581 : 2574 : fDisconnect = true;
582 : 2574 : LOCK(m_sock_mutex);
583 [ + + ]: 2574 : if (m_sock) {
584 [ + - + - : 1872 : LogDebug(BCLog::NET, "Resetting socket for %s", LogPeer());
+ - + - ]
585 : 1872 : m_sock.reset();
586 : :
587 : : TRACEPOINT(net, closed_connection,
588 : : GetId(),
589 : : m_addr_name.c_str(),
590 : : ConnectionTypeAsString().c_str(),
591 : : ConnectedThroughNetwork(),
592 : 1872 : TicksSinceEpoch<std::chrono::seconds>(m_connected));
593 : : }
594 [ - + + - ]: 2574 : m_i2p_sam_session.reset();
595 : 2574 : }
596 : :
597 : 1876 : void CConnman::AddWhitelistPermissionFlags(NetPermissionFlags& flags, std::optional<CNetAddr> addr, const std::vector<NetWhitelistPermissions>& ranges) const {
598 [ + + ]: 2274 : for (const auto& subnet : ranges) {
599 [ + - + - ]: 398 : if (addr.has_value() && subnet.m_subnet.Match(addr.value())) {
600 : 398 : NetPermissions::AddFlag(flags, subnet.m_flags);
601 : : }
602 : : }
603 [ + + ]: 1876 : 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 : : }
610 : 1876 : }
611 : :
612 : 20670 : CService CNode::GetAddrLocal() const
613 : : {
614 : 20670 : AssertLockNotHeld(m_addr_local_mutex);
615 : 20670 : LOCK(m_addr_local_mutex);
616 [ + - ]: 20670 : return m_addr_local;
617 : 20670 : }
618 : :
619 : 1793 : void CNode::SetAddrLocal(const CService& addrLocalIn) {
620 : 1793 : AssertLockNotHeld(m_addr_local_mutex);
621 : 1793 : LOCK(m_addr_local_mutex);
622 [ + - + - ]: 1793 : if (Assume(!m_addr_local.IsValid())) { // Addr local can only be set once during version msg processing
623 : 1793 : m_addr_local = addrLocalIn;
624 : : }
625 : 1793 : }
626 : :
627 : 18996 : Network CNode::ConnectedThroughNetwork() const
628 : : {
629 [ + + ]: 18996 : return m_inbound_onion ? NET_ONION : addr.GetNetClass();
630 : : }
631 : :
632 : 64 : bool CNode::IsConnectedThroughPrivacyNet() const
633 : : {
634 [ + - + + ]: 64 : return m_inbound_onion || addr.IsPrivacyNet();
635 : : }
636 : :
637 : : #undef X
638 : : #define X(name) stats.name = name
639 : 18868 : void CNode::CopyStats(CNodeStats& stats)
640 : : {
641 : 18868 : stats.nodeid = this->GetId();
642 : 18868 : X(addr);
643 : 18868 : X(addrBind);
644 : 18868 : stats.m_network = ConnectedThroughNetwork();
645 : 18868 : X(m_last_send);
646 : 18868 : X(m_last_recv);
647 : 18868 : X(m_last_tx_time);
648 : 18868 : X(m_last_block_time);
649 : 18868 : X(m_connected);
650 : 18868 : X(m_addr_name);
651 : 18868 : X(nVersion);
652 : 18868 : {
653 : 18868 : LOCK(m_subver_mutex);
654 [ + - + - ]: 37736 : X(cleanSubVer);
655 : 0 : }
656 : 18868 : stats.fInbound = IsInboundConn();
657 : 18868 : X(m_bip152_highbandwidth_to);
658 : 18868 : X(m_bip152_highbandwidth_from);
659 : 18868 : {
660 : 18868 : LOCK(cs_vSend);
661 [ + - ]: 18868 : X(mapSendBytesPerMsgType);
662 [ + - ]: 18868 : X(nSendBytes);
663 : 0 : }
664 : 18868 : {
665 : 18868 : LOCK(cs_vRecv);
666 [ + - ]: 18868 : X(mapRecvBytesPerMsgType);
667 : 18868 : X(nRecvBytes);
668 : 18868 : Transport::Info info = m_transport->GetInfo();
669 : 18868 : stats.m_transport_type = info.transport_type;
670 [ + + + - ]: 18868 : if (info.session_id) stats.m_session_id = HexStr(*info.session_id);
671 : 0 : }
672 : 18868 : X(m_permission_flags);
673 : :
674 : 18868 : X(m_last_ping_time);
675 : 18868 : X(m_min_ping_time);
676 : :
677 : : // Leave string empty if addrLocal invalid (not filled in yet)
678 : 18868 : CService addrLocalUnlocked = GetAddrLocal();
679 [ + - + + : 18868 : stats.addrLocal = addrLocalUnlocked.IsValid() ? addrLocalUnlocked.ToStringAddrPort() : "";
+ - + - ]
680 : :
681 : 18868 : X(m_conn_type);
682 : 18868 : }
683 : : #undef X
684 : :
685 : 218221 : bool CNode::ReceiveMsgBytes(std::span<const uint8_t> msg_bytes, bool& complete)
686 : : {
687 : 218221 : complete = false;
688 : 218221 : const auto time{NodeClock::now()};
689 : 218221 : LOCK(cs_vRecv);
690 : 218221 : m_last_recv = time;
691 : 218221 : nRecvBytes += msg_bytes.size();
692 [ + + ]: 823974 : while (msg_bytes.size() > 0) {
693 : : // absorb network data
694 [ + - + + ]: 387542 : if (!m_transport->ReceivedBytes(msg_bytes)) {
695 : : // Serious transport problem, disconnect from the peer.
696 : : return false;
697 : : }
698 : :
699 [ + - + + ]: 387532 : if (m_transport->ReceivedMessageComplete()) {
700 : : // decompose a transport agnostic CNetMessage from the deserializer
701 : 146807 : bool reject_message{false};
702 [ + - ]: 146807 : CNetMessage msg = m_transport->GetReceivedMessage(time, reject_message);
703 [ + + ]: 146807 : 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 : : }
709 : :
710 : : // Store received bytes per message type.
711 : : // To prevent a memory DOS, only allow known message types.
712 : 146725 : auto i = mapRecvBytesPerMsgType.find(msg.m_type);
713 [ + + ]: 146725 : if (i == mapRecvBytesPerMsgType.end()) {
714 : 6 : i = mapRecvBytesPerMsgType.find(NET_MESSAGE_TYPE_OTHER);
715 : : }
716 [ - + ]: 146725 : assert(i != mapRecvBytesPerMsgType.end());
717 [ + - ]: 146725 : i->second += msg.m_raw_message_size;
718 : :
719 : : // push the message to the process queue,
720 [ + - ]: 146725 : vRecvMsg.push_back(std::move(msg));
721 : :
722 : 146725 : complete = true;
723 : 146807 : }
724 : : }
725 : :
726 : : return true;
727 : 218221 : }
728 : :
729 : 33846 : std::string CNode::LogPeer() const
730 : : {
731 : 33846 : auto peer_info{strprintf("peer=%d", GetId())};
732 [ + + ]: 33846 : if (fLogIPs) {
733 [ + - + - ]: 42 : return strprintf("%s, peeraddr=%s", peer_info, addr.ToStringAddrPort());
734 : : } else {
735 : 33825 : return peer_info;
736 : : }
737 : 33846 : }
738 : :
739 : 1757 : std::string CNode::DisconnectMsg() const
740 : : {
741 [ + - ]: 3514 : return strprintf("disconnecting %s", LogPeer());
742 : : }
743 : :
744 : 1997 : V1Transport::V1Transport(const NodeId node_id) noexcept
745 : 1997 : : m_magic_bytes{Params().MessageStart()}, m_node_id{node_id}
746 : : {
747 : 1997 : LOCK(m_recv_mutex);
748 [ + - ]: 1997 : Reset();
749 : 1997 : }
750 : :
751 : 18477 : Transport::Info V1Transport::GetInfo() const noexcept
752 : : {
753 : 18477 : return {.transport_type = TransportProtocolType::V1, .session_id = {}};
754 : : }
755 : :
756 : 138217 : int V1Transport::readHeader(std::span<const uint8_t> msg_bytes)
757 : : {
758 : 138217 : AssertLockHeld(m_recv_mutex);
759 : : // copy data to temporary parsing buffer
760 : 138217 : unsigned int nRemaining = CMessageHeader::HEADER_SIZE - nHdrPos;
761 [ + + ]: 138217 : unsigned int nCopy = std::min<unsigned int>(nRemaining, msg_bytes.size());
762 : :
763 [ + + ]: 138217 : memcpy(&hdrbuf[nHdrPos], msg_bytes.data(), nCopy);
764 : 138217 : nHdrPos += nCopy;
765 : :
766 : : // if header incomplete, exit
767 [ + + ]: 138217 : if (nHdrPos < CMessageHeader::HEADER_SIZE)
768 : 10 : return nCopy;
769 : :
770 : : // deserialize to CMessageHeader
771 : 138207 : try {
772 [ + - ]: 138207 : hdrbuf >> hdr;
773 : : }
774 [ - - ]: 0 : 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 [ + + ]: 138207 : 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 : : }
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 [ + + ]: 138205 : 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 : : }
792 : :
793 : : // switch state to reading message data
794 : 138202 : in_data = true;
795 : :
796 : 138202 : return nCopy;
797 : : }
798 : :
799 : 240082 : int V1Transport::readData(std::span<const uint8_t> msg_bytes)
800 : : {
801 : 240082 : AssertLockHeld(m_recv_mutex);
802 : 240082 : unsigned int nRemaining = hdr.nMessageSize - nDataPos;
803 [ + + ]: 240082 : unsigned int nCopy = std::min<unsigned int>(nRemaining, msg_bytes.size());
804 : :
805 [ - + + + ]: 240082 : if (vRecv.size() < nDataPos + nCopy) {
806 : : // Allocate up to 256 KiB ahead, but never more than the total message size.
807 [ + + ]: 282317 : vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024));
808 : : }
809 : :
810 : 240082 : hasher.Write(msg_bytes.first(nCopy));
811 : 240082 : memcpy(&vRecv[nDataPos], msg_bytes.data(), nCopy);
812 : 240082 : nDataPos += nCopy;
813 : :
814 : 240082 : return nCopy;
815 : : }
816 : :
817 : 138201 : const uint256& V1Transport::GetMessageHash() const
818 : : {
819 : 138201 : AssertLockHeld(m_recv_mutex);
820 [ + - - + ]: 138201 : assert(CompleteInternal());
821 [ + - ]: 276402 : if (data_hash.IsNull())
822 : 138201 : hasher.Finalize(data_hash);
823 : 138201 : return data_hash;
824 : : }
825 : :
826 : 138201 : CNetMessage V1Transport::GetReceivedMessage(NodeClock::time_point time, bool& reject_message)
827 : : {
828 : 138201 : AssertLockNotHeld(m_recv_mutex);
829 : : // Initialize out parameter
830 : 138201 : reject_message = false;
831 : : // decompose a single CNetMessage from the TransportDeserializer
832 : 138201 : LOCK(m_recv_mutex);
833 [ + - ]: 138201 : CNetMessage msg(std::move(vRecv));
834 : :
835 : : // store message type string, time, and sizes
836 [ + - ]: 138201 : msg.m_type = hdr.GetMessageType();
837 : 138201 : msg.m_time = time;
838 : 138201 : msg.m_message_size = hdr.nMessageSize;
839 : 138201 : msg.m_raw_message_size = hdr.nMessageSize + CMessageHeader::HEADER_SIZE;
840 : :
841 [ + - ]: 138201 : uint256 hash = GetMessageHash();
842 : :
843 : : // We just received a message off the wire, harvest entropy from the time (and the message checksum)
844 : 138201 : RandAddEvent(ReadLE32(hash.begin()));
845 : :
846 : : // Check checksum and header message type string
847 [ + + ]: 138201 : 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 : : SanitizeString(msg.m_type), msg.m_message_size,
850 : : HexStr(std::span{hash}.first(CMessageHeader::CHECKSUM_SIZE)),
851 : : HexStr(hdr.pchChecksum),
852 : : m_node_id);
853 : 1 : reject_message = true;
854 [ + - + + ]: 138200 : } else if (!hdr.IsMessageTypeValid()) {
855 [ + - + - : 162 : LogDebug(BCLog::NET, "Header error: Invalid message type (%s, %u bytes), peer=%d\n",
+ - + - +
- ]
856 : : SanitizeString(hdr.GetMessageType()), msg.m_message_size, m_node_id);
857 : 81 : reject_message = true;
858 : : }
859 : :
860 : : // Always reset the network deserializer (prepare for the next message)
861 [ + - ]: 138201 : Reset();
862 [ + - ]: 138201 : return msg;
863 : 138201 : }
864 : :
865 : 143688 : bool V1Transport::SetMessageToSend(CSerializedNetMsg& msg) noexcept
866 : : {
867 : 143688 : AssertLockNotHeld(m_send_mutex);
868 : : // Determine whether a new message can be set.
869 : 143688 : LOCK(m_send_mutex);
870 [ + - - + : 143688 : if (m_sending_header || m_bytes_sent < m_message_to_send.data.size()) return false;
+ + ]
871 : :
872 : : // create dbl-sha256 checksum
873 : 143086 : uint256 hash = Hash(msg.data);
874 : :
875 : : // create header
876 [ - + ]: 143086 : CMessageHeader hdr(m_magic_bytes, msg.m_type.c_str(), msg.data.size());
877 [ + + ]: 143086 : memcpy(hdr.pchChecksum, hash.begin(), CMessageHeader::CHECKSUM_SIZE);
878 : :
879 : : // serialize header
880 [ + + ]: 143086 : m_header_to_send.clear();
881 : 143086 : VectorWriter{m_header_to_send, 0, hdr};
882 : :
883 : : // update state
884 : 143086 : m_message_to_send = std::move(msg);
885 : 143086 : m_sending_header = true;
886 : 143086 : m_bytes_sent = 0;
887 : 143086 : return true;
888 : 143688 : }
889 : :
890 : 1119718 : Transport::BytesToSend V1Transport::GetBytesToSend(bool have_next_message) const noexcept
891 : : {
892 : 1119718 : AssertLockNotHeld(m_send_mutex);
893 : 1119718 : LOCK(m_send_mutex);
894 [ + + ]: 1119718 : if (m_sending_header) {
895 [ - + + + ]: 143133 : 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 [ + + + + ]: 143133 : have_next_message || !m_message_to_send.data.empty(),
899 : 143133 : m_message_to_send.m_type
900 : 143133 : };
901 : : } else {
902 [ - + ]: 976585 : 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 : : have_next_message,
906 : 976585 : m_message_to_send.m_type
907 : 976585 : };
908 : : }
909 : 1119718 : }
910 : :
911 : 280697 : void V1Transport::MarkBytesSent(size_t bytes_sent) noexcept
912 : : {
913 : 280697 : AssertLockNotHeld(m_send_mutex);
914 : 280697 : LOCK(m_send_mutex);
915 : 280697 : m_bytes_sent += bytes_sent;
916 [ + + - + : 280697 : 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 : 143081 : m_sending_header = false;
919 : 143081 : m_bytes_sent = 0;
920 [ + - - + : 137616 : } 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 : 136997 : ClearShrink(m_message_to_send.data);
923 : 136997 : m_bytes_sent = 0;
924 : : }
925 : 280697 : }
926 : :
927 : 286177 : size_t V1Transport::GetSendMemoryUsage() const noexcept
928 : : {
929 : 286177 : AssertLockNotHeld(m_send_mutex);
930 : 286177 : LOCK(m_send_mutex);
931 : : // Don't count sending-side fields besides m_message_to_send, as they're all small and bounded.
932 [ + - ]: 286177 : return m_message_to_send.GetMemoryUsage();
933 : 286177 : }
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 : 1509 : V2MessageMap() noexcept
984 : 1509 : {
985 [ + + ]: 57342 : for (size_t i = 1; i < std::size(V2_MESSAGE_IDS); ++i) {
986 : 55833 : m_map.emplace(V2_MESSAGE_IDS[i], i);
987 : : }
988 : 1509 : }
989 : :
990 : 9361 : std::optional<uint8_t> operator()(const std::string& message_name) const noexcept
991 : : {
992 : 9361 : auto it = m_map.find(message_name);
993 [ + + ]: 9361 : if (it == m_map.end()) return std::nullopt;
994 : 8434 : return it->second;
995 : : }
996 : : };
997 : :
998 : : const V2MessageMap V2_MESSAGE_MAP;
999 : :
1000 : 288 : std::vector<uint8_t> GenerateRandomGarbage() noexcept
1001 : : {
1002 : 288 : std::vector<uint8_t> ret;
1003 : 288 : FastRandomContext rng;
1004 : 288 : ret.resize(rng.randrange(V2Transport::MAX_GARBAGE_LEN + 1));
1005 : 288 : rng.fillrand(MakeWritableByteSpan(ret));
1006 : 288 : return ret;
1007 : 288 : }
1008 : :
1009 : : } // namespace
1010 : :
1011 : 282 : void V2Transport::StartSendingHandshake() noexcept
1012 : : {
1013 : 282 : AssertLockHeld(m_send_mutex);
1014 [ - + ]: 282 : Assume(m_send_state == SendState::AWAITING_KEY);
1015 : 282 : Assume(m_send_buffer.empty());
1016 : : // Initialize the send buffer with ellswift pubkey + provided garbage.
1017 [ - + ]: 282 : m_send_buffer.resize(EllSwiftPubKey::size() + m_send_garbage.size());
1018 : 282 : std::copy(std::begin(m_cipher.GetOurPubKey()), std::end(m_cipher.GetOurPubKey()), MakeWritableByteSpan(m_send_buffer).begin());
1019 : 282 : 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 : 282 : }
1022 : :
1023 : 288 : V2Transport::V2Transport(NodeId nodeid, bool initiating, const CKey& key, std::span<const std::byte> ent32, std::vector<uint8_t> garbage) noexcept
1024 : 288 : : m_cipher{key, ent32},
1025 : 288 : m_initiating{initiating},
1026 : 288 : m_nodeid{nodeid},
1027 : 288 : m_v1_fallback{nodeid},
1028 [ + + ]: 288 : m_recv_state{initiating ? RecvState::KEY : RecvState::KEY_MAYBE_V1},
1029 [ - + ]: 288 : m_send_garbage{std::move(garbage)},
1030 [ + + - + ]: 732 : m_send_state{initiating ? SendState::AWAITING_KEY : SendState::MAYBE_V1}
1031 : : {
1032 [ - + + + ]: 288 : Assume(m_send_garbage.size() <= MAX_GARBAGE_LEN);
1033 : : // Start sending immediately if we're the initiator of the connection.
1034 [ + + ]: 288 : if (initiating) {
1035 : 132 : LOCK(m_send_mutex);
1036 [ + - ]: 132 : StartSendingHandshake();
1037 : 132 : }
1038 : 288 : }
1039 : :
1040 : 288 : V2Transport::V2Transport(NodeId nodeid, bool initiating) noexcept
1041 : 576 : : V2Transport{nodeid, initiating, GenerateRandomKey(),
1042 : 576 : MakeByteSpan(GetRandHash()), GenerateRandomGarbage()} {}
1043 : :
1044 : 18711 : void V2Transport::SetReceiveState(RecvState recv_state) noexcept
1045 : : {
1046 : 18711 : AssertLockHeld(m_recv_mutex);
1047 : : // Enforce allowed state transitions.
1048 [ + + + + : 18711 : switch (m_recv_state) {
+ + - - ]
1049 : 156 : case RecvState::KEY_MAYBE_V1:
1050 : 156 : Assume(recv_state == RecvState::KEY || recv_state == RecvState::V1);
1051 : 156 : 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 : 8878 : case RecvState::APP:
1062 : 8878 : Assume(recv_state == RecvState::APP_READY);
1063 : 8878 : break;
1064 : 8878 : case RecvState::APP_READY:
1065 : 8878 : Assume(recv_state == RecvState::APP);
1066 : 8878 : break;
1067 : 0 : case RecvState::V1:
1068 : 0 : Assume(false); // V1 state cannot be left
1069 : 0 : break;
1070 : : }
1071 : : // Change state.
1072 : 18711 : m_recv_state = recv_state;
1073 : 18711 : }
1074 : :
1075 : 427 : void V2Transport::SetSendState(SendState send_state) noexcept
1076 : : {
1077 : 427 : AssertLockHeld(m_send_mutex);
1078 : : // Enforce allowed state transitions.
1079 [ + + - - ]: 427 : switch (m_send_state) {
1080 : 156 : case SendState::MAYBE_V1:
1081 : 156 : Assume(send_state == SendState::V1 || send_state == SendState::AWAITING_KEY);
1082 : 156 : 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 : : }
1091 : : // Change state.
1092 : 427 : m_send_state = send_state;
1093 : 427 : }
1094 : :
1095 : 12662 : bool V2Transport::ReceivedMessageComplete() const noexcept
1096 : : {
1097 : 12662 : AssertLockNotHeld(m_recv_mutex);
1098 : 12662 : LOCK(m_recv_mutex);
1099 [ + + ]: 12662 : if (m_recv_state == RecvState::V1) return m_v1_fallback.ReceivedMessageComplete();
1100 : :
1101 : 12263 : return m_recv_state == RecvState::APP_READY;
1102 : 12662 : }
1103 : :
1104 : 159 : void V2Transport::ProcessReceivedMaybeV1Bytes() noexcept
1105 : : {
1106 : 159 : AssertLockHeld(m_recv_mutex);
1107 : 159 : AssertLockNotHeld(m_send_mutex);
1108 : 159 : 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 : 159 : 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 : 159 : std::copy(std::begin(Params().MessageStart()), std::end(Params().MessageStart()), v1_prefix.begin());
1115 [ - + + + ]: 159 : Assume(m_recv_buffer.size() <= v1_prefix.size());
1116 [ + + ]: 159 : 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 : 150 : SetReceiveState(RecvState::KEY); // Convert to KEY state, leaving received bytes around.
1119 : : // Transition the sender to AWAITING_KEY state and start sending.
1120 : 150 : LOCK(m_send_mutex);
1121 : 150 : SetSendState(SendState::AWAITING_KEY);
1122 [ + - ]: 150 : StartSendingHandshake();
1123 [ + + ]: 159 : } 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 : : }
1140 : 159 : }
1141 : :
1142 : 366 : bool V2Transport::ProcessReceivedKeyBytes() noexcept
1143 : : {
1144 : 366 : AssertLockHeld(m_recv_mutex);
1145 : 366 : AssertLockNotHeld(m_send_mutex);
1146 [ - + ]: 366 : Assume(m_recv_state == RecvState::KEY);
1147 [ - + + + ]: 366 : 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 : 366 : static constexpr std::array<uint8_t, 12> MATCH = {'v', 'e', 'r', 's', 'i', 'o', 'n', 0, 0, 0, 0, 0};
1156 : 366 : static constexpr size_t OFFSET = std::tuple_size_v<MessageStartChars>;
1157 [ + + + + ]: 366 : if (!m_initiating && m_recv_buffer.size() >= OFFSET + MATCH.size()) {
1158 [ + + ]: 215 : 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 : : HexStr(std::span(m_recv_buffer).first(OFFSET)));
1161 : 2 : return false;
1162 : : }
1163 : : }
1164 : :
1165 [ + + ]: 364 : 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 : : /*contents=*/VERSION_CONTENTS,
1191 : 271 : /*aad=*/MakeByteSpan(m_send_garbage),
1192 : : /*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 : : }
1199 : : return true;
1200 : : }
1201 : :
1202 : 565471 : bool V2Transport::ProcessReceivedGarbageBytes() noexcept
1203 : : {
1204 : 565471 : AssertLockHeld(m_recv_mutex);
1205 [ - + ]: 565471 : Assume(m_recv_state == RecvState::GARB_GARBTERM);
1206 [ - + + + ]: 565471 : Assume(m_recv_buffer.size() <= MAX_GARBAGE_LEN + BIP324Cipher::GARBAGE_TERMINATOR_LEN);
1207 [ + + ]: 565471 : if (m_recv_buffer.size() >= BIP324Cipher::GARBAGE_TERMINATOR_LEN) {
1208 [ + + ]: 561406 : 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 [ + + ]: 561141 : } 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 : : } else {
1220 : : // We still need to receive more garbage and/or garbage terminator bytes.
1221 : : }
1222 : : } else {
1223 : : // We have less than GARBAGE_TERMINATOR_LEN (16) bytes, so we certainly need to receive
1224 : : // more first.
1225 : : }
1226 : : return true;
1227 : : }
1228 : :
1229 : 118514 : bool V2Transport::ProcessReceivedPacketBytes() noexcept
1230 : : {
1231 : 118514 : AssertLockHeld(m_recv_mutex);
1232 [ - + ]: 118514 : 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 : 118514 : static constexpr size_t MAX_CONTENTS_LEN =
1239 : : 1 + CMessageHeader::MESSAGE_TYPE_SIZE +
1240 : : std::min<size_t>(MAX_SIZE, MAX_PROTOCOL_MESSAGE_LENGTH);
1241 : :
1242 [ - + + + ]: 118514 : if (m_recv_buffer.size() == BIP324Cipher::LENGTH_LEN) {
1243 : : // Length descriptor received.
1244 : 58479 : m_recv_len = m_cipher.DecryptLength(MakeByteSpan(m_recv_buffer));
1245 [ + + ]: 58479 : 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 : : }
1249 [ + + + + ]: 60035 : } 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 : 58469 : m_recv_decode_buffer.resize(m_recv_len);
1254 : 58469 : bool ignore{false};
1255 : 116938 : bool ret = m_cipher.Decrypt(
1256 : 58469 : /*input=*/MakeByteSpan(m_recv_buffer).subspan(BIP324Cipher::LENGTH_LEN),
1257 : 58469 : /*aad=*/MakeByteSpan(m_recv_aad),
1258 : : /*ignore=*/ignore,
1259 : : /*contents=*/MakeWritableByteSpan(m_recv_decode_buffer));
1260 [ + + ]: 58469 : 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 : : }
1264 : : // We have decrypted a valid packet with the AAD we expected, so clear the expected AAD.
1265 : 58457 : ClearShrink(m_recv_aad);
1266 : : // Feed the last 4 bytes of the Poly1305 authentication tag (and its timing) into our RNG.
1267 [ - + ]: 58457 : 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 [ + + ]: 58457 : if (!ignore) {
1272 [ + + - ]: 9141 : 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 : 8878 : case RecvState::APP:
1279 : : // Application message decrypted correctly. It can be extracted using GetMessage().
1280 : 8878 : SetReceiveState(RecvState::APP_READY);
1281 : 8878 : break;
1282 : 0 : default:
1283 : : // Any other state is invalid (this function should not have been called).
1284 : 0 : Assume(false);
1285 : : }
1286 : : }
1287 : : // Wipe the receive buffer where the next packet will be received into.
1288 : 58457 : ClearShrink(m_recv_buffer);
1289 : : // In all but APP_READY state, we can wipe the decoded contents.
1290 [ + + ]: 58457 : if (m_recv_state != RecvState::APP_READY) ClearShrink(m_recv_decode_buffer);
1291 : : } 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 : : }
1295 : : return true;
1296 : : }
1297 : :
1298 : 687631 : size_t V2Transport::GetMaxBytesToProcess() noexcept
1299 : : {
1300 : 687631 : AssertLockHeld(m_recv_mutex);
1301 [ + + + + : 687631 : switch (m_recv_state) {
- - + ]
1302 : 159 : 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 [ - + ]: 159 : 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 : 159 : return V1_PREFIX_LEN - m_recv_buffer.size();
1311 : 366 : case RecvState::KEY:
1312 : : // During the KEY state, we only allow the 64-byte key into the receive buffer.
1313 [ - + ]: 366 : 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 : 366 : return EllSwiftPubKey::size() - m_recv_buffer.size();
1318 : : case RecvState::GARB_GARBTERM:
1319 : : // Process garbage bytes one by one (because terminator may appear anywhere).
1320 : : return 1;
1321 : 118514 : case RecvState::VERSION:
1322 : 118514 : 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 [ - + + + ]: 118514 : if (m_recv_buffer.size() < BIP324Cipher::LENGTH_LEN) {
1327 : 58489 : return BIP324Cipher::LENGTH_LEN - m_recv_buffer.size();
1328 : : } 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 : 60025 : return BIP324Cipher::EXPANSION + m_recv_len - m_recv_buffer.size();
1334 : : }
1335 : 3121 : case RecvState::APP_READY:
1336 : : // No bytes can be processed until GetMessage() is called.
1337 : 3121 : 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 : : }
1343 : 0 : Assume(false); // unreachable
1344 : 0 : return 0;
1345 : : }
1346 : :
1347 : 12016 : bool V2Transport::ReceivedBytes(std::span<const uint8_t>& msg_bytes) noexcept
1348 : : {
1349 : 12016 : AssertLockNotHeld(m_recv_mutex);
1350 : : /** How many bytes to allocate in the receive buffer at most above what is received so far. */
1351 : 12016 : static constexpr size_t MAX_RESERVE_AHEAD = 256 * 1024;
1352 : :
1353 : 12016 : LOCK(m_recv_mutex);
1354 [ + + ]: 12016 : 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 [ + + ]: 696099 : while (!msg_bytes.empty()) {
1361 : : // Decide how many bytes to copy from msg_bytes to m_recv_buffer.
1362 : 687631 : size_t max_read = GetMaxBytesToProcess();
1363 : :
1364 : : // Reserve space in the buffer if there is not enough.
1365 [ - + + + : 696114 : if (m_recv_buffer.size() + std::min(msg_bytes.size(), max_read) > m_recv_buffer.capacity()) {
- + + + ]
1366 [ + + - - : 117302 : switch (m_recv_state) {
- ]
1367 : 279 : 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 : 117023 : case RecvState::VERSION:
1375 : 117023 : 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 [ + + ]: 117023 : size_t alloc_add = std::min(max_read, msg_bytes.size() + MAX_RESERVE_AHEAD);
1382 : 117023 : m_recv_buffer.reserve(m_recv_buffer.size() + alloc_add);
1383 : 117023 : break;
1384 : : }
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 : : }
1394 : : }
1395 : :
1396 : : // Can't read more than provided input.
1397 [ + + ]: 687631 : max_read = std::min(msg_bytes.size(), max_read);
1398 : : // Copy data to buffer.
1399 : 687631 : m_recv_buffer.insert(m_recv_buffer.end(), UCharCast(msg_bytes.data()), UCharCast(msg_bytes.data() + max_read));
1400 [ + + + + : 687631 : msg_bytes = msg_bytes.subspan(max_read);
- - + ]
1401 : :
1402 : : // Process data in the buffer.
1403 [ + + + + : 687631 : switch (m_recv_state) {
- - + ]
1404 : 159 : case RecvState::KEY_MAYBE_V1:
1405 : 159 : ProcessReceivedMaybeV1Bytes();
1406 [ + + ]: 159 : if (m_recv_state == RecvState::V1) return true;
1407 : : break;
1408 : :
1409 : 366 : case RecvState::KEY:
1410 [ + + ]: 366 : if (!ProcessReceivedKeyBytes()) return false;
1411 : : break;
1412 : :
1413 : 565471 : case RecvState::GARB_GARBTERM:
1414 [ + + ]: 565471 : if (!ProcessReceivedGarbageBytes()) return false;
1415 : : break;
1416 : :
1417 : 118514 : case RecvState::VERSION:
1418 : 118514 : case RecvState::APP:
1419 [ + + ]: 118514 : if (!ProcessReceivedPacketBytes()) return false;
1420 : : break;
1421 : :
1422 : : case RecvState::APP_READY:
1423 : : return true;
1424 : :
1425 : 0 : case RecvState::V1:
1426 : : // We should have bailed out before.
1427 : 0 : Assume(false);
1428 : 0 : break;
1429 : : }
1430 : : // Make sure we have made progress before continuing.
1431 : 684476 : Assume(max_read > 0);
1432 : : }
1433 : :
1434 : : return true;
1435 : 12016 : }
1436 : :
1437 : 8878 : std::optional<std::string> V2Transport::GetMessageType(std::span<const uint8_t>& contents) noexcept
1438 : : {
1439 [ - + ]: 8878 : if (contents.size() == 0) return std::nullopt; // Empty contents
1440 [ + + ]: 8878 : uint8_t first_byte = contents[0];
1441 [ + + ]: 8878 : contents = contents.subspan(1); // Strip first byte.
1442 : :
1443 [ + + ]: 8878 : if (first_byte != 0) {
1444 : : // Short (1 byte) encoding.
1445 [ + + ]: 7930 : if (first_byte < std::size(V2_MESSAGE_IDS)) {
1446 : : // Valid short message id.
1447 [ - + ]: 15858 : return V2_MESSAGE_IDS[first_byte];
1448 : : } else {
1449 : : // Unknown short message id.
1450 : 1 : return std::nullopt;
1451 : : }
1452 : : }
1453 : :
1454 [ + + ]: 948 : if (contents.size() < CMessageHeader::MESSAGE_TYPE_SIZE) {
1455 : 10 : return std::nullopt; // Long encoding needs 12 message type bytes.
1456 : : }
1457 : :
1458 : : size_t msg_type_len{0};
1459 [ + - + + ]: 8366 : 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 [ + + + - ]: 7438 : if (contents[msg_type_len] < ' ' || contents[msg_type_len] > 0x7E) {
1463 : 10 : return {};
1464 : : }
1465 : 7428 : ++msg_type_len;
1466 : : }
1467 : 928 : std::string ret{reinterpret_cast<const char*>(contents.data()), msg_type_len};
1468 [ + + ]: 4546 : while (msg_type_len < CMessageHeader::MESSAGE_TYPE_SIZE) {
1469 : : // Verify that message type bytes after the first 0x00 are also 0x00.
1470 [ + + ]: 3668 : if (contents[msg_type_len] != 0) return {};
1471 : 3618 : ++msg_type_len;
1472 : : }
1473 : : // Strip message type bytes of contents.
1474 : 878 : contents = contents.subspan(CMessageHeader::MESSAGE_TYPE_SIZE);
1475 : 878 : return ret;
1476 : 928 : }
1477 : :
1478 : 9081 : CNetMessage V2Transport::GetReceivedMessage(NodeClock::time_point time, bool& reject_message) noexcept
1479 : : {
1480 : 9081 : AssertLockNotHeld(m_recv_mutex);
1481 : 9081 : LOCK(m_recv_mutex);
1482 [ + + ]: 9081 : if (m_recv_state == RecvState::V1) return m_v1_fallback.GetReceivedMessage(time, reject_message);
1483 : :
1484 [ - + ]: 8878 : Assume(m_recv_state == RecvState::APP_READY);
1485 [ - + ]: 8878 : std::span<const uint8_t> contents{m_recv_decode_buffer};
1486 : 8878 : auto msg_type = GetMessageType(contents);
1487 : 8878 : CNetMessage msg{DataStream{}};
1488 : : // Note that BIP324Cipher::EXPANSION also includes the length descriptor size.
1489 [ - + ]: 8878 : msg.m_raw_message_size = m_recv_decode_buffer.size() + BIP324Cipher::EXPANSION;
1490 [ + + ]: 8878 : if (msg_type) {
1491 : 8807 : reject_message = false;
1492 : 8807 : msg.m_type = std::move(*msg_type);
1493 : 8807 : msg.m_time = time;
1494 : 8807 : msg.m_message_size = contents.size();
1495 : 8807 : msg.m_recv.resize(contents.size());
1496 : 8807 : std::copy(contents.begin(), contents.end(), UCharCast(msg.m_recv.data()));
1497 : : } 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 : : }
1501 : 8878 : ClearShrink(m_recv_decode_buffer);
1502 : 8878 : SetReceiveState(RecvState::APP);
1503 : :
1504 : 8878 : return msg;
1505 : 8878 : }
1506 : :
1507 : 9788 : bool V2Transport::SetMessageToSend(CSerializedNetMsg& msg) noexcept
1508 : : {
1509 : 9788 : AssertLockNotHeld(m_send_mutex);
1510 : 9788 : LOCK(m_send_mutex);
1511 [ + + ]: 9788 : 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 [ + + + + ]: 9447 : if (!(m_send_state == SendState::READY && m_send_buffer.empty())) return false;
1516 : : // Construct contents (encoding message type + payload).
1517 : 9361 : std::vector<uint8_t> contents;
1518 : 9361 : auto short_message_id = V2_MESSAGE_MAP(msg.m_type);
1519 [ + + ]: 9361 : if (short_message_id) {
1520 [ - + ]: 8434 : contents.resize(1 + msg.data.size());
1521 : 8434 : contents[0] = *short_message_id;
1522 : 8434 : std::copy(msg.data.begin(), msg.data.end(), contents.begin() + 1);
1523 : : } 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 [ - + ]: 927 : contents.resize(1 + CMessageHeader::MESSAGE_TYPE_SIZE + msg.data.size(), 0);
1527 [ - + ]: 927 : std::copy(msg.m_type.begin(), msg.m_type.end(), contents.data() + 1);
1528 : 927 : std::copy(msg.data.begin(), msg.data.end(), contents.begin() + 1 + CMessageHeader::MESSAGE_TYPE_SIZE);
1529 : : }
1530 : : // Construct ciphertext in send buffer.
1531 [ - + ]: 9361 : m_send_buffer.resize(contents.size() + BIP324Cipher::EXPANSION);
1532 : 9361 : m_cipher.Encrypt(MakeByteSpan(contents), {}, false, MakeWritableByteSpan(m_send_buffer));
1533 : 9361 : m_send_type = msg.m_type;
1534 : : // Release memory
1535 : 9361 : ClearShrink(msg.data);
1536 : 9361 : return true;
1537 : 9361 : }
1538 : :
1539 : 55452 : Transport::BytesToSend V2Transport::GetBytesToSend(bool have_next_message) const noexcept
1540 : : {
1541 : 55452 : AssertLockNotHeld(m_send_mutex);
1542 : 55452 : LOCK(m_send_mutex);
1543 [ + + ]: 55452 : if (m_send_state == SendState::V1) return m_v1_fallback.GetBytesToSend(have_next_message);
1544 : :
1545 [ + + ]: 53000 : if (m_send_state == SendState::MAYBE_V1) Assume(m_send_buffer.empty());
1546 [ - + + + ]: 53000 : Assume(m_send_pos <= m_send_buffer.size());
1547 : 53000 : return {
1548 [ + + ]: 53000 : 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 [ + + + + ]: 53000 : have_next_message && m_send_state == SendState::READY,
1552 : 53000 : m_send_type
1553 : 53000 : };
1554 : 55452 : }
1555 : :
1556 : 11139 : void V2Transport::MarkBytesSent(size_t bytes_sent) noexcept
1557 : : {
1558 : 11139 : AssertLockNotHeld(m_send_mutex);
1559 : 11139 : LOCK(m_send_mutex);
1560 [ + + + - ]: 11139 : if (m_send_state == SendState::V1) return m_v1_fallback.MarkBytesSent(bytes_sent);
1561 : :
1562 [ + + + + : 10471 : if (m_send_state == SendState::AWAITING_KEY && m_send_pos == 0 && bytes_sent > 0) {
+ - ]
1563 [ + - ]: 138 : LogDebug(BCLog::NET, "start sending v2 handshake to peer=%d\n", m_nodeid);
1564 : : }
1565 : :
1566 : 10471 : m_send_pos += bytes_sent;
1567 [ - + + + ]: 10471 : Assume(m_send_pos <= m_send_buffer.size());
1568 [ + + ]: 10471 : if (m_send_pos >= CMessageHeader::HEADER_SIZE) {
1569 : 10354 : m_sent_v1_header_worth = true;
1570 : : }
1571 : : // Wipe the buffer when everything is sent.
1572 [ + + ]: 10471 : if (m_send_pos == m_send_buffer.size()) {
1573 : 9752 : m_send_pos = 0;
1574 : 9752 : ClearShrink(m_send_buffer);
1575 : : }
1576 : 11139 : }
1577 : :
1578 : 154 : bool V2Transport::ShouldReconnectV1() const noexcept
1579 : : {
1580 : 154 : AssertLockNotHeld(m_send_mutex);
1581 : 154 : AssertLockNotHeld(m_recv_mutex);
1582 : : // Only outgoing connections need reconnection.
1583 [ + + ]: 154 : if (!m_initiating) return false;
1584 : :
1585 : 77 : 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 [ + + ]: 77 : if (m_recv_state != RecvState::KEY) return false;
1589 [ + - ]: 9 : 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 : 9 : LOCK(m_send_mutex);
1592 [ + - ]: 9 : return m_sent_v1_header_worth;
1593 : 86 : }
1594 : :
1595 : 19564 : size_t V2Transport::GetSendMemoryUsage() const noexcept
1596 : : {
1597 : 19564 : AssertLockNotHeld(m_send_mutex);
1598 : 19564 : LOCK(m_send_mutex);
1599 [ + + ]: 19564 : if (m_send_state == SendState::V1) return m_v1_fallback.GetSendMemoryUsage();
1600 : :
1601 [ - + ]: 37764 : return sizeof(m_send_buffer) + memusage::DynamicUsage(m_send_buffer);
1602 : 19564 : }
1603 : :
1604 : 2261 : Transport::Info V2Transport::GetInfo() const noexcept
1605 : : {
1606 : 2261 : AssertLockNotHeld(m_recv_mutex);
1607 : 2261 : LOCK(m_recv_mutex);
1608 [ + + ]: 2261 : if (m_recv_state == RecvState::V1) return m_v1_fallback.GetInfo();
1609 : :
1610 [ + + ]: 2205 : 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 [ + + ]: 2205 : if (m_recv_state != RecvState::KEY_MAYBE_V1 && m_recv_state != RecvState::KEY &&
1615 : : m_recv_state != RecvState::GARB_GARBTERM && m_recv_state != RecvState::VERSION) {
1616 : 2145 : info.transport_type = TransportProtocolType::V2;
1617 : 2145 : info.session_id = uint256(MakeUCharSpan(m_cipher.GetSessionID()));
1618 : : } else {
1619 : 60 : info.transport_type = TransportProtocolType::DETECTING;
1620 : : }
1621 : :
1622 : 2205 : return info;
1623 : 2261 : }
1624 : :
1625 : 152648 : std::pair<size_t, bool> CConnman::SocketSendData(CNode& node) const
1626 : : {
1627 : 152648 : auto it = node.vSendMsg.begin();
1628 : 152648 : size_t nSentSize = 0;
1629 : 152648 : bool data_left{false}; //!< second return value (whether unsent data remains)
1630 : 152648 : std::optional<bool> expected_more;
1631 : :
1632 : 442271 : while (true) {
1633 [ + + ]: 442271 : 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 : 153063 : size_t memusage = it->GetMemoryUsage();
1638 [ + + ]: 153063 : if (node.m_transport->SetMessageToSend(*it)) {
1639 : : // Update memory usage of send buffer (as *it will be deleted).
1640 : 152375 : node.m_send_memusage -= memusage;
1641 : 152375 : ++it;
1642 : : }
1643 : : }
1644 [ + + ]: 442271 : 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 [ + + ]: 442271 : if (expected_more.has_value()) Assume(!data.empty() == *expected_more);
1649 [ + + ]: 442271 : expected_more = more;
1650 [ + + ]: 442271 : data_left = !data.empty(); // will be overwritten on next loop if all of data gets sent
1651 : 442271 : int nBytes = 0;
1652 [ + + ]: 442271 : if (!data.empty()) {
1653 : 290262 : 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 [ + + ]: 290262 : if (!node.m_sock) {
1658 : : break;
1659 : : }
1660 : 290245 : int flags = MSG_NOSIGNAL | MSG_DONTWAIT;
1661 : : #ifdef MSG_MORE
1662 [ + + ]: 290245 : if (more) {
1663 : 137615 : flags |= MSG_MORE;
1664 : : }
1665 : : #endif
1666 [ + - + - ]: 290245 : nBytes = node.m_sock->Send(data.data(), data.size(), flags);
1667 : 17 : }
1668 [ + + ]: 290245 : if (nBytes > 0) {
1669 : 290244 : node.m_last_send = NodeClock::now();
1670 : 290244 : node.nSendBytes += nBytes;
1671 : : // Notify transport that bytes have been processed.
1672 : 290244 : node.m_transport->MarkBytesSent(nBytes);
1673 : : // Update statistics per message type.
1674 [ + + ]: 290244 : if (!msg_type.empty()) { // don't report v2 handshake bytes for now
1675 : 289948 : node.AccountForSentBytes(msg_type, nBytes);
1676 : : }
1677 : 290244 : nSentSize += nBytes;
1678 [ + + ]: 290244 : if ((size_t)nBytes != data.size()) {
1679 : : // could not send full message; stop sending more
1680 : : break;
1681 : : }
1682 : : } else {
1683 [ + + ]: 152010 : if (nBytes < 0) {
1684 : : // error
1685 : 1 : int nErr = WSAGetLastError();
1686 [ + - + - ]: 1 : if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) {
1687 [ + - + - : 1 : LogDebug(BCLog::NET, "socket send error, %s: %s", node.DisconnectMsg(), NetworkErrorString(nErr));
+ - ]
1688 : 1 : node.CloseSocketDisconnect();
1689 : : }
1690 : : }
1691 : : break;
1692 : : }
1693 : : }
1694 : :
1695 : 152648 : const bool pause_send{node.m_send_memusage + node.m_transport->GetSendMemoryUsage() > nSendBufferMaxSize};
1696 [ + + - + ]: 152648 : if (pause_send && !node.fPauseSend) {
1697 : 0 : node.m_pause_send_since = NodeClock::now();
1698 : : }
1699 [ + + ]: 152648 : node.fPauseSend = pause_send;
1700 : :
1701 [ + + ]: 152648 : if (it == node.vSendMsg.end()) {
1702 [ - + ]: 152625 : assert(node.m_send_memusage == 0);
1703 : : }
1704 : 152648 : node.vSendMsg.erase(node.vSendMsg.begin(), it);
1705 : 152648 : return {nSentSize, data_left};
1706 : : }
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 : 7 : bool CConnman::AttemptToEvictConnection(bool evict_tx_relay_peer_only, std::optional<NodeId> protect_peer)
1717 : : {
1718 : 7 : AssertLockNotHeld(m_nodes_mutex);
1719 : :
1720 : 7 : std::vector<NodeEvictionCandidate> vEvictionCandidates;
1721 : 7 : {
1722 : :
1723 [ + - ]: 7 : LOCK(m_nodes_mutex);
1724 [ + + ]: 60 : 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 : : }
1730 [ + + + + ]: 49 : if (evict_tx_relay_peer_only && !node->m_relays_txs) {
1731 : 21 : continue;
1732 : : }
1733 : 28 : NodeEvictionCandidate candidate{
1734 : 28 : .id = node->GetId(),
1735 : : .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 [ + - + - : 56 : };
+ - ]
1749 [ + - ]: 28 : vEvictionCandidates.push_back(candidate);
1750 : : }
1751 : 0 : }
1752 [ + - ]: 7 : const std::optional<NodeId> node_id_to_evict = SelectNodeToEvict(std::move(vEvictionCandidates));
1753 [ + + ]: 7 : if (!node_id_to_evict) {
1754 : : return false;
1755 : : }
1756 [ + - ]: 1 : LOCK(m_nodes_mutex);
1757 [ + - ]: 1 : for (CNode* pnode : m_nodes) {
1758 [ + - ]: 1 : if (pnode->GetId() == *node_id_to_evict) {
1759 [ + - + - : 2 : LogDebug(BCLog::NET, "selected %s connection for eviction, %s", pnode->ConnectionTypeAsString(), pnode->DisconnectMsg());
+ - + - ]
1760 : : TRACEPOINT(net, evicted_inbound_connection,
1761 : : pnode->GetId(),
1762 : : pnode->m_addr_name.c_str(),
1763 : : pnode->ConnectionTypeAsString().c_str(),
1764 : : pnode->ConnectedThroughNetwork(),
1765 : 1 : TicksSinceEpoch<std::chrono::seconds>(pnode->m_connected));
1766 : 1 : pnode->fDisconnect = true;
1767 : 1 : return true;
1768 : : }
1769 : : }
1770 : : return false;
1771 : 8 : }
1772 : :
1773 : 1166 : void CConnman::AcceptConnection(const ListenSocket& hListenSocket) {
1774 : 1166 : AssertLockNotHeld(m_nodes_mutex);
1775 : :
1776 : 1166 : struct sockaddr_storage sockaddr;
1777 : 1166 : socklen_t len = sizeof(sockaddr);
1778 : 2332 : auto sock = hListenSocket.sock->Accept((struct sockaddr*)&sockaddr, &len);
1779 : :
1780 [ - + ]: 1166 : 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 : : }
1785 : 0 : return;
1786 : : }
1787 : :
1788 [ + - ]: 1166 : CService addr;
1789 [ + - - + ]: 1166 : if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr, len)) {
1790 [ # # ]: 0 : LogWarning("Unknown socket family\n");
1791 : : } else {
1792 [ + - ]: 2332 : addr = MaybeFlipIPv6toCJDNS(addr);
1793 : : }
1794 : :
1795 [ + - + - ]: 1166 : const CService addr_bind{MaybeFlipIPv6toCJDNS(GetBindAddress(*sock))};
1796 : :
1797 : 1166 : NetPermissionFlags permission_flags = NetPermissionFlags::None;
1798 [ + - ]: 1166 : hListenSocket.AddSocketPermissionFlags(permission_flags);
1799 : :
1800 [ + - ]: 1166 : CreateNodeFromAcceptedSocket(std::move(sock), permission_flags, addr_bind, addr);
1801 : 1166 : }
1802 : :
1803 : 1166 : void CConnman::CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock,
1804 : : NetPermissionFlags permission_flags,
1805 : : const CService& addr_bind,
1806 : : const CService& addr)
1807 : : {
1808 : 1166 : AssertLockNotHeld(m_nodes_mutex);
1809 : :
1810 : 1166 : int nInbound = 0;
1811 : :
1812 [ + + ]: 1166 : 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 [ + + + - ]: 2319 : AddWhitelistPermissionFlags(permission_flags, inbound_onion ? std::optional<CNetAddr>{} : addr, vWhitelistedRangeIncoming);
1817 : :
1818 : 1166 : {
1819 : 1166 : LOCK(m_nodes_mutex);
1820 [ + + ]: 5391 : for (const CNode* pnode : m_nodes) {
1821 [ + + ]: 4225 : if (pnode->IsInboundConn()) nInbound++;
1822 : : }
1823 : 1166 : }
1824 : :
1825 [ - + ]: 1166 : if (!fNetworkActive) {
1826 [ # # # # ]: 0 : LogDebug(BCLog::NET, "connection from %s dropped: not accepting new connections\n", addr.ToStringAddrPort());
1827 : 0 : return;
1828 : : }
1829 : :
1830 [ - + ]: 1166 : if (!sock->IsSelectable()) {
1831 [ # # ]: 0 : LogInfo("connection from %s dropped: non-selectable socket\n", addr.ToStringAddrPort());
1832 : 0 : return;
1833 : : }
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 : 1166 : const int on{1};
1838 [ - + ]: 1166 : 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 : : addr.ToStringAddrPort());
1841 : : }
1842 : :
1843 : : // Don't accept connections from banned peers.
1844 [ + - + + ]: 1166 : bool banned = m_banman && m_banman->IsBanned(addr);
1845 [ + + + + ]: 1166 : if (!NetPermissions::HasFlag(permission_flags, NetPermissionFlags::NoBan) && banned)
1846 : : {
1847 [ + - + - ]: 3 : LogDebug(BCLog::NET, "connection from %s dropped (banned)\n", addr.ToStringAddrPort());
1848 : 3 : return;
1849 : : }
1850 : :
1851 : : // Only accept connections from discouraged peers if our inbound slots aren't (almost) full.
1852 [ + - + - ]: 1163 : bool discouraged = m_banman && m_banman->IsDiscouraged(addr);
1853 [ + + + + : 1163 : if (!NetPermissions::HasFlag(permission_flags, NetPermissionFlags::NoBan) && nInbound + 1 >= m_max_inbound && discouraged)
+ - ]
1854 : : {
1855 [ # # # # ]: 0 : LogDebug(BCLog::NET, "connection from %s dropped (discouraged)\n", addr.ToStringAddrPort());
1856 : 0 : return;
1857 : : }
1858 : :
1859 [ + + ]: 1163 : if (nInbound >= m_max_inbound)
1860 : : {
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 : : }
1866 : : }
1867 : :
1868 : 1162 : NodeId id = GetNewNodeId();
1869 : 1162 : 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 : 1162 : ServiceFlags local_services = GetLocalServices();
1874 : 1162 : const bool use_v2transport(local_services & NODE_P2P_V2);
1875 : :
1876 : 1162 : uint64_t network_id = GetDeterministicRandomizer(RANDOMIZER_ID_NETWORKKEY)
1877 [ + + ]: 1162 : .Write(inbound_onion ? NET_ONION : addr.GetNetClass())
1878 [ - + + - ]: 1162 : .Write(addr_bind.GetAddrBytes())
1879 [ + - + - ]: 1162 : .Write(addr_bind.GetPort()) // inbound connections use bind port
1880 [ + - ]: 1162 : .Finalize();
1881 : 1162 : CNode* pnode = new CNode(id,
1882 : 1162 : std::move(sock),
1883 [ + - ]: 2324 : CAddress{addr, NODE_NONE},
1884 : : CalculateKeyedNetGroup(addr),
1885 : : nonce,
1886 : : addr_bind,
1887 : 0 : /*addrNameIn=*/"",
1888 : : ConnectionType::INBOUND,
1889 : : inbound_onion,
1890 : : network_id,
1891 : 1162 : CNodeOptions{
1892 : : .permission_flags = permission_flags,
1893 : : .prefer_evict = discouraged,
1894 : 1162 : .recv_flood_size = nReceiveFloodSize,
1895 : : .use_v2transport = use_v2transport,
1896 [ + - + - : 2324 : });
+ - + - ]
1897 : 1162 : pnode->AddRef();
1898 : 1162 : m_msgproc->InitializeNode(*pnode, local_services);
1899 : 1162 : {
1900 : 1162 : LOCK(m_nodes_mutex);
1901 [ + - ]: 1162 : m_nodes.push_back(pnode);
1902 : 0 : }
1903 [ + - + - ]: 1162 : LogDebug(BCLog::NET, "connection from %s accepted\n", addr.ToStringAddrPort());
1904 : : TRACEPOINT(net, inbound_connection,
1905 : : pnode->GetId(),
1906 : : pnode->m_addr_name.c_str(),
1907 : : pnode->ConnectionTypeAsString().c_str(),
1908 : : pnode->ConnectedThroughNetwork(),
1909 : 1162 : GetNodeCount(ConnectionDirection::In));
1910 : :
1911 : : // We received a new connection, harvest entropy from the time (and our peer count)
1912 : 1162 : RandAddEvent((uint32_t)id);
1913 : : }
1914 : :
1915 : 170 : bool CConnman::AddConnection(const std::string& address, ConnectionType conn_type, bool use_v2transport = false)
1916 : : {
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 : : case ConnectionType::INBOUND:
1922 : : case ConnectionType::PRIVATE_BROADCAST:
1923 : : return false;
1924 : : // no separate per-type limit for MANUAL because semAddnode limits them
1925 : : case ConnectionType::MANUAL:
1926 : : 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 : : case ConnectionType::ADDR_FETCH:
1935 : : break;
1936 : : // no limit for FEELER connections since they're short-lived
1937 : : case ConnectionType::FEELER:
1938 : : break;
1939 : : } // no default case, so the compiler can warn about missing cases
1940 : :
1941 : : // Count existing connections
1942 [ + + + - ]: 656 : int existing_connections = WITH_LOCK(m_nodes_mutex,
1943 : : 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 [ + + ]: 340 : if (max_connections != std::nullopt && existing_connections >= max_connections) return false;
1947 : :
1948 : : // Max total automatic outbound or manual connections already exist
1949 [ + + ]: 340 : CountingSemaphoreGrant<> grant(conn_type == ConnectionType::MANUAL ? *semAddnode : *semOutbound, true);
1950 [ + - ]: 170 : if (!grant) return false;
1951 : :
1952 [ + - - + ]: 340 : OpenNetworkConnection(/*addrConnect=*/CAddress{},
1953 : : /*fCountFailure=*/false,
1954 : : /*grant_outbound=*/std::move(grant),
1955 : : /*pszDest=*/address.c_str(),
1956 : : /*conn_type=*/conn_type,
1957 : : /*use_v2transport=*/use_v2transport,
1958 [ + - ]: 170 : /*proxy_override=*/std::nullopt);
1959 : 170 : return true;
1960 : : }
1961 : :
1962 : 393929 : void CConnman::DisconnectNodes()
1963 : : {
1964 : 393929 : AssertLockNotHeld(m_nodes_mutex);
1965 : 393929 : 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 [ + - ]: 393929 : decltype(m_reconnections) reconnections_to_add;
1970 : :
1971 : 393929 : {
1972 [ + - ]: 393929 : LOCK(m_nodes_mutex);
1973 : :
1974 [ + + ]: 393929 : const bool network_active{fNetworkActive};
1975 [ + + ]: 393929 : if (!network_active) {
1976 : : // Disconnect any connected nodes
1977 [ + + ]: 143 : 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 : : }
1982 : : }
1983 : : }
1984 : :
1985 : : // Disconnect unused nodes
1986 [ + - ]: 393929 : std::vector<CNode*> nodes_copy = m_nodes;
1987 [ + + ]: 969912 : for (CNode* pnode : nodes_copy)
1988 : : {
1989 [ + + ]: 575983 : if (pnode->fDisconnect)
1990 : : {
1991 : : // remove from m_nodes
1992 : 1084 : 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 [ + + + + ]: 1084 : if (network_active && pnode->m_transport->ShouldReconnectV1()) {
1998 : 9 : reconnections_to_add.push_back({
1999 : 9 : .proxy_override = pnode->m_proxy_override,
2000 : 9 : .addr_connect = pnode->addr,
2001 [ - + ]: 9 : .grant = std::move(pnode->grantOutbound),
2002 : 9 : .destination = pnode->m_dest,
2003 : 9 : .conn_type = pnode->m_conn_type,
2004 : : .use_v2transport = false});
2005 [ + - + - : 9 : LogDebug(BCLog::NET, "retrying with v1 transport protocol for peer=%d\n", pnode->GetId());
+ - ]
2006 : : }
2007 : :
2008 : : // release outbound grant (if any)
2009 : 1084 : pnode->grantOutbound.Release();
2010 : :
2011 : : // close socket and cleanup
2012 [ + - ]: 1084 : pnode->CloseSocketDisconnect();
2013 : :
2014 : : // update connection count by network
2015 [ + + + - ]: 1084 : if (pnode->IsManualOrFullOutboundConn()) --m_network_conn_counts[pnode->addr.GetNetwork()];
2016 : :
2017 : : // hold in disconnected pool until all refs are released
2018 [ + - ]: 1084 : pnode->Release();
2019 [ + - ]: 1084 : m_nodes_disconnected.push_back(pnode);
2020 : : }
2021 : : }
2022 [ + - ]: 393929 : }
2023 : 393929 : {
2024 : : // Delete disconnected nodes
2025 [ + - ]: 393929 : std::list<CNode*> nodes_disconnected_copy = m_nodes_disconnected;
2026 [ + + ]: 395020 : for (CNode* pnode : nodes_disconnected_copy)
2027 : : {
2028 : : // Destroy the object only after other threads have stopped using it.
2029 [ + + ]: 1091 : if (pnode->GetRefCount() <= 0) {
2030 : 1084 : std::erase(m_nodes_disconnected, pnode);
2031 [ + - ]: 1084 : DeleteNode(pnode);
2032 : : }
2033 : : }
2034 : 0 : }
2035 : 393929 : {
2036 : : // Move entries from reconnections_to_add to m_reconnections.
2037 [ + - ]: 393929 : LOCK(m_reconnections_mutex);
2038 [ + - ]: 393929 : m_reconnections.splice(m_reconnections.end(), std::move(reconnections_to_add));
2039 : 393929 : }
2040 [ + - - + : 393947 : }
+ - - - -
- ]
2041 : :
2042 : 393929 : void CConnman::NotifyNumConnectionsChanged()
2043 : : {
2044 : 393929 : AssertLockNotHeld(m_nodes_mutex);
2045 : :
2046 : 393929 : size_t nodes_size;
2047 : 393929 : {
2048 : 393929 : LOCK(m_nodes_mutex);
2049 [ - + + - ]: 393929 : nodes_size = m_nodes.size();
2050 : 393929 : }
2051 [ + + ]: 393929 : if(nodes_size != nPrevNodeCount) {
2052 : 2663 : nPrevNodeCount = nodes_size;
2053 [ + - ]: 2663 : if (m_client_interface) {
2054 : 2663 : m_client_interface->NotifyNumConnectionsChanged(nodes_size);
2055 : : }
2056 : : }
2057 : 393929 : }
2058 : :
2059 : 788253 : bool CConnman::ShouldRunInactivityChecks(const CNode& node, NodeClock::time_point now) const
2060 : : {
2061 : 788253 : return node.m_connected + m_peer_connect_timeout < now;
2062 : : }
2063 : :
2064 : 574111 : bool CConnman::InactivityCheck(const CNode& node, NodeClock::time_point now) const
2065 : : {
2066 : : // Tests that see disconnects after using mocktime can start nodes with a
2067 : : // large timeout. For example, -peertimeout=999999999.
2068 : 574111 : const auto last_send{node.m_last_send.load()};
2069 : 574111 : const auto last_recv{node.m_last_recv.load()};
2070 : :
2071 [ + + ]: 574111 : if (!ShouldRunInactivityChecks(node, now)) return false;
2072 : :
2073 [ + + ]: 103 : bool has_received{last_recv > NodeClock::epoch};
2074 : 103 : bool has_sent{last_send > NodeClock::epoch};
2075 : :
2076 [ + + ]: 103 : 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 : : "socket no message in first %i seconds%s, %s",
2082 : : count_seconds(m_peer_connect_timeout),
2083 : : has_never,
2084 : : node.DisconnectMsg()
2085 : : );
2086 : 3 : return true;
2087 : 3 : }
2088 : :
2089 [ - + ]: 100 : if (now > last_send + TIMEOUT_INTERVAL) {
2090 [ # # # # ]: 0 : LogDebug(BCLog::NET,
2091 : : "socket sending timeout: %is, %s", Ticks<std::chrono::seconds>(now - last_send),
2092 : : node.DisconnectMsg()
2093 : : );
2094 : 0 : return true;
2095 : : }
2096 : :
2097 [ - + ]: 100 : if (now > last_recv + TIMEOUT_INTERVAL) {
2098 [ # # # # ]: 0 : LogDebug(BCLog::NET,
2099 : : "socket receive timeout: %is, %s", Ticks<std::chrono::seconds>(now - last_recv),
2100 : : node.DisconnectMsg()
2101 : : );
2102 : 0 : return true;
2103 : : }
2104 : :
2105 [ - + ]: 100 : 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 : : "send buffer full for %is, %s", Ticks<std::chrono::seconds>(now - last_pause),
2110 : : node.DisconnectMsg()
2111 : : );
2112 : 0 : return true;
2113 : : }
2114 : : }
2115 : :
2116 [ + + ]: 100 : 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 : : } else {
2120 [ + - + - ]: 7 : LogDebug(BCLog::NET, "version handshake timeout, %s", node.DisconnectMsg());
2121 : : }
2122 : 9 : return true;
2123 : : }
2124 : :
2125 : : return false;
2126 : : }
2127 : :
2128 : 393929 : Sock::EventsPerSock CConnman::GenerateWaitSockets(std::span<CNode* const> nodes)
2129 : : {
2130 : 393929 : Sock::EventsPerSock events_per_sock;
2131 : :
2132 [ + + ]: 788818 : for (const ListenSocket& hListenSocket : vhListenSocket) {
2133 [ + - ]: 394889 : events_per_sock.emplace(hListenSocket.sock, Sock::Events{Sock::RecvEvent});
2134 : : }
2135 : :
2136 [ + + ]: 968828 : for (CNode* pnode : nodes) {
2137 [ + - ]: 574899 : bool select_recv = !pnode->fPauseRecv;
2138 : 574899 : bool select_send;
2139 : 574899 : {
2140 [ + - ]: 574899 : 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 [ + + ]: 574899 : const auto& [to_send, more, _msg_type] = pnode->m_transport->GetBytesToSend(!pnode->vSendMsg.empty());
2145 [ + + + - : 1147859 : select_send = !to_send.empty() || more;
+ - ]
2146 : 574899 : }
2147 [ + + ]: 574899 : if (!select_recv && !select_send) continue;
2148 : :
2149 [ + - ]: 573865 : LOCK(pnode->m_sock_mutex);
2150 [ + - ]: 573865 : if (pnode->m_sock) {
2151 [ + + - + ]: 1145791 : Sock::Event event = (select_send ? Sock::SendEvent : 0) | (select_recv ? Sock::RecvEvent : 0);
2152 [ + - ]: 573865 : events_per_sock.emplace(pnode->m_sock, Sock::Events{event});
2153 : : }
2154 : 573865 : }
2155 : :
2156 : 393929 : return events_per_sock;
2157 : 0 : }
2158 : :
2159 : 393929 : void CConnman::SocketHandler()
2160 : : {
2161 : 393929 : AssertLockNotHeld(m_nodes_mutex);
2162 : 393929 : AssertLockNotHeld(m_total_bytes_sent_mutex);
2163 : :
2164 [ + - ]: 393929 : Sock::EventsPerSock events_per_sock;
2165 : :
2166 : 393929 : {
2167 [ + - ]: 393929 : const NodesSnapshot snap{*this, /*shuffle=*/false};
2168 : :
2169 : 393929 : 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 [ - + + - ]: 787858 : events_per_sock = GenerateWaitSockets(snap.Nodes());
2176 [ + + + - : 393929 : if (events_per_sock.empty() || !events_per_sock.begin()->first->WaitMany(timeout, events_per_sock)) {
- + ]
2177 [ + - ]: 127 : m_interrupt_net->sleep_for(timeout);
2178 : : }
2179 : :
2180 : : // Service (send/receive) each of the already connected nodes.
2181 [ + - ]: 393929 : SocketHandlerConnected(snap.Nodes(), events_per_sock);
2182 : 393929 : }
2183 : :
2184 : : // Accept new connections from listening sockets.
2185 [ + - ]: 393929 : SocketHandlerListening(events_per_sock);
2186 : 393929 : }
2187 : :
2188 : 393929 : void CConnman::SocketHandlerConnected(const std::vector<CNode*>& nodes,
2189 : : const Sock::EventsPerSock& events_per_sock)
2190 : : {
2191 : 393929 : AssertLockNotHeld(m_total_bytes_sent_mutex);
2192 : :
2193 : 393929 : const auto now{NodeClock::now()};
2194 : :
2195 [ + + ]: 968041 : for (CNode* pnode : nodes) {
2196 [ + + ]: 574537 : if (m_interrupt_net->interrupted()) {
2197 : : return;
2198 : : }
2199 : :
2200 : : //
2201 : : // Receive
2202 : : //
2203 : 574112 : bool recvSet = false;
2204 : 574112 : bool sendSet = false;
2205 : 574112 : bool errorSet = false;
2206 : 574112 : {
2207 : 574112 : LOCK(pnode->m_sock_mutex);
2208 [ + + ]: 574112 : if (!pnode->m_sock) {
2209 [ + - ]: 1 : continue;
2210 : : }
2211 [ + - + - ]: 1148222 : const auto it = events_per_sock.find(pnode->m_sock);
2212 [ + + + - ]: 1147188 : if (it != events_per_sock.end()) {
2213 : 573077 : recvSet = it->second.occurred & Sock::RecvEvent;
2214 : 573077 : sendSet = it->second.occurred & Sock::SendEvent;
2215 : 573077 : errorSet = it->second.occurred & Sock::ErrorEvent;
2216 : : }
2217 : 1 : }
2218 : :
2219 [ + + ]: 574111 : if (sendSet) {
2220 : : // Send data
2221 [ + - + - ]: 2745 : auto [bytes_sent, data_left] = WITH_LOCK(pnode->cs_vSend, return SocketSendData(*pnode));
2222 [ + - ]: 915 : if (bytes_sent) {
2223 : 915 : 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 [ + + ]: 915 : if (data_left) recvSet = false;
2233 : : }
2234 : : }
2235 : :
2236 [ + + ]: 574111 : if (recvSet || errorSet)
2237 : : {
2238 : : // typical socket buffer is 8K-64K
2239 : 218873 : uint8_t pchBuf[0x10000];
2240 : 218873 : int nBytes = 0;
2241 : 218873 : {
2242 : 218873 : LOCK(pnode->m_sock_mutex);
2243 [ - + ]: 218873 : if (!pnode->m_sock) {
2244 [ # # ]: 0 : continue;
2245 : : }
2246 [ + - + - ]: 218873 : nBytes = pnode->m_sock->Recv(pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
2247 : 0 : }
2248 [ + + ]: 218873 : if (nBytes > 0)
2249 : : {
2250 : 218182 : bool notify = false;
2251 [ + + ]: 218182 : if (!pnode->ReceiveMsgBytes({pchBuf, (size_t)nBytes}, notify)) {
2252 [ + - + - ]: 10 : LogDebug(BCLog::NET,
2253 : : "receiving message bytes failed, %s",
2254 : : pnode->DisconnectMsg()
2255 : : );
2256 : 10 : pnode->CloseSocketDisconnect();
2257 : : }
2258 : 218182 : RecordBytesRecv(nBytes);
2259 [ + + ]: 218182 : if (notify) {
2260 : 112638 : pnode->MarkReceivedMsgsForProcessing();
2261 : 112638 : WakeMessageHandler();
2262 : : }
2263 : : }
2264 [ + + ]: 691 : else if (nBytes == 0)
2265 : : {
2266 : : // socket closed gracefully
2267 [ + - ]: 674 : if (!pnode->fDisconnect) {
2268 [ + - + - ]: 674 : LogDebug(BCLog::NET, "socket closed, %s", pnode->DisconnectMsg());
2269 : : }
2270 : 674 : pnode->CloseSocketDisconnect();
2271 : : }
2272 [ + - ]: 17 : else if (nBytes < 0)
2273 : : {
2274 : : // error
2275 : 17 : int nErr = WSAGetLastError();
2276 [ + - + - ]: 17 : if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
2277 : : {
2278 [ + - ]: 17 : if (!pnode->fDisconnect) {
2279 [ + - + - : 17 : LogDebug(BCLog::NET, "socket recv error, %s: %s", pnode->DisconnectMsg(), NetworkErrorString(nErr));
+ - ]
2280 : : }
2281 : 17 : pnode->CloseSocketDisconnect();
2282 : : }
2283 : : }
2284 : : }
2285 : :
2286 [ + + ]: 574111 : if (InactivityCheck(*pnode, now)) pnode->fDisconnect = true;
2287 : : }
2288 : : }
2289 : :
2290 : 393929 : void CConnman::SocketHandlerListening(const Sock::EventsPerSock& events_per_sock)
2291 : : {
2292 : 393929 : AssertLockNotHeld(m_nodes_mutex);
2293 : :
2294 [ + + ]: 787682 : for (const ListenSocket& listen_socket : vhListenSocket) {
2295 [ + + ]: 394870 : if (m_interrupt_net->interrupted()) {
2296 : : return;
2297 : : }
2298 [ + - + - ]: 787506 : const auto it = events_per_sock.find(listen_socket.sock);
2299 [ + - + + ]: 394919 : if (it != events_per_sock.end() && it->second.occurred & Sock::RecvEvent) {
2300 : 1166 : AcceptConnection(listen_socket);
2301 : : }
2302 : : }
2303 : : }
2304 : :
2305 : 1136 : void CConnman::ThreadSocketHandler()
2306 : : {
2307 : 1136 : AssertLockNotHeld(m_total_bytes_sent_mutex);
2308 : :
2309 [ + + ]: 395065 : while (!m_interrupt_net->interrupted()) {
2310 : 393929 : DisconnectNodes();
2311 : 393929 : NotifyNumConnectionsChanged();
2312 : 393929 : SocketHandler();
2313 : : }
2314 : 1136 : }
2315 : :
2316 : 210559 : void CConnman::WakeMessageHandler()
2317 : : {
2318 : 210559 : {
2319 : 210559 : LOCK(mutexMsgProc);
2320 [ + - ]: 210559 : fMsgProcWake = true;
2321 : 210559 : }
2322 : 210559 : condMsgProc.notify_one();
2323 : 210559 : }
2324 : :
2325 : 13 : void CConnman::ThreadDNSAddressSeed()
2326 : : {
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 : : return;
2336 : : }
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 : : }
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 : : }
2350 : : }
2351 : : }
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 : : }
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 [ + + ]: 22 : 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 : : } else {
2405 [ + - ]: 1 : LogInfo("P2P peers available. Skipped DNS seeding.\n");
2406 : : }
2407 : 1 : return;
2408 : : }
2409 : : }
2410 : : }
2411 : : }
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 : : }
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 : : } 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 : : }
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 : : } 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 : : }
2456 : 0 : }
2457 : 9 : --seeds_right_now;
2458 : : }
2459 [ + - ]: 9 : LogInfo("%d addresses found from DNS seeds\n", found);
2460 : : } else {
2461 [ # # ]: 0 : LogInfo("Skipping DNS seeds. Enough peers have been found\n");
2462 : : }
2463 : 13 : }
2464 : :
2465 : 1147 : void CConnman::DumpAddresses()
2466 : : {
2467 : 1147 : const auto start{SteadyClock::now()};
2468 : :
2469 : 1147 : DumpPeerAddresses(::gArgs, addrman);
2470 : :
2471 [ + - ]: 1147 : LogDebug(BCLog::NET, "Flushed %d addresses to peers.dat %dms",
2472 : : addrman.get().Size(), Ticks<std::chrono::milliseconds>(SteadyClock::now() - start));
2473 : 1147 : }
2474 : :
2475 : 188 : void CConnman::ProcessAddrFetch()
2476 : : {
2477 : 188 : AssertLockNotHeld(m_nodes_mutex);
2478 : 188 : AssertLockNotHeld(m_unused_i2p_sessions_mutex);
2479 [ + - ]: 188 : std::string strDest;
2480 : 188 : {
2481 [ + - ]: 188 : LOCK(m_addr_fetches_mutex);
2482 [ + + ]: 188 : if (m_addr_fetches.empty())
2483 [ + - ]: 181 : return;
2484 [ + - ]: 7 : strDest = m_addr_fetches.front();
2485 [ + - ]: 7 : m_addr_fetches.pop_front();
2486 : 181 : }
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 [ + - ]: 7 : 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 : : /*fCountFailure=*/false,
2495 : : /*grant_outbound=*/std::move(grant),
2496 : : /*pszDest=*/strDest.c_str(),
2497 : : /*conn_type=*/ConnectionType::ADDR_FETCH,
2498 : : /*use_v2transport=*/use_v2transport,
2499 [ + - ]: 14 : /*proxy_override=*/std::nullopt);
2500 : : }
2501 : 188 : }
2502 : :
2503 : 74 : bool CConnman::GetTryNewOutboundPeer() const
2504 : : {
2505 : 74 : return m_try_another_outbound_peer;
2506 : : }
2507 : :
2508 : 1418 : void CConnman::SetTryNewOutboundPeer(bool flag)
2509 : : {
2510 : 1418 : m_try_another_outbound_peer = flag;
2511 [ + - + + ]: 2835 : LogDebug(BCLog::NET, "setting try another outbound peer=%s\n", flag ? "true" : "false");
2512 : 1418 : }
2513 : :
2514 : 38 : void CConnman::StartExtraBlockRelayPeers()
2515 : : {
2516 [ + - ]: 38 : LogDebug(BCLog::NET, "enabling extra block-relay-only peers\n");
2517 : 38 : m_start_extra_block_relay_peers = true;
2518 : 38 : }
2519 : :
2520 : : // Return the number of outbound connections that are full relay (not blocks only)
2521 : 2 : int CConnman::GetFullOutboundConnCount() const
2522 : : {
2523 : 2 : AssertLockNotHeld(m_nodes_mutex);
2524 : :
2525 : 2 : int nRelevant = 0;
2526 : 2 : {
2527 : 2 : LOCK(m_nodes_mutex);
2528 [ + + ]: 6 : for (const CNode* pnode : m_nodes) {
2529 [ + - + + ]: 4 : if (pnode->fSuccessfullyConnected && pnode->IsFullOutboundConn()) ++nRelevant;
2530 : : }
2531 : 2 : }
2532 : 2 : return nRelevant;
2533 : : }
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 : 186 : int CConnman::GetExtraFullOutboundCount() const
2542 : : {
2543 : 186 : AssertLockNotHeld(m_nodes_mutex);
2544 : :
2545 : 186 : int full_outbound_peers = 0;
2546 : 186 : {
2547 : 186 : LOCK(m_nodes_mutex);
2548 [ + + ]: 497 : for (const CNode* pnode : m_nodes) {
2549 [ + - + + : 311 : if (pnode->fSuccessfullyConnected && !pnode->fDisconnect && pnode->IsFullOutboundConn()) {
+ + ]
2550 : 62 : ++full_outbound_peers;
2551 : : }
2552 : : }
2553 : 186 : }
2554 [ + + ]: 186 : return std::max(full_outbound_peers - m_max_outbound_full_relay, 0);
2555 : : }
2556 : :
2557 : 186 : int CConnman::GetExtraBlockRelayCount() const
2558 : : {
2559 : 186 : AssertLockNotHeld(m_nodes_mutex);
2560 : :
2561 : 186 : int block_relay_peers = 0;
2562 : 186 : {
2563 : 186 : LOCK(m_nodes_mutex);
2564 [ + + ]: 497 : for (const CNode* pnode : m_nodes) {
2565 [ + - + + : 311 : if (pnode->fSuccessfullyConnected && !pnode->fDisconnect && pnode->IsBlockOnlyConn()) {
+ + ]
2566 : 13 : ++block_relay_peers;
2567 : : }
2568 : : }
2569 : 186 : }
2570 [ + + ]: 186 : return std::max(block_relay_peers - m_max_outbound_block_relay, 0);
2571 : : }
2572 : :
2573 : 1128 : bool CConnman::EvictTxPeerIfFull(std::optional<NodeId> protect_peer)
2574 : : {
2575 : 1128 : int tx_inbound_peers{0};
2576 : 1128 : {
2577 : 1128 : LOCK(m_nodes_mutex);
2578 [ + + ]: 6238 : for (const CNode* pnode : m_nodes) {
2579 [ + - + + : 5110 : if (!pnode->fDisconnect && pnode->IsInboundConn() && pnode->m_relays_txs) {
+ + ]
2580 : 4868 : ++tx_inbound_peers;
2581 : : }
2582 : : }
2583 : 1128 : }
2584 [ + + ]: 1128 : if (tx_inbound_peers > m_max_inbound_full_relay) {
2585 : 6 : return AttemptToEvictConnection(/*evict_tx_relay_peer_only=*/true, protect_peer);
2586 : : }
2587 : : return true;
2588 : : }
2589 : :
2590 : 152 : std::unordered_set<Network> CConnman::GetReachableEmptyNetworks() const
2591 : : {
2592 : 152 : std::unordered_set<Network> networks{};
2593 [ + + ]: 1216 : for (int n = 0; n < NET_MAX; n++) {
2594 : 1064 : enum Network net = (enum Network)n;
2595 [ + + ]: 1064 : if (net == NET_UNROUTABLE || net == NET_INTERNAL) continue;
2596 [ + - + + : 760 : if (g_reachable_nets.Contains(net) && addrman.get().Size(net, std::nullopt) == 0) {
+ - + + ]
2597 [ + - ]: 519 : networks.insert(net);
2598 : : }
2599 : : }
2600 : 152 : return networks;
2601 : 0 : }
2602 : :
2603 : 38 : bool CConnman::MultipleManualOrFullOutboundConns(Network net) const
2604 : : {
2605 : 38 : AssertLockHeld(m_nodes_mutex);
2606 : 38 : return m_network_conn_counts[net] > 1;
2607 : : }
2608 : :
2609 : 0 : bool CConnman::MaybePickPreferredNetwork(std::optional<Network>& network)
2610 : : {
2611 : 0 : AssertLockNotHeld(m_nodes_mutex);
2612 : :
2613 : 0 : std::array<Network, 5> nets{NET_IPV4, NET_IPV6, NET_ONION, NET_I2P, NET_CJDNS};
2614 : 0 : std::shuffle(nets.begin(), nets.end(), FastRandomContext());
2615 : :
2616 : 0 : LOCK(m_nodes_mutex);
2617 [ # # ]: 0 : for (const auto net : nets) {
2618 [ # # # # : 0 : if (g_reachable_nets.Contains(net) && m_network_conn_counts[net] == 0 && addrman.get().Size(net) != 0) {
# # # # #
# ]
2619 : 0 : network = net;
2620 : 0 : return true;
2621 : : }
2622 : : }
2623 : :
2624 : : return false;
2625 : 0 : }
2626 : :
2627 : 44 : void CConnman::ThreadOpenConnections(const std::vector<std::string> connect, std::span<const std::string> seed_nodes)
2628 : : {
2629 : 44 : AssertLockNotHeld(m_nodes_mutex);
2630 : 44 : AssertLockNotHeld(m_reconnections_mutex);
2631 : 44 : AssertLockNotHeld(m_unused_i2p_sessions_mutex);
2632 : 44 : AssertLockNotHeld(m_anchors_mutex);
2633 : 44 : FastRandomContext rng;
2634 : : // Connect to specific addresses
2635 [ + + ]: 44 : if (!connect.empty())
2636 : : {
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 : : {
2642 [ + + ]: 12 : for (const std::string& strAddr : connect)
2643 : : {
2644 [ + - - + ]: 14 : OpenNetworkConnection(/*addrConnect=*/CAddress{CService{}, NODE_NONE},
2645 : : /*fCountFailure=*/false,
2646 : : /*grant_outbound=*/{},
2647 : : /*pszDest=*/strAddr.c_str(),
2648 : : /*conn_type=*/ConnectionType::MANUAL,
2649 : : /*use_v2transport=*/use_v2transport,
2650 [ + - ]: 7 : /*proxy_override=*/std::nullopt);
2651 [ + - - + ]: 7 : for (int i = 0; i < 10 && i < nLoop; i++)
2652 : : {
2653 [ # # # # ]: 0 : if (!m_interrupt_net->sleep_for(500ms)) {
2654 : : return;
2655 : : }
2656 : : }
2657 : : }
2658 [ + - - + ]: 5 : if (!m_interrupt_net->sleep_for(500ms)) {
2659 : : return;
2660 : : }
2661 [ # # ]: 0 : PerformReconnections();
2662 : 0 : }
2663 : : }
2664 : :
2665 : : // Initiate network connections
2666 : 39 : auto start = GetTime<std::chrono::microseconds>();
2667 : :
2668 : : // Minimum time before next feeler connection (in microseconds).
2669 : 39 : auto next_feeler = start + rng.rand_exp_duration(FEELER_INTERVAL);
2670 : 39 : auto next_extra_block_relay = start + rng.rand_exp_duration(EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL);
2671 [ + - ]: 39 : auto next_extra_network_peer{start + rng.rand_exp_duration(EXTRA_NETWORK_PEER_INTERVAL)};
2672 [ + - + - ]: 39 : const bool dnsseed = gArgs.GetBoolArg("-dnsseed", DEFAULT_DNSSEED);
2673 [ + - + - ]: 39 : bool add_fixed_seeds = gArgs.GetBoolArg("-fixedseeds", DEFAULT_FIXEDSEEDS);
2674 [ + - + - ]: 39 : const bool use_seednodes{!gArgs.GetArgs("-seednode").empty()};
2675 : :
2676 : 39 : auto seed_node_timer = NodeClock::now();
2677 [ + - + + : 39 : bool add_addr_fetch{addrman.get().Size() == 0 && !seed_nodes.empty()};
+ + ]
2678 : 39 : constexpr std::chrono::seconds ADD_NEXT_SEEDNODE = 10s;
2679 : :
2680 [ + + ]: 39 : if (!add_fixed_seeds) {
2681 [ + - ]: 35 : LogInfo("Fixed seeds are disabled\n");
2682 : : }
2683 : :
2684 [ + - + + ]: 191 : while (!m_interrupt_net->interrupted()) {
2685 [ + + ]: 188 : 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 : : } 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 : : }
2695 : : }
2696 : :
2697 [ + - ]: 188 : ProcessAddrFetch();
2698 : :
2699 [ + - + + ]: 188 : if (!m_interrupt_net->sleep_for(500ms)) {
2700 : : return;
2701 : : }
2702 : :
2703 [ + - ]: 152 : PerformReconnections();
2704 : :
2705 : 152 : CountingSemaphoreGrant<> grant(*semOutbound);
2706 [ + - + - ]: 152 : if (m_interrupt_net->interrupted()) {
2707 : : return;
2708 : : }
2709 : :
2710 [ + - ]: 152 : const std::unordered_set<Network> fixed_seed_networks{GetReachableEmptyNetworks()};
2711 [ + + + - ]: 152 : 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 : : }
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 : : }
2730 : 0 : }
2731 : :
2732 [ + - ]: 1 : 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 : : }
2748 : :
2749 : : //
2750 : : // Choose an address to connect to based on most recently seen
2751 : : //
2752 [ + - ]: 152 : CAddress addrConnect;
2753 : :
2754 : : // Only connect out to one peer per ipv4/ipv6 network group (/16 for IPv4).
2755 : 152 : int nOutboundFullRelay = 0;
2756 : 152 : int nOutboundBlockRelay = 0;
2757 : 152 : int outbound_privacy_network_peers = 0;
2758 [ + - ]: 152 : std::set<std::vector<unsigned char>> outbound_ipv46_peer_netgroups;
2759 : :
2760 : 152 : {
2761 [ + - ]: 152 : LOCK(m_nodes_mutex);
2762 [ + + ]: 277 : for (const CNode* pnode : m_nodes) {
2763 [ + + ]: 125 : if (pnode->IsFullOutboundConn()) nOutboundFullRelay++;
2764 [ + + ]: 125 : if (pnode->IsBlockOnlyConn()) nOutboundBlockRelay++;
2765 : :
2766 : : // Make sure our persistent outbound slots to ipv4/ipv6 peers belong to different netgroups.
2767 [ + + ]: 125 : 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 : : case ConnectionType::INBOUND:
2772 : : // Short-lived outbound connections should not affect how we select outbound
2773 : : // peers from addrman.
2774 : : case ConnectionType::ADDR_FETCH:
2775 : : case ConnectionType::FEELER:
2776 : : case ConnectionType::PRIVATE_BROADCAST:
2777 : : break;
2778 : 113 : case ConnectionType::MANUAL:
2779 : 113 : case ConnectionType::OUTBOUND_FULL_RELAY:
2780 : 113 : case ConnectionType::BLOCK_RELAY:
2781 : 226 : const CAddress address{pnode->addr};
2782 [ + + + - : 113 : 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 : 5 : ++outbound_privacy_network_peers;
2791 : : } else {
2792 [ + - + - ]: 216 : outbound_ipv46_peer_netgroups.insert(m_netgroupman.GetGroup(address));
2793 : : }
2794 : : } // no default case, so the compiler can warn about missing cases
2795 : : }
2796 : 0 : }
2797 : :
2798 [ + + + - ]: 152 : 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 : : }
2803 : : }
2804 : :
2805 : 152 : ConnectionType conn_type = ConnectionType::OUTBOUND_FULL_RELAY;
2806 : 152 : auto now = GetTime<std::chrono::microseconds>();
2807 : 152 : bool anchor = false;
2808 : 152 : bool fFeeler = false;
2809 : 152 : 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 [ + + + - : 302 : const bool have_anchors{fNetworkActive && WITH_LOCK(m_anchors_mutex, return !m_anchors.empty())};
+ + + - ]
2826 [ - + ]: 2 : if (have_anchors && (nOutboundBlockRelay < m_max_outbound_block_relay)) {
2827 : : conn_type = ConnectionType::BLOCK_RELAY;
2828 : : anchor = true;
2829 [ + + ]: 150 : } else if (nOutboundFullRelay < m_max_outbound_full_relay) {
2830 : : // OUTBOUND_FULL_RELAY
2831 [ + + ]: 8 : } else if (nOutboundBlockRelay < m_max_outbound_block_relay) {
2832 : : conn_type = ConnectionType::BLOCK_RELAY;
2833 [ + - + - ]: 6 : } else if (GetTryNewOutboundPeer()) {
2834 : : // OUTBOUND_FULL_RELAY
2835 [ + + - + ]: 6 : } 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 : 1 : next_extra_block_relay = now + rng.rand_exp_duration(EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL);
2858 : 1 : conn_type = ConnectionType::BLOCK_RELAY;
2859 [ - + ]: 5 : } else if (now > next_feeler) {
2860 : 0 : next_feeler = now + rng.rand_exp_duration(FEELER_INTERVAL);
2861 : 0 : conn_type = ConnectionType::FEELER;
2862 : 0 : fFeeler = true;
2863 [ + - ]: 5 : } else if (nOutboundFullRelay == m_max_outbound_full_relay &&
2864 [ - + ]: 5 : m_max_outbound_full_relay == MAX_OUTBOUND_FULL_RELAY_CONNECTIONS &&
2865 [ + - - + : 10 : now > next_extra_network_peer &&
- - ]
2866 [ # # ]: 0 : 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 : 0 : next_extra_network_peer = now + rng.rand_exp_duration(EXTRA_NETWORK_PEER_INTERVAL);
2874 : : } else {
2875 : : // skip to next iteration of while loop
2876 : 5 : continue;
2877 : : }
2878 : :
2879 [ + - ]: 147 : addrman.get().ResolveCollisions();
2880 : :
2881 : 147 : const auto current_time{NodeClock::now()};
2882 : 147 : int nTries = 0;
2883 [ + - ]: 147 : const auto reachable_nets{g_reachable_nets.All()};
2884 : :
2885 [ + - + - ]: 151 : while (!m_interrupt_net->interrupted()) {
2886 [ + + ]: 151 : 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 : : }
2894 : 2 : }
2895 [ + - ]: 2 : if (anchor_addr) {
2896 [ + - + - : 6 : if (!anchor_addr->IsValid() || IsLocal(*anchor_addr) || !g_reachable_nets.Contains(*anchor_addr) ||
+ - + - +
- - + ]
2897 [ + - + - : 6 : !m_msgproc->HasAllDesirableServiceFlags(anchor_addr->nServices) ||
+ - + - ]
2898 [ + - ]: 4 : 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 : : }
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 : 149 : nTries++;
2909 [ + - ]: 149 : if (nTries > 100)
2910 : : break;
2911 : :
2912 [ + - ]: 149 : CAddress addr;
2913 : 149 : NodeSeconds addr_last_try{0s};
2914 : :
2915 [ - + ]: 149 : 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 [ # # ]: 0 : std::tie(addr, addr_last_try) = addrman.get().SelectTriedCollision();
2919 : :
2920 [ # # # # ]: 0 : if (!addr.IsValid()) {
2921 : : // No tried table collisions. Select a new table address
2922 : : // for our feeler.
2923 [ # # ]: 0 : std::tie(addr, addr_last_try) = addrman.get().Select(true, reachable_nets);
2924 [ # # # # ]: 0 : } 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 : : }
2934 : : } 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 [ - + ]: 298 : std::tie(addr, addr_last_try) = preferred_net.has_value()
2940 [ - + - - : 298 : ? addrman.get().Select(false, {*preferred_net})
- - + - -
+ - - ]
2941 [ + - ]: 298 : : addrman.get().Select(false, reachable_nets);
2942 : : }
2943 : :
2944 : : // Require outbound IPv4/IPv6 connections, other than feelers, to be to distinct network groups
2945 [ + - + - : 298 : if (!fFeeler && outbound_ipv46_peer_netgroups.contains(m_netgroupman.GetGroup(addr))) {
+ + + + ]
2946 : 4 : continue;
2947 : : }
2948 : :
2949 : : // if we selected an invalid or local address, restart
2950 [ + - + + : 145 : if (!addr.IsValid() || IsLocal(addr)) {
+ - + - ]
2951 : : break;
2952 : : }
2953 : :
2954 [ + - - + ]: 19 : if (!g_reachable_nets.Contains(addr)) {
2955 : 0 : continue;
2956 : : }
2957 : :
2958 : : // only consider very recently tried nodes after 30 failed attempts
2959 [ - + - - ]: 19 : if (current_time - addr_last_try < 10min && nTries < 30) {
2960 : 0 : continue;
2961 : : }
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 [ + - + - : 19 : if (!fFeeler && !m_msgproc->HasAllDesirableServiceFlags(addr.nServices)) {
+ - ]
2967 : 0 : continue;
2968 [ - + - - ]: 19 : } else if (fFeeler && !MayHaveUsefulAddressDB(addr.nServices)) {
2969 : 0 : continue;
2970 : : }
2971 : :
2972 : : // Do not connect to bad ports, unless 50 invalid addresses have been selected already.
2973 [ + - + + : 19 : if (nTries < 50 && (addr.IsIPv4() || addr.IsIPv6()) && IsBadPort(addr.GetPort())) {
+ + + - +
- + - ]
2974 : 0 : continue;
2975 : : }
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 [ + - - + ]: 19 : 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 : : preferred_net.has_value() ? "network-specific " : "",
2983 : : ConnectionTypeAsString(conn_type), GetNetworkName(addr.GetNetwork()),
2984 : : fLogIPs ? strprintf(": %s", addr.ToStringAddrPort()) : "");
2985 : 0 : continue;
2986 : : }
2987 : :
2988 : 19 : addrConnect = addr;
2989 : : break;
2990 : 149 : }
2991 : :
2992 [ + - + + ]: 147 : if (addrConnect.IsValid()) {
2993 [ - + ]: 21 : if (fFeeler) {
2994 : : // Add small amount of random noise before connection to avoid synchronization.
2995 [ # # # # ]: 0 : if (!m_interrupt_net->sleep_for(rng.rand_uniform_duration<CThreadInterrupt::Clock>(FEELER_SLEEP_WINDOW))) {
2996 : 0 : return;
2997 : : }
2998 [ # # # # : 0 : LogDebug(BCLog::NET, "Making feeler connection to %s\n", addrConnect.ToStringAddrPort());
# # # # ]
2999 : : }
3000 : :
3001 [ - + - - : 21 : 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 [ - + ]: 21 : 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 [ + - ]: 21 : const bool use_v2transport(addrConnect.nServices & GetLocalServices() & NODE_P2P_V2);
3010 : 21 : OpenNetworkConnection(/*addrConnect=*/addrConnect,
3011 : : /*fCountFailure=*/count_failures,
3012 : : /*grant_outbound=*/std::move(grant),
3013 : : /*pszDest=*/nullptr,
3014 : : /*conn_type=*/conn_type,
3015 : : /*use_v2transport=*/use_v2transport,
3016 [ + - ]: 42 : /*proxy_override=*/std::nullopt);
3017 : : }
3018 : 152 : }
3019 : 44 : }
3020 : :
3021 : 51 : std::vector<CAddress> CConnman::GetCurrentBlockRelayOnlyConns() const
3022 : : {
3023 : 51 : AssertLockNotHeld(m_nodes_mutex);
3024 : 51 : std::vector<CAddress> ret;
3025 [ + - ]: 51 : LOCK(m_nodes_mutex);
3026 [ + + ]: 88 : for (const CNode* pnode : m_nodes) {
3027 [ + + ]: 37 : if (pnode->IsBlockOnlyConn()) {
3028 [ + - ]: 3 : ret.push_back(pnode->addr);
3029 : : }
3030 : : }
3031 : :
3032 [ + - ]: 51 : return ret;
3033 : 51 : }
3034 : :
3035 : 5730 : std::vector<AddedNodeInfo> CConnman::GetAddedNodeInfo(bool include_connected) const
3036 : : {
3037 : 5730 : AssertLockNotHeld(m_nodes_mutex);
3038 : :
3039 : 5730 : std::vector<AddedNodeInfo> ret;
3040 : :
3041 [ + - ]: 5730 : std::list<AddedNodeParams> lAddresses(0);
3042 : 5730 : {
3043 [ + - ]: 5730 : LOCK(m_added_nodes_mutex);
3044 [ - + + - ]: 5730 : ret.reserve(m_added_node_params.size());
3045 [ + - ]: 5730 : std::copy(m_added_node_params.cbegin(), m_added_node_params.cend(), std::back_inserter(lAddresses));
3046 : 0 : }
3047 : :
3048 : :
3049 : : // Build a map of all already connected addresses (by IP:port and by name) to inbound/outbound and resolved CService
3050 [ + - ]: 5730 : std::map<CService, bool> mapConnected;
3051 : 5730 : std::map<std::string, std::pair<bool, CService>> mapConnectedByName;
3052 : 5730 : {
3053 [ + - ]: 5730 : LOCK(m_nodes_mutex);
3054 [ + + ]: 11051 : for (const CNode* pnode : m_nodes) {
3055 [ + - + - ]: 5321 : if (pnode->addr.IsValid()) {
3056 [ + - ]: 5321 : mapConnected[pnode->addr] = pnode->IsInboundConn();
3057 : : }
3058 [ - + ]: 5321 : std::string addrName{pnode->m_addr_name};
3059 [ + - ]: 5321 : if (!addrName.empty()) {
3060 [ + - ]: 5321 : mapConnectedByName[std::move(addrName)] = std::make_pair(pnode->IsInboundConn(), static_cast<const CService&>(pnode->addr));
3061 : : }
3062 : 5321 : }
3063 : 0 : }
3064 : :
3065 [ + + ]: 5767 : for (const auto& addr : lAddresses) {
3066 [ + - + - : 74 : 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 : : }
3075 : 10 : addedNode.resolvedAddress = service;
3076 : 10 : addedNode.fConnected = true;
3077 : 10 : addedNode.fInbound = it->second;
3078 : : }
3079 : : } 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 : : }
3086 : 0 : addedNode.resolvedAddress = it->second.second;
3087 : 0 : addedNode.fConnected = true;
3088 : 0 : addedNode.fInbound = it->second.first;
3089 : : }
3090 : : }
3091 [ + - ]: 32 : ret.emplace_back(std::move(addedNode));
3092 : 37 : }
3093 : :
3094 : 5730 : return ret;
3095 : 5730 : }
3096 : :
3097 : 1136 : void CConnman::ThreadOpenAddedConnections()
3098 : : {
3099 : 1136 : AssertLockNotHeld(m_nodes_mutex);
3100 : 1136 : AssertLockNotHeld(m_reconnections_mutex);
3101 : 1136 : AssertLockNotHeld(m_unused_i2p_sessions_mutex);
3102 : :
3103 : 10288 : while (true)
3104 : : {
3105 : 5712 : CountingSemaphoreGrant<> grant(*semAddnode);
3106 [ + - ]: 5712 : std::vector<AddedNodeInfo> vInfo = GetAddedNodeInfo(/*include_connected=*/false);
3107 : 5712 : bool tried = false;
3108 [ + + ]: 5715 : 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 : : break;
3113 : : }
3114 : 5 : tried = true;
3115 [ + - - + ]: 10 : OpenNetworkConnection(/*addrConnect=*/CAddress{CService{}, NODE_NONE},
3116 : : /*fCountFailure=*/false,
3117 : : /*grant_outbound=*/std::move(grant),
3118 : : /*pszDest=*/info.m_params.m_added_node.c_str(),
3119 : : /*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 : : }
3125 : : // See if any reconnections are desired.
3126 [ + - ]: 5710 : PerformReconnections();
3127 : : // Retry every 60 seconds if a connection was attempted, otherwise two seconds
3128 [ + + + - : 5710 : if (!m_interrupt_net->sleep_for(tried ? 60s : 2s)) {
+ + ]
3129 : : return;
3130 : : }
3131 : 5712 : }
3132 : : }
3133 : :
3134 : : // if successful, this moves the passed grant to the constructed node
3135 : 747 : 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 : : {
3143 : 747 : AssertLockNotHeld(m_nodes_mutex);
3144 : 747 : AssertLockNotHeld(m_unused_i2p_sessions_mutex);
3145 [ - + ]: 747 : assert(conn_type != ConnectionType::INBOUND);
3146 : :
3147 : : //
3148 : : // Initiate outbound network connection
3149 : : //
3150 [ + - ]: 747 : if (m_interrupt_net->interrupted()) {
3151 : : return false;
3152 : : }
3153 [ + + ]: 747 : if (!fNetworkActive) {
3154 : : return false;
3155 : : }
3156 [ + + ]: 743 : if (!pszDest) {
3157 [ + - + - : 59 : bool banned_or_discouraged = m_banman && (m_banman->IsDiscouraged(addrConnect) || m_banman->IsBanned(addrConnect));
- + ]
3158 [ + - + - : 59 : if (IsLocal(addrConnect) || banned_or_discouraged || AlreadyConnectedToAddress(addrConnect)) {
+ + ]
3159 : 5 : return false;
3160 : : }
3161 [ + - ]: 684 : } else if (AlreadyConnectedToHost(pszDest)) {
3162 : : return false;
3163 : : }
3164 : :
3165 [ + - ]: 738 : CNode* pnode = ConnectNode(addrConnect, pszDest, fCountFailure, conn_type, use_v2transport, proxy_override);
3166 : :
3167 [ + + ]: 738 : if (!pnode)
3168 : : return false;
3169 : 710 : pnode->grantOutbound = std::move(grant_outbound);
3170 : :
3171 : 710 : m_msgproc->InitializeNode(*pnode, m_local_services);
3172 : 710 : {
3173 : 710 : LOCK(m_nodes_mutex);
3174 [ + - ]: 710 : m_nodes.push_back(pnode);
3175 : :
3176 : : // update connection count by network
3177 [ + + + - ]: 710 : if (pnode->IsManualOrFullOutboundConn()) ++m_network_conn_counts[pnode->addr.GetNetwork()];
3178 : 710 : }
3179 : :
3180 : : TRACEPOINT(net, outbound_connection,
3181 : : pnode->GetId(),
3182 : : pnode->m_addr_name.c_str(),
3183 : : pnode->ConnectionTypeAsString().c_str(),
3184 : : pnode->ConnectedThroughNetwork(),
3185 : 710 : GetNodeCount(ConnectionDirection::Out));
3186 : :
3187 : 710 : return true;
3188 : : }
3189 : :
3190 : 366 : std::optional<Network> CConnman::PrivateBroadcast::PickNetwork(std::optional<Proxy>& proxy) const
3191 : : {
3192 : 366 : prevector<4, Network> nets;
3193 : 366 : std::optional<Proxy> clearnet_proxy;
3194 [ - + ]: 366 : proxy.reset();
3195 [ + - + - ]: 366 : if (g_reachable_nets.Contains(NET_ONION)) {
3196 : 366 : nets.push_back(NET_ONION);
3197 : :
3198 [ + - + + ]: 732 : clearnet_proxy = ProxyForIPv4or6();
3199 [ + + ]: 366 : if (clearnet_proxy.has_value()) {
3200 [ + - + - ]: 43 : if (g_reachable_nets.Contains(NET_IPV4)) {
3201 : 43 : nets.push_back(NET_IPV4);
3202 : : }
3203 [ + - + - ]: 43 : if (g_reachable_nets.Contains(NET_IPV6)) {
3204 : 43 : nets.push_back(NET_IPV6);
3205 : : }
3206 : : }
3207 : : }
3208 [ + - + + ]: 366 : if (g_reachable_nets.Contains(NET_I2P)) {
3209 : 238 : nets.push_back(NET_I2P);
3210 : : }
3211 : :
3212 [ - + - + ]: 366 : if (nets.empty()) {
3213 : 0 : return std::nullopt;
3214 : : }
3215 : :
3216 [ - + + - ]: 732 : const Network net{nets[FastRandomContext{}.randrange(nets.size())]};
3217 [ + + ]: 366 : if (net == NET_IPV4 || net == NET_IPV6) {
3218 [ + - ]: 27 : proxy = clearnet_proxy;
3219 : : }
3220 : 366 : return net;
3221 : 366 : }
3222 : :
3223 : 9 : size_t CConnman::PrivateBroadcast::NumToOpen() const
3224 : : {
3225 : 9 : return m_num_to_open;
3226 : : }
3227 : :
3228 : 12646 : void CConnman::PrivateBroadcast::NumToOpenAdd(size_t n)
3229 : : {
3230 : 12646 : m_num_to_open += n;
3231 : 12646 : m_num_to_open.notify_all();
3232 : 12646 : }
3233 : :
3234 : 27 : size_t CConnman::PrivateBroadcast::NumToOpenSub(size_t n)
3235 : : {
3236 : 27 : size_t current_value{m_num_to_open.load()};
3237 : 27 : size_t new_value;
3238 : 27 : do {
3239 [ + + ]: 27 : new_value = current_value > n ? current_value - n : 0;
3240 [ - + ]: 27 : } while (!m_num_to_open.compare_exchange_strong(current_value, new_value));
3241 : 27 : return new_value;
3242 : : }
3243 : :
3244 : 371 : void CConnman::PrivateBroadcast::NumToOpenWait() const
3245 : : {
3246 : 371 : m_num_to_open.wait(0);
3247 : 371 : }
3248 : :
3249 : 366 : std::optional<Proxy> CConnman::PrivateBroadcast::ProxyForIPv4or6() const
3250 : : {
3251 [ + + ]: 366 : if (m_outbound_tor_ok_at_least_once.load()) {
3252 [ - + ]: 43 : if (const auto tor_proxy = GetProxy(NET_ONION)) {
3253 : : return tor_proxy;
3254 : 0 : }
3255 : : }
3256 : 323 : return std::nullopt;
3257 : : }
3258 : :
3259 : : Mutex NetEventsInterface::g_msgproc_mutex;
3260 : :
3261 : 1136 : void CConnman::ThreadMessageHandler()
3262 : : {
3263 : 1136 : AssertLockNotHeld(m_nodes_mutex);
3264 : :
3265 : 1136 : LOCK(NetEventsInterface::g_msgproc_mutex);
3266 : :
3267 [ + + ]: 260124 : while (!flagInterruptMsgProc)
3268 : : {
3269 : 257857 : bool fMoreWork = false;
3270 : :
3271 : 257857 : {
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 [ + - ]: 257857 : const NodesSnapshot snap{*this, /*shuffle=*/true};
3276 : :
3277 [ + + ]: 623342 : for (CNode* pnode : snap.Nodes()) {
3278 [ + + ]: 365490 : if (pnode->fDisconnect)
3279 : 56 : continue;
3280 : :
3281 : : // Receive messages
3282 [ + - ]: 365434 : bool fMoreNodeWork{m_msgproc->ProcessMessages(*pnode, flagInterruptMsgProc)};
3283 [ + + + + ]: 365434 : fMoreWork |= (fMoreNodeWork && !pnode->fPauseSend);
3284 [ + + ]: 365434 : if (flagInterruptMsgProc)
3285 : : return;
3286 : : // Send messages
3287 [ + - ]: 365429 : m_msgproc->SendMessages(*pnode);
3288 : :
3289 [ + - ]: 365429 : if (flagInterruptMsgProc)
3290 : : return;
3291 : : }
3292 [ + - ]: 257857 : }
3293 : :
3294 [ + - ]: 257852 : WAIT_LOCK(mutexMsgProc, lock);
3295 [ + + ]: 257852 : if (!fMoreWork) {
3296 [ + + + - ]: 506196 : condMsgProc.wait_until(lock, std::chrono::steady_clock::now() + std::chrono::milliseconds(100), [this]() EXCLUSIVE_LOCKS_REQUIRED(mutexMsgProc) { return fMsgProcWake; });
3297 : : }
3298 [ + - ]: 257852 : fMsgProcWake = false;
3299 : 257852 : }
3300 : 1136 : }
3301 : :
3302 : 4 : void CConnman::ThreadI2PAcceptIncoming()
3303 : : {
3304 : 4 : AssertLockNotHeld(m_nodes_mutex);
3305 : :
3306 : 4 : static constexpr auto err_wait_begin = 1s;
3307 : 4 : static constexpr auto err_wait_cap = 5min;
3308 : 4 : auto err_wait = err_wait_begin;
3309 : :
3310 : 4 : bool advertising_listen_addr = false;
3311 : 4 : i2p::Connection conn;
3312 : :
3313 : 21 : auto SleepOnFailure = [&]() {
3314 : 17 : m_interrupt_net->sleep_for(err_wait);
3315 [ + - ]: 17 : if (err_wait < err_wait_cap) {
3316 : 17 : err_wait += 1s;
3317 : : }
3318 : 21 : };
3319 : :
3320 [ + - + + ]: 21 : while (!m_interrupt_net->interrupted()) {
3321 : :
3322 [ + - + - ]: 17 : if (!m_i2p_sam_session->Listen(conn)) {
3323 [ - + - - : 17 : if (advertising_listen_addr && conn.me.IsValid()) {
- - ]
3324 [ # # ]: 0 : RemoveLocal(conn.me);
3325 : : advertising_listen_addr = false;
3326 : : }
3327 [ + - ]: 17 : SleepOnFailure();
3328 : 17 : continue;
3329 : : }
3330 : :
3331 [ # # ]: 0 : if (!advertising_listen_addr) {
3332 [ # # ]: 0 : AddLocal(conn.me, LOCAL_MANUAL);
3333 : : advertising_listen_addr = true;
3334 : : }
3335 : :
3336 [ # # # # ]: 0 : if (!m_i2p_sam_session->Accept(conn)) {
3337 [ # # ]: 0 : SleepOnFailure();
3338 : 0 : continue;
3339 : : }
3340 : :
3341 [ # # ]: 0 : CreateNodeFromAcceptedSocket(std::move(conn.sock), NetPermissionFlags::None, conn.me, conn.peer);
3342 : :
3343 : 0 : err_wait = err_wait_begin;
3344 : : }
3345 : 4 : }
3346 : :
3347 : 7 : void CConnman::ThreadPrivateBroadcast()
3348 : : {
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 [ + + ]: 373 : while (!m_interrupt_net->interrupted()) {
3354 : :
3355 [ - + ]: 371 : if (!fNetworkActive) {
3356 : 0 : m_interrupt_net->sleep_for(5s);
3357 : 0 : continue;
3358 : : }
3359 : :
3360 : 371 : CountingSemaphoreGrant<> conn_max_grant{m_private_broadcast.m_sem_conn_max}; // Would block if too many are opened.
3361 : :
3362 [ + - ]: 371 : m_private_broadcast.NumToOpenWait();
3363 : :
3364 [ + - + + ]: 371 : if (m_interrupt_net->interrupted()) {
3365 : : break;
3366 : : }
3367 : :
3368 : 366 : std::optional<Proxy> proxy;
3369 [ + - ]: 366 : const std::optional<Network> net{m_private_broadcast.PickNetwork(proxy)};
3370 [ - + ]: 366 : 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 : : }
3375 : :
3376 [ + - + - : 732 : const auto [addr, _] = addrman.get().Select(/*new_only=*/false, {net.value()});
+ - ]
3377 : :
3378 [ + - + + : 366 : if (!addr.IsValid() || IsLocal(addr)) {
+ - - + ]
3379 : 333 : ++addrman_num_bad_addresses;
3380 [ + + ]: 333 : if (addrman_num_bad_addresses > 100) {
3381 [ + - + - : 120 : LogDebug(BCLog::PRIVBROADCAST, "Connections needed but addrman keeps returning bad addresses, will retry");
+ - ]
3382 [ + - ]: 120 : m_interrupt_net->sleep_for(500ms);
3383 : : }
3384 : 333 : continue;
3385 : : }
3386 : 33 : addrman_num_bad_addresses = 0;
3387 : :
3388 [ + - ]: 33 : auto target_str{addr.ToStringAddrPort()};
3389 [ + + ]: 33 : if (proxy.has_value()) {
3390 [ + - + - ]: 28 : target_str += " through the proxy at " + proxy->ToString();
3391 : : }
3392 : :
3393 [ + - ]: 33 : const bool use_v2transport(addr.nServices & GetLocalServices() & NODE_P2P_V2);
3394 : :
3395 [ + - + + ]: 33 : if (OpenNetworkConnection(addr,
3396 : : /*fCountFailure=*/true,
3397 : : std::move(conn_max_grant),
3398 : : /*pszDest=*/nullptr,
3399 : : ConnectionType::PRIVATE_BROADCAST,
3400 : : use_v2transport,
3401 : : proxy)) {
3402 [ + - ]: 24 : const size_t remaining{m_private_broadcast.NumToOpenSub(1)};
3403 [ + - + - : 24 : LogDebug(BCLog::PRIVBROADCAST, "Socket connected to %s; remaining connections to open: %d", target_str, remaining);
+ - ]
3404 : : } else {
3405 [ + - ]: 9 : const size_t remaining{m_private_broadcast.NumToOpen()};
3406 [ - + ]: 9 : if (remaining == 0) {
3407 [ - - - - : 33 : LogDebug(BCLog::PRIVBROADCAST, "Failed to connect to %s, will not retry, no more connections needed", target_str);
- - ]
3408 : : } else {
3409 [ + - + - : 9 : LogDebug(BCLog::PRIVBROADCAST, "Failed to connect to %s, will retry to a different address; remaining connections to open: %d", target_str, remaining);
+ - ]
3410 [ + - ]: 9 : m_interrupt_net->sleep_for(100ms); // Prevent busy loop if OpenNetworkConnection() fails fast repeatedly.
3411 : : }
3412 : : }
3413 [ + + ]: 737 : }
3414 : 7 : }
3415 : :
3416 : 1153 : bool CConnman::BindListenPort(const CService& addrBind, bilingual_str& strError, NetPermissionFlags permissions)
3417 : : {
3418 : 1153 : int nOne = 1;
3419 : :
3420 : : // Create socket for listening for incoming connections
3421 : 1153 : struct sockaddr_storage sockaddr;
3422 : 1153 : socklen_t len = sizeof(sockaddr);
3423 [ - + ]: 1153 : if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
3424 : : {
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 : : }
3429 : :
3430 : 1153 : std::unique_ptr<Sock> sock = CreateSock(addrBind.GetSAFamily(), SOCK_STREAM, IPPROTO_TCP);
3431 [ - + ]: 1153 : 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 : : return false;
3435 : : }
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 [ + - - + ]: 1153 : 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 : : }
3454 : : #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 [ + + ]: 1153 : if (addrBind.IsIPv6()) {
3459 : : #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 : : }
3464 : : #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 : : }
3473 : :
3474 [ + - + + ]: 1153 : if (sock->Bind(reinterpret_cast<struct sockaddr*>(&sockaddr), len) == SOCKET_ERROR) {
3475 : 12 : int nErr = WSAGetLastError();
3476 [ + + ]: 12 : if (nErr == WSAEADDRINUSE)
3477 [ + - + - ]: 2 : strError = strprintf(_("Unable to bind to %s on this computer. %s is probably already running."), addrBind.ToStringAddrPort(), CLIENT_NAME);
3478 : : else
3479 [ + - + - : 22 : 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 : : return false;
3482 : : }
3483 [ + - + - ]: 1141 : LogInfo("Bound to %s\n", addrBind.ToStringAddrPort());
3484 : :
3485 : : // Listen for incoming connections
3486 [ + - - + ]: 1141 : if (sock->Listen(SOMAXCONN) == SOCKET_ERROR)
3487 : : {
3488 [ # # # # ]: 0 : strError = strprintf(_("Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError()));
3489 [ # # ]: 0 : LogError("%s\n", strError.original);
3490 : : return false;
3491 : : }
3492 : :
3493 [ + - ]: 1141 : vhListenSocket.emplace_back(std::move(sock), permissions);
3494 : : return true;
3495 : 1153 : }
3496 : :
3497 : 32 : void Discover()
3498 : : {
3499 [ + + ]: 32 : if (!fDiscover)
3500 : : return;
3501 : :
3502 [ + + ]: 12 : for (const CNetAddr &addr: GetLocalAddresses()) {
3503 [ + - - + : 6 : if (AddLocal(addr, LOCAL_IF) && fLogIPs) {
- - ]
3504 [ # # # # ]: 0 : LogInfo("%s: %s\n", __func__, addr.ToStringAddr());
3505 : : }
3506 : : }
3507 : : }
3508 : :
3509 : 1426 : void CConnman::SetNetworkActive(bool active)
3510 : : {
3511 : 1426 : LogInfo("%s: %s\n", __func__, active);
3512 : :
3513 [ + + ]: 1426 : if (fNetworkActive == active) {
3514 : : return;
3515 : : }
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 : : }
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 : : }
3537 : : }
3538 : :
3539 : 1413 : 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 : 1413 : std::shared_ptr<CThreadInterrupt> interrupt_net)
3546 [ + - ]: 1413 : : addrman(addrman_in)
3547 [ + - ]: 1413 : , m_netgroupman{netgroupman}
3548 : 1413 : , nSeed0(nSeed0In)
3549 : 1413 : , nSeed1(nSeed1In)
3550 [ + - - - ]: 1413 : , m_interrupt_net{interrupt_net}
3551 [ + - + - : 2826 : , m_params(params)
+ - + - ]
3552 : : {
3553 [ + - ]: 1413 : SetTryNewOutboundPeer(false);
3554 : :
3555 : 1413 : Options connOptions;
3556 [ + - ]: 1413 : Init(connOptions);
3557 [ + - ]: 1413 : SetNetworkActive(network_active);
3558 : 1413 : }
3559 : :
3560 : 1872 : NodeId CConnman::GetNewNodeId()
3561 : : {
3562 : 1872 : return nLastNodeId.fetch_add(1, std::memory_order_relaxed);
3563 : : }
3564 : :
3565 : 2 : uint16_t CConnman::GetDefaultPort(Network net) const
3566 : : {
3567 [ - + ]: 2 : return net == NET_I2P ? I2P_SAM31_PORT : m_params.GetDefaultPort();
3568 : : }
3569 : :
3570 : 762 : uint16_t CConnman::GetDefaultPort(const std::string& addr) const
3571 : : {
3572 : 762 : CNetAddr a;
3573 [ - + + - : 762 : return a.SetSpecial(addr) ? GetDefaultPort(a.GetNetwork()) : m_params.GetDefaultPort();
+ + + - +
- ]
3574 : 762 : }
3575 : :
3576 : 1153 : bool CConnman::Bind(const CService& addr_, unsigned int flags, NetPermissionFlags permissions)
3577 : : {
3578 : 1153 : const CService addr{MaybeFlipIPv6toCJDNS(addr_)};
3579 : :
3580 [ + - ]: 1153 : bilingual_str strError;
3581 [ + - + + ]: 1153 : 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 : : }
3585 : 12 : return false;
3586 : : }
3587 : :
3588 [ + - - + : 1141 : if (addr.IsRoutable() && fDiscover && !(flags & BF_DONT_ADVERTISE) && !NetPermissions::HasFlag(permissions, NetPermissionFlags::NoBan)) {
- - - - -
- ]
3589 [ # # ]: 0 : AddLocal(addr, LOCAL_BIND);
3590 : : }
3591 : :
3592 : : return true;
3593 : 1153 : }
3594 : :
3595 : 1132 : bool CConnman::InitBinds(const Options& options)
3596 : : {
3597 [ + + ]: 2245 : for (const auto& addrBind : options.vBinds) {
3598 [ + + ]: 1123 : if (!Bind(addrBind, BF_REPORT_ERROR, NetPermissionFlags::None)) {
3599 : : return false;
3600 : : }
3601 : : }
3602 [ + + ]: 1124 : for (const auto& addrBind : options.vWhiteBinds) {
3603 [ + + ]: 3 : if (!Bind(addrBind.m_service, BF_REPORT_ERROR, addrBind.m_flags)) {
3604 : : return false;
3605 : : }
3606 : : }
3607 [ + + ]: 1140 : for (const auto& addr_bind : options.onion_binds) {
3608 [ + - ]: 19 : if (!Bind(addr_bind, BF_REPORT_ERROR | BF_DONT_ADVERTISE, NetPermissionFlags::None)) {
3609 : : return false;
3610 : : }
3611 : : }
3612 [ + + ]: 1121 : 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 : : }
3625 : 4 : }
3626 : : return true;
3627 : : }
3628 : :
3629 : 1148 : bool CConnman::Start(CScheduler& scheduler, const Options& connOptions)
3630 : : {
3631 : 1148 : AssertLockNotHeld(m_total_bytes_sent_mutex);
3632 : 1148 : Init(connOptions);
3633 : :
3634 [ + + + + ]: 1148 : 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 : : }
3640 : 12 : return false;
3641 : : }
3642 : :
3643 [ + + ]: 1136 : if (connOptions.m_i2p_accept_incoming) {
3644 [ + + ]: 1119 : if (const auto i2p_sam = GetProxy(NET_I2P)) {
3645 [ + - ]: 16 : m_i2p_sam_session = std::make_unique<i2p::sam::Session>(gArgs.GetDataDirNet() / "i2p_private_key",
3646 [ + - ]: 8 : *i2p_sam, m_interrupt_net);
3647 : 1119 : }
3648 : : }
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 : 1136 : std::vector<std::string> seed_nodes = connOptions.vSeedNodes;
3652 [ + + ]: 1136 : if (!seed_nodes.empty()) {
3653 : 7 : std::shuffle(seed_nodes.begin(), seed_nodes.end(), FastRandomContext{});
3654 : : }
3655 : :
3656 [ + + ]: 1136 : if (m_use_addrman_outgoing) {
3657 : : // Load addresses from anchors.dat
3658 [ + - ]: 39 : LOCK(m_anchors_mutex);
3659 [ + - + - ]: 117 : m_anchors = ReadAnchors(gArgs.GetDataDirNet() / ANCHORS_DATABASE_FILENAME);
3660 [ - + - + ]: 39 : if (m_anchors.size() > MAX_BLOCK_RELAY_ONLY_ANCHORS) {
3661 [ # # ]: 0 : m_anchors.resize(MAX_BLOCK_RELAY_ONLY_ANCHORS);
3662 : : }
3663 [ + + ]: 39 : if (fNetworkActive) {
3664 [ - + + - : 39 : LogInfo("%i block-relay-only anchors will be tried for connections.\n", m_anchors.size());
+ - ]
3665 : : }
3666 : 39 : }
3667 : :
3668 [ + - ]: 1136 : if (m_client_interface) {
3669 [ + - ]: 1136 : m_client_interface->InitMessage(_("Starting network threads…"));
3670 : : }
3671 : :
3672 : 1136 : fAddressesInitialized = true;
3673 : :
3674 [ + - ]: 1136 : if (semOutbound == nullptr) {
3675 : : // initialize semaphore
3676 [ + + + - ]: 1139 : semOutbound = std::make_unique<std::counting_semaphore<>>(std::min(m_max_automatic_outbound, m_max_automatic_connections));
3677 : : }
3678 [ + - ]: 1136 : if (semAddnode == nullptr) {
3679 : : // initialize semaphore
3680 [ + - ]: 1136 : semAddnode = std::make_unique<std::counting_semaphore<>>(m_max_addnode);
3681 : : }
3682 : :
3683 : : //
3684 : : // Start threads
3685 : : //
3686 [ - + ]: 1136 : assert(m_msgproc);
3687 [ + - ]: 1136 : m_interrupt_net->reset();
3688 [ + - ]: 1136 : flagInterruptMsgProc = false;
3689 : :
3690 : 1136 : {
3691 [ + - ]: 1136 : LOCK(mutexMsgProc);
3692 [ + - ]: 1136 : fMsgProcWake = false;
3693 : 1136 : }
3694 : :
3695 : : // Send and receive from sockets, accept connections
3696 [ + - ]: 2272 : threadSocketHandler = std::thread(&util::TraceThread, "net", [this] { ThreadSocketHandler(); });
3697 : :
3698 [ + - + - : 1136 : if (!gArgs.GetBoolArg("-dnsseed", DEFAULT_DNSSEED))
+ + ]
3699 [ + - ]: 1123 : LogInfo("DNS seeding disabled\n");
3700 : : else
3701 [ + - ]: 26 : threadDNSAddressSeed = std::thread(&util::TraceThread, "dnsseed", [this] { ThreadDNSAddressSeed(); });
3702 : :
3703 : : // Initiate manual connections
3704 [ + - ]: 2272 : threadOpenAddedConnections = std::thread(&util::TraceThread, "addcon", [this] { ThreadOpenAddedConnections(); });
3705 : :
3706 [ + + + - ]: 1136 : 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 : : }
3712 : 0 : return false;
3713 : : }
3714 [ + + + + ]: 1136 : if (connOptions.m_use_addrman_outgoing || !connOptions.m_specified_outgoing.empty()) {
3715 : 44 : threadOpenConnections = std::thread(
3716 [ + - ]: 44 : &util::TraceThread, "opencon",
3717 [ + - + - : 176 : [this, connect = connOptions.m_specified_outgoing, seed_nodes = std::move(seed_nodes)] { ThreadOpenConnections(connect, seed_nodes); });
- + + - ]
3718 : : }
3719 : :
3720 : : // Process messages
3721 [ + - ]: 2272 : threadMessageHandler = std::thread(&util::TraceThread, "msghand", [this] { ThreadMessageHandler(); });
3722 : :
3723 [ + + ]: 1136 : if (m_i2p_sam_session) {
3724 : 4 : threadI2PAcceptIncoming =
3725 [ + - ]: 8 : std::thread(&util::TraceThread, "i2paccept", [this] { ThreadI2PAcceptIncoming(); });
3726 : : }
3727 : :
3728 [ + - + - : 1136 : if (gArgs.GetBoolArg("-privatebroadcast", DEFAULT_PRIVATE_BROADCAST)) {
+ + ]
3729 : 7 : threadPrivateBroadcast =
3730 [ + - ]: 14 : std::thread(&util::TraceThread, "privbcast", [this] { ThreadPrivateBroadcast(); });
3731 : : }
3732 : :
3733 : : // Dump network addresses
3734 [ + - ]: 1147 : scheduler.scheduleEvery([this] { DumpAddresses(); }, DUMP_PEERS_INTERVAL);
3735 : :
3736 : : // Run the ASMap Health check once and then schedule it to run every 24h.
3737 [ + - + + ]: 1136 : if (m_netgroupman.UsingASMap()) {
3738 [ + - ]: 7 : ASMapHealthCheck();
3739 [ + - ]: 14 : scheduler.scheduleEvery([this] { ASMapHealthCheck(); }, ASMAP_HEALTH_CHECK_INTERVAL);
3740 : : }
3741 : :
3742 : : return true;
3743 : 1136 : }
3744 : :
3745 : : class CNetCleanup
3746 : : {
3747 : : public:
3748 : : CNetCleanup() = default;
3749 : :
3750 : : ~CNetCleanup()
3751 : : {
3752 : : #ifdef WIN32
3753 : : // Shutdown Windows Sockets
3754 : : WSACleanup();
3755 : : #endif
3756 : : }
3757 : : };
3758 : : static CNetCleanup instance_of_cnetcleanup;
3759 : :
3760 : 2630 : void CConnman::Interrupt()
3761 : : {
3762 : 2630 : {
3763 : 2630 : LOCK(mutexMsgProc);
3764 [ + - ]: 2630 : flagInterruptMsgProc = true;
3765 : 2630 : }
3766 : 2630 : condMsgProc.notify_all();
3767 : :
3768 : 2630 : (*m_interrupt_net)();
3769 : 2630 : g_socks5_interrupt();
3770 : :
3771 [ + + ]: 2630 : if (semOutbound) {
3772 [ + + ]: 13611 : for (int i=0; i<m_max_automatic_outbound; i++) {
3773 : 12475 : semOutbound->release();
3774 : : }
3775 : : }
3776 : :
3777 [ + + ]: 2630 : if (semAddnode) {
3778 [ + + ]: 10224 : for (int i=0; i<m_max_addnode; i++) {
3779 : 9088 : semAddnode->release();
3780 : : }
3781 : : }
3782 : :
3783 : 2630 : m_private_broadcast.m_sem_conn_max.release();
3784 : 2630 : m_private_broadcast.NumToOpenAdd(1); // Just unblock NumToOpenWait() to be able to continue with shutdown.
3785 : 2630 : }
3786 : :
3787 : 2630 : void CConnman::StopThreads()
3788 : : {
3789 [ + + ]: 2630 : if (threadPrivateBroadcast.joinable()) {
3790 : 7 : threadPrivateBroadcast.join();
3791 : : }
3792 [ + + ]: 2630 : if (threadI2PAcceptIncoming.joinable()) {
3793 : 4 : threadI2PAcceptIncoming.join();
3794 : : }
3795 [ + + ]: 2630 : if (threadMessageHandler.joinable())
3796 : 1136 : threadMessageHandler.join();
3797 [ + + ]: 2630 : if (threadOpenConnections.joinable())
3798 : 44 : threadOpenConnections.join();
3799 [ + + ]: 2630 : if (threadOpenAddedConnections.joinable())
3800 : 1136 : threadOpenAddedConnections.join();
3801 [ + + ]: 2630 : if (threadDNSAddressSeed.joinable())
3802 : 13 : threadDNSAddressSeed.join();
3803 [ + + ]: 2630 : if (threadSocketHandler.joinable())
3804 : 1136 : threadSocketHandler.join();
3805 : 2630 : }
3806 : :
3807 : 2630 : void CConnman::StopNodes()
3808 : : {
3809 : 2630 : AssertLockNotHeld(m_nodes_mutex);
3810 : 2630 : AssertLockNotHeld(m_reconnections_mutex);
3811 : 2630 : AssertLockNotHeld(m_anchors_mutex);
3812 : :
3813 [ + + ]: 2630 : if (fAddressesInitialized) {
3814 : 1136 : DumpAddresses();
3815 : 1136 : fAddressesInitialized = false;
3816 : :
3817 [ + + ]: 1136 : if (m_use_addrman_outgoing) {
3818 : : // Anchor connections are only dumped during clean shutdown.
3819 : 39 : std::vector<CAddress> anchors_to_dump = GetCurrentBlockRelayOnlyConns();
3820 : 39 : {
3821 [ + - ]: 39 : LOCK(m_anchors_mutex);
3822 [ + + + + ]: 39 : if (!fNetworkActive && !m_anchors.empty()) {
3823 [ + - ]: 2 : anchors_to_dump = m_anchors;
3824 : : }
3825 : 0 : }
3826 [ - + - + ]: 39 : if (anchors_to_dump.size() > MAX_BLOCK_RELAY_ONLY_ANCHORS) {
3827 [ # # ]: 0 : anchors_to_dump.resize(MAX_BLOCK_RELAY_ONLY_ANCHORS);
3828 : : }
3829 [ + - + - ]: 117 : DumpAnchors(gArgs.GetDataDirNet() / ANCHORS_DATABASE_FILENAME, anchors_to_dump);
3830 : 39 : }
3831 : : }
3832 : :
3833 : : // Delete peer connections.
3834 : 2630 : std::vector<CNode*> nodes;
3835 [ + - + - ]: 5260 : WITH_LOCK(m_nodes_mutex, nodes.swap(m_nodes));
3836 [ + + ]: 3418 : for (CNode* pnode : nodes) {
3837 [ + - + - : 788 : LogDebug(BCLog::NET, "Stopping node, %s", pnode->DisconnectMsg());
+ - + - ]
3838 [ + - ]: 788 : pnode->CloseSocketDisconnect();
3839 [ + - ]: 788 : DeleteNode(pnode);
3840 : : }
3841 : :
3842 [ - + ]: 2630 : for (CNode* pnode : m_nodes_disconnected) {
3843 [ # # ]: 0 : DeleteNode(pnode);
3844 : : }
3845 : 2630 : m_nodes_disconnected.clear();
3846 [ + - + - ]: 5260 : WITH_LOCK(m_reconnections_mutex, m_reconnections.clear());
3847 : 2630 : vhListenSocket.clear();
3848 [ + + ]: 2630 : semOutbound.reset();
3849 [ + + ]: 3766 : semAddnode.reset();
3850 : 2630 : }
3851 : :
3852 : 1872 : void CConnman::DeleteNode(CNode* pnode)
3853 : : {
3854 [ - + ]: 1872 : assert(pnode);
3855 : 1872 : m_msgproc->FinalizeNode(*pnode);
3856 : 1872 : delete pnode;
3857 : 1872 : }
3858 : :
3859 [ + - ]: 1413 : CConnman::~CConnman()
3860 : : {
3861 : 1413 : Interrupt();
3862 : 1413 : Stop();
3863 : 2826 : }
3864 : :
3865 : 495 : std::vector<CAddress> CConnman::GetAddressesUnsafe(size_t max_addresses, size_t max_pct, std::optional<Network> network, const bool filtered) const
3866 : : {
3867 : 495 : std::vector<CAddress> addresses = addrman.get().GetAddr(max_addresses, max_pct, network, filtered);
3868 [ + - ]: 495 : if (m_banman) {
3869 [ + - + - : 34959 : std::erase_if(addresses, [this](const CAddress& addr) { return m_banman->IsDiscouraged(addr) || m_banman->IsBanned(addr); });
- + ]
3870 : : }
3871 : 495 : return addresses;
3872 : 0 : }
3873 : :
3874 : 1055 : std::vector<CAddress> CConnman::GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct)
3875 : : {
3876 : 1055 : uint64_t network_id = requestor.m_network_key;
3877 : 1055 : const auto current_time = GetTime<std::chrono::microseconds>();
3878 [ + - ]: 1055 : auto r = m_addr_response_caches.emplace(network_id, CachedAddrResponse{});
3879 [ + + ]: 1055 : CachedAddrResponse& cache_entry = r.first->second;
3880 [ + + ]: 1055 : if (cache_entry.m_cache_entry_expiration < current_time) { // If emplace() added new one it has expiration 0.
3881 : 407 : 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 : 407 : cache_entry.m_cache_entry_expiration = current_time +
3907 : 407 : 21h + FastRandomContext().randrange<std::chrono::microseconds>(6h);
3908 : : }
3909 : 1055 : return cache_entry.m_addrs_response_cache;
3910 : : }
3911 : :
3912 : 15 : bool CConnman::AddNode(const AddedNodeParams& add)
3913 : : {
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 [ + + ]: 27 : for (const auto& it : m_added_node_params) {
3919 [ + + + - : 50 : 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 : : }
3921 : :
3922 [ + - ]: 9 : m_added_node_params.push_back(add);
3923 : : return true;
3924 : 15 : }
3925 : :
3926 : 4 : bool CConnman::RemoveAddedNode(std::string_view node)
3927 : : {
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 : : }
3934 : : }
3935 : : return false;
3936 : 4 : }
3937 : :
3938 : 25 : bool CConnman::AddedNodesContain(const CAddress& addr) const
3939 : : {
3940 : 25 : AssertLockNotHeld(m_added_nodes_mutex);
3941 : 25 : const std::string addr_str{addr.ToStringAddr()};
3942 [ + - ]: 25 : const std::string addr_port_str{addr.ToStringAddrPort()};
3943 [ + - ]: 25 : LOCK(m_added_nodes_mutex);
3944 [ - + ]: 25 : return (m_added_node_params.size() < 24 // bound the query to a reasonable limit
3945 [ + - + + ]: 25 : && std::any_of(m_added_node_params.cbegin(), m_added_node_params.cend(),
3946 [ + - + + : 45 : [&](const auto& p) { return p.m_added_node == addr_str || p.m_added_node == addr_port_str; }));
+ - ]
3947 : 25 : }
3948 : :
3949 : 3076 : size_t CConnman::GetNodeCount(ConnectionDirection flags) const
3950 : : {
3951 : 3076 : LOCK(m_nodes_mutex);
3952 [ + + ]: 3076 : if (flags == ConnectionDirection::Both) // Shortcut if we want total
3953 [ - + ]: 1030 : return m_nodes.size();
3954 : :
3955 : 2046 : int nNum = 0;
3956 [ + + ]: 3182 : for (const auto& pnode : m_nodes) {
3957 [ + + + + ]: 1802 : if (flags & (pnode->IsInboundConn() ? ConnectionDirection::In : ConnectionDirection::Out)) {
3958 : 568 : nNum++;
3959 : : }
3960 : : }
3961 : :
3962 : 2046 : return nNum;
3963 : 3076 : }
3964 : :
3965 : :
3966 : 0 : std::map<CNetAddr, LocalServiceInfo> CConnman::getNetLocalAddresses() const
3967 : : {
3968 : 0 : LOCK(g_maplocalhost_mutex);
3969 [ # # # # ]: 0 : return mapLocalHost;
3970 : 0 : }
3971 : :
3972 : 22442 : uint32_t CConnman::GetMappedAS(const CNetAddr& addr) const
3973 : : {
3974 : 22442 : return m_netgroupman.GetMappedAS(addr);
3975 : : }
3976 : :
3977 : 10236 : void CConnman::GetNodeStats(std::vector<CNodeStats>& vstats) const
3978 : : {
3979 : 10236 : AssertLockNotHeld(m_nodes_mutex);
3980 : :
3981 : 10236 : vstats.clear();
3982 : 10236 : LOCK(m_nodes_mutex);
3983 [ - + + - ]: 10236 : vstats.reserve(m_nodes.size());
3984 [ + + ]: 29104 : for (CNode* pnode : m_nodes) {
3985 [ + - ]: 18868 : vstats.emplace_back();
3986 [ + - ]: 18868 : pnode->CopyStats(vstats.back());
3987 [ + - ]: 18868 : vstats.back().m_mapped_as = GetMappedAS(pnode->addr);
3988 : : }
3989 : 10236 : }
3990 : :
3991 : 4 : bool CConnman::DisconnectNode(std::string_view strNode)
3992 : : {
3993 : 4 : LOCK(m_nodes_mutex);
3994 [ - + ]: 10 : 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 : : }
4001 : : return false;
4002 : 4 : }
4003 : :
4004 : 33 : bool CConnman::DisconnectNode(const CSubNet& subnet, bool disconnect_private_broadcast)
4005 : : {
4006 : 33 : AssertLockNotHeld(m_nodes_mutex);
4007 : 33 : bool disconnected = false;
4008 : 33 : LOCK(m_nodes_mutex);
4009 [ + + ]: 50 : for (CNode* pnode : m_nodes) {
4010 [ + - + + : 17 : if (subnet.Match(pnode->addr) && (disconnect_private_broadcast || !pnode->IsPrivateBroadcastConn())) {
+ + + + ]
4011 [ + - + - : 22 : 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 : : }
4015 : : }
4016 [ + - ]: 33 : return disconnected;
4017 : 33 : }
4018 : :
4019 : 16 : bool CConnman::DisconnectNode(const CNetAddr& addr)
4020 : : {
4021 : 16 : AssertLockNotHeld(m_nodes_mutex);
4022 [ + - ]: 16 : return DisconnectNode(CSubNet(addr));
4023 : : }
4024 : :
4025 : 126 : bool CConnman::DisconnectNode(NodeId id)
4026 : : {
4027 : 126 : LOCK(m_nodes_mutex);
4028 [ + - ]: 186 : for(CNode* pnode : m_nodes) {
4029 [ + + ]: 186 : if (id == pnode->GetId()) {
4030 [ + - + - : 126 : LogDebug(BCLog::NET, "disconnect by id, %s", pnode->DisconnectMsg());
+ - + - ]
4031 : 126 : pnode->fDisconnect = true;
4032 : 126 : return true;
4033 : : }
4034 : : }
4035 : : return false;
4036 : 126 : }
4037 : :
4038 : 218182 : void CConnman::RecordBytesRecv(uint64_t bytes)
4039 : : {
4040 : 218182 : nTotalBytesRecv += bytes;
4041 : 218182 : }
4042 : :
4043 : 152630 : void CConnman::RecordBytesSent(uint64_t bytes)
4044 : : {
4045 : 152630 : AssertLockNotHeld(m_total_bytes_sent_mutex);
4046 : 152630 : LOCK(m_total_bytes_sent_mutex);
4047 : :
4048 : 152630 : nTotalBytesSent += bytes;
4049 : :
4050 : 152630 : const auto now = GetTime<std::chrono::seconds>();
4051 [ + + ]: 152630 : if (nMaxOutboundCycleStartTime + MAX_UPLOAD_TIMEFRAME < now)
4052 : : {
4053 : : // timeframe expired, reset cycle
4054 : 594 : nMaxOutboundCycleStartTime = now;
4055 : 594 : nMaxOutboundTotalBytesSentInCycle = 0;
4056 : : }
4057 : :
4058 [ + - ]: 152630 : nMaxOutboundTotalBytesSentInCycle += bytes;
4059 : 152630 : }
4060 : :
4061 : 19 : uint64_t CConnman::GetMaxOutboundTarget() const
4062 : : {
4063 : 19 : AssertLockNotHeld(m_total_bytes_sent_mutex);
4064 : 19 : LOCK(m_total_bytes_sent_mutex);
4065 [ + - ]: 19 : return nMaxOutboundLimit;
4066 : 19 : }
4067 : :
4068 : 19 : std::chrono::seconds CConnman::GetMaxOutboundTimeframe() const
4069 : : {
4070 : 19 : return MAX_UPLOAD_TIMEFRAME;
4071 : : }
4072 : :
4073 : 19 : std::chrono::seconds CConnman::GetMaxOutboundTimeLeftInCycle() const
4074 : : {
4075 : 19 : AssertLockNotHeld(m_total_bytes_sent_mutex);
4076 : 19 : LOCK(m_total_bytes_sent_mutex);
4077 [ + - ]: 19 : return GetMaxOutboundTimeLeftInCycle_();
4078 : 19 : }
4079 : :
4080 : 1127 : std::chrono::seconds CConnman::GetMaxOutboundTimeLeftInCycle_() const
4081 : : {
4082 : 1127 : AssertLockHeld(m_total_bytes_sent_mutex);
4083 : :
4084 [ + + ]: 1127 : if (nMaxOutboundLimit == 0)
4085 : 13 : return 0s;
4086 : :
4087 [ + + ]: 1114 : if (nMaxOutboundCycleStartTime.count() == 0)
4088 : 4 : return MAX_UPLOAD_TIMEFRAME;
4089 : :
4090 : 1110 : const std::chrono::seconds cycleEndTime = nMaxOutboundCycleStartTime + MAX_UPLOAD_TIMEFRAME;
4091 : 1110 : const auto now = GetTime<std::chrono::seconds>();
4092 [ - + ]: 1110 : return (cycleEndTime < now) ? 0s : cycleEndTime - now;
4093 : : }
4094 : :
4095 : 26858 : bool CConnman::OutboundTargetReached(bool historicalBlockServingLimit) const
4096 : : {
4097 : 26858 : AssertLockNotHeld(m_total_bytes_sent_mutex);
4098 : 26858 : LOCK(m_total_bytes_sent_mutex);
4099 [ + + ]: 26858 : if (nMaxOutboundLimit == 0)
4100 : : return false;
4101 : :
4102 [ + + ]: 1116 : if (historicalBlockServingLimit)
4103 : : {
4104 : : // keep a large enough buffer to at least relay each block once
4105 [ + - ]: 1108 : const std::chrono::seconds timeLeftInCycle = GetMaxOutboundTimeLeftInCycle_();
4106 : 1108 : const uint64_t buffer = timeLeftInCycle / std::chrono::minutes{10} * MAX_BLOCK_SERIALIZED_SIZE;
4107 [ + + + + ]: 1108 : if (buffer >= nMaxOutboundLimit || nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit - buffer)
4108 : 827 : return true;
4109 : : }
4110 [ + + ]: 8 : else if (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit)
4111 : 3 : return true;
4112 : :
4113 : : return false;
4114 : 26858 : }
4115 : :
4116 : 19 : uint64_t CConnman::GetOutboundTargetBytesLeft() const
4117 : : {
4118 : 19 : AssertLockNotHeld(m_total_bytes_sent_mutex);
4119 : 19 : LOCK(m_total_bytes_sent_mutex);
4120 [ + + ]: 19 : if (nMaxOutboundLimit == 0)
4121 : : return 0;
4122 : :
4123 [ + + ]: 6 : return (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit) ? 0 : nMaxOutboundLimit - nMaxOutboundTotalBytesSentInCycle;
4124 : 19 : }
4125 : :
4126 : 19 : uint64_t CConnman::GetTotalBytesRecv() const
4127 : : {
4128 : 19 : return nTotalBytesRecv;
4129 : : }
4130 : :
4131 : 19 : uint64_t CConnman::GetTotalBytesSent() const
4132 : : {
4133 : 19 : AssertLockNotHeld(m_total_bytes_sent_mutex);
4134 : 19 : LOCK(m_total_bytes_sent_mutex);
4135 [ + - ]: 19 : return nTotalBytesSent;
4136 : 19 : }
4137 : :
4138 : 5546 : ServiceFlags CConnman::GetLocalServices() const
4139 : : {
4140 : 5546 : return m_local_services;
4141 : : }
4142 : :
4143 : 1922 : static util::NotNullUniquePtr<Transport> MakeTransport(NodeId id, bool use_v2transport, bool inbound) noexcept
4144 : : {
4145 [ + + ]: 1922 : if (use_v2transport) {
4146 [ - + - + ]: 213 : return util::NotNull{std::make_unique<V2Transport>(id, /*initiating=*/!inbound)};
4147 : : } else {
4148 [ - + - + ]: 1709 : return util::NotNull{std::make_unique<V1Transport>(id)};
4149 : : }
4150 : : }
4151 : :
4152 : 1922 : 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 : 1922 : CNodeOptions&& node_opts)
4163 : 1922 : : m_transport{MakeTransport(idIn, node_opts.use_v2transport, conn_type_in == ConnectionType::INBOUND)},
4164 : 1922 : m_permission_flags{node_opts.permission_flags},
4165 [ + + ]: 1922 : m_sock{sock},
4166 : 1922 : m_connected{NodeClock::now()},
4167 [ - - ]: 1922 : m_proxy_override{std::move(node_opts.proxy_override)},
4168 : 1922 : addr{addrIn},
4169 : 1922 : addrBind{addrBindIn},
4170 [ + + + - ]: 1922 : m_addr_name{addrNameIn.empty() ? addr.ToStringAddrPort() : addrNameIn},
4171 [ - + ]: 1922 : m_dest(addrNameIn),
4172 : 1922 : m_inbound_onion{inbound_onion},
4173 [ + - ]: 1922 : m_prefer_evict{node_opts.prefer_evict},
4174 : 1922 : nKeyedNetGroup{nKeyedNetGroupIn},
4175 : 1922 : m_network_key{network_key},
4176 : 1922 : m_conn_type{conn_type_in},
4177 : 1922 : id{idIn},
4178 : 1922 : nLocalHostNonce{nLocalHostNonceIn},
4179 [ + - ]: 1922 : m_recv_flood_size{node_opts.recv_flood_size},
4180 [ + - + - : 3844 : m_i2p_sam_session{std::move(node_opts.i2p_sam_session)}
+ + ]
4181 : : {
4182 [ + + + - ]: 1922 : if (inbound_onion) assert(conn_type_in == ConnectionType::INBOUND);
4183 : :
4184 [ + + ]: 71114 : for (const auto& msg : ALL_NET_MESSAGE_TYPES) {
4185 [ + - ]: 69192 : mapRecvBytesPerMsgType[msg] = 0;
4186 : : }
4187 [ + - ]: 1922 : mapRecvBytesPerMsgType[NET_MESSAGE_TYPE_OTHER] = 0;
4188 : :
4189 [ + + ]: 1922 : if (fLogIPs) {
4190 [ + - + - : 9 : LogDebug(BCLog::NET, "Added connection to %s peer=%d\n", m_addr_name, id);
+ - ]
4191 : : } else {
4192 [ + - + - : 1913 : LogDebug(BCLog::NET, "Added connection peer=%d\n", id);
+ - ]
4193 : : }
4194 [ - - ]: 1922 : }
4195 : :
4196 : 112659 : void CNode::MarkReceivedMsgsForProcessing()
4197 : : {
4198 : 112659 : AssertLockNotHeld(m_msg_process_queue_mutex);
4199 : :
4200 : 112659 : size_t nSizeAdded = 0;
4201 [ + + ]: 259384 : for (const auto& msg : vRecvMsg) {
4202 : : // vRecvMsg contains only completed CNetMessage
4203 : : // the single possible partially deserialized message are held by TransportDeserializer
4204 : 146725 : nSizeAdded += msg.GetMemoryUsage();
4205 : : }
4206 : :
4207 : 112659 : LOCK(m_msg_process_queue_mutex);
4208 : 112659 : m_msg_process_queue.splice(m_msg_process_queue.end(), vRecvMsg);
4209 : 112659 : m_msg_process_queue_size += nSizeAdded;
4210 [ + - ]: 112659 : fPauseRecv = m_msg_process_queue_size > m_recv_flood_size;
4211 : 112659 : }
4212 : :
4213 : 362321 : std::optional<std::pair<CNetMessage, bool>> CNode::PollMessage()
4214 : : {
4215 : 362321 : LOCK(m_msg_process_queue_mutex);
4216 [ + + ]: 362321 : if (m_msg_process_queue.empty()) return std::nullopt;
4217 : :
4218 : 146559 : std::list<CNetMessage> msgs;
4219 : : // Just take one message
4220 : 146559 : msgs.splice(msgs.begin(), m_msg_process_queue, m_msg_process_queue.begin());
4221 : 146559 : m_msg_process_queue_size -= msgs.front().GetMemoryUsage();
4222 : 146559 : fPauseRecv = m_msg_process_queue_size > m_recv_flood_size;
4223 : :
4224 : 293118 : return std::make_pair(std::move(msgs.front()), !m_msg_process_queue.empty());
4225 : 146559 : }
4226 : :
4227 : 83871 : bool CConnman::NodeFullyConnected(const CNode* pnode)
4228 : : {
4229 [ + - + + : 83871 : return pnode && pnode->fSuccessfullyConnected && !pnode->fDisconnect;
+ + ]
4230 : : }
4231 : :
4232 : : /// Private broadcast connections only need to send certain message types.
4233 : : /// Other messages are not needed and may degrade privacy.
4234 : 106 : static bool IsOutboundMessageAllowedInPrivateBroadcast(std::string_view type) noexcept
4235 : : {
4236 : 187 : return type == NetMsgType::VERSION ||
4237 [ + + ]: 81 : type == NetMsgType::VERACK ||
4238 [ + + ]: 60 : type == NetMsgType::INV ||
4239 [ + + + + ]: 146 : type == NetMsgType::TX ||
4240 [ + - ]: 20 : type == NetMsgType::PING;
4241 : : }
4242 : :
4243 : 152411 : void CConnman::PushMessage(CNode* pnode, CSerializedNetMsg&& msg)
4244 : : {
4245 : 152411 : AssertLockNotHeld(m_total_bytes_sent_mutex);
4246 : :
4247 [ + + - + : 152411 : 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 : : }
4251 : :
4252 [ + + + + : 152411 : if (!m_private_broadcast.m_outbound_tor_ok_at_least_once.load() && !pnode->IsInboundConn() &&
+ + ]
4253 [ + + + + : 211982 : 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 : : }
4258 : :
4259 [ - + ]: 152411 : size_t nMessageSize = msg.data.size();
4260 [ + - ]: 152411 : LogDebug(BCLog::NET, "sending %s (%d bytes) peer=%d\n", msg.m_type, nMessageSize, pnode->GetId());
4261 [ + + ]: 152411 : if (m_capture_messages) {
4262 [ - + ]: 20 : CaptureMessage(pnode->addr, msg.m_type, msg.data, /*is_incoming=*/false);
4263 : : }
4264 : :
4265 : : TRACEPOINT(net, outbound_message,
4266 : : pnode->GetId(),
4267 : : pnode->m_addr_name.c_str(),
4268 : : pnode->ConnectionTypeAsString().c_str(),
4269 : : msg.m_type.c_str(),
4270 : : msg.data.size(),
4271 : : msg.data.data()
4272 : 152411 : );
4273 : :
4274 : 152411 : size_t nBytesSent = 0;
4275 : 152411 : {
4276 : 152411 : 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 [ + + ]: 152411 : const auto& [to_send, more, _msg_type] =
4280 [ + + ]: 152411 : pnode->m_transport->GetBytesToSend(/*have_next_message=*/true);
4281 [ + + - + ]: 152411 : const bool queue_was_empty{to_send.empty() && pnode->vSendMsg.empty()};
4282 : :
4283 : : // Update memory usage of send buffer.
4284 : 152411 : pnode->m_send_memusage += msg.GetMemoryUsage();
4285 [ + + + + ]: 152411 : if (pnode->m_send_memusage + pnode->m_transport->GetSendMemoryUsage() > nSendBufferMaxSize && !pnode->fPauseSend) {
4286 : 1784 : pnode->m_pause_send_since = NodeClock::now();
4287 : 1784 : pnode->fPauseSend = true;
4288 : : }
4289 : : // Move message to vSendMsg queue.
4290 [ + - ]: 152411 : 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 [ + + + + ]: 152411 : if (queue_was_empty && more) {
4300 [ + - ]: 151733 : std::tie(nBytesSent, std::ignore) = SocketSendData(*pnode);
4301 : : }
4302 : 152411 : }
4303 [ + + ]: 152411 : if (nBytesSent) RecordBytesSent(nBytesSent);
4304 : : }
4305 : :
4306 : 1010 : bool CConnman::ForNode(NodeId id, std::function<bool(CNode* pnode)> func)
4307 : : {
4308 : 1010 : AssertLockNotHeld(m_nodes_mutex);
4309 : :
4310 : 1010 : CNode* found = nullptr;
4311 : 1010 : LOCK(m_nodes_mutex);
4312 [ + + ]: 1381 : for (auto&& pnode : m_nodes) {
4313 [ + + ]: 1316 : if(pnode->GetId() == id) {
4314 : : found = pnode;
4315 : : break;
4316 : : }
4317 : : }
4318 [ + + + - : 1011 : return found != nullptr && NodeFullyConnected(found) && func(found);
+ - + - +
+ + - ]
4319 : 1010 : }
4320 : :
4321 : 5670 : CSipHasher CConnman::GetDeterministicRandomizer(uint64_t id) const
4322 : : {
4323 : 5670 : return CSipHasher(nSeed0, nSeed1).Write(id);
4324 : : }
4325 : :
4326 : 1872 : uint64_t CConnman::CalculateKeyedNetGroup(const CNetAddr& address) const
4327 : : {
4328 : 1872 : std::vector<unsigned char> vchNetGroup(m_netgroupman.GetGroup(address));
4329 : :
4330 [ + - + - : 3744 : return GetDeterministicRandomizer(RANDOMIZER_ID_NETGROUP).Write(vchNetGroup).Finalize();
+ - ]
4331 : 1872 : }
4332 : :
4333 : 5862 : void CConnman::PerformReconnections()
4334 : : {
4335 : 5862 : AssertLockNotHeld(m_nodes_mutex);
4336 : 5862 : AssertLockNotHeld(m_reconnections_mutex);
4337 : 5862 : AssertLockNotHeld(m_unused_i2p_sessions_mutex);
4338 : 5878 : while (true) {
4339 : : // Move first element of m_reconnections to todo (avoiding an allocation inside the lock).
4340 [ + - ]: 5870 : decltype(m_reconnections) todo;
4341 : 5870 : {
4342 [ + - ]: 5870 : LOCK(m_reconnections_mutex);
4343 [ + + ]: 5870 : if (m_reconnections.empty()) break;
4344 [ + - ]: 8 : todo.splice(todo.end(), m_reconnections, m_reconnections.begin());
4345 : 5862 : }
4346 : :
4347 [ + + ]: 8 : auto& item = *todo.begin();
4348 : 16 : 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 : : /*fCountFailure=*/false,
4354 [ + - ]: 8 : std::move(item.grant),
4355 : 3 : item.destination.empty() ? nullptr : item.destination.c_str(),
4356 : : item.conn_type,
4357 : 8 : item.use_v2transport,
4358 [ + + ]: 8 : item.proxy_override);
4359 : 8 : }
4360 : 5862 : }
4361 : :
4362 : 7 : void CConnman::ASMapHealthCheck()
4363 : : {
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 [ # # ]: 0 : [](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 : 23 : static void CaptureMessageToFile(const CAddress& addr,
4377 : : const std::string& msg_type,
4378 : : std::span<const unsigned char> data,
4379 : : bool is_incoming)
4380 : : {
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 [ - + + - : 115 : fs::path base_path = gArgs.GetDataDirNet() / "message_capture" / fs::u8path(clean_addr);
+ - + - ]
4392 [ + - ]: 23 : fs::create_directories(base_path);
4393 : :
4394 [ + + + - ]: 69 : fs::path path = base_path / (is_incoming ? "msgs_recv.dat" : "msgs_sent.dat");
4395 [ + - + - ]: 46 : 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 [ + - ]: 224 : f << uint8_t{'\0'};
4401 : : }
4402 [ + - ]: 23 : uint32_t size = data.size();
4403 [ + - ]: 23 : ser_writedata32(f, size);
4404 [ + - ]: 23 : f << data;
4405 : :
4406 [ + - - + ]: 46 : 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 : : }
4410 : 69 : }
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;
|