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