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