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