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