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