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