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