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