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