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