Bitcoin ABC 0.34.3
P2P Digital Currency
Loading...
Searching...
No Matches
net.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2019 The Bitcoin Core developers
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#if defined(HAVE_CONFIG_H)
7#include <config/bitcoin-config.h>
8#endif
9
10#include <net.h>
11
12#include <addrdb.h>
13#include <addrman.h>
14#include <avalanche/avalanche.h>
15#include <banman.h>
16#include <clientversion.h>
17#include <common/args.h>
18#include <common/netif.h>
19#include <compat/compat.h>
20#include <config.h>
21#include <consensus/consensus.h>
22#include <crypto/sha256.h>
23#include <dnsseeds.h>
24#include <i2p.h>
25#include <logging.h>
26#include <netaddress.h>
27#include <netbase.h>
28#include <node/eviction.h>
29#include <node/ui_interface.h>
30#include <protocol.h>
31#include <random.h>
32#include <scheduler.h>
33#include <util/fs.h>
34#include <util/sock.h>
35#include <util/strencodings.h>
36#include <util/thread.h>
38#include <util/trace.h>
39#include <util/translation.h>
40
41#ifdef WIN32
42#include <cstring>
43#else
44#include <fcntl.h>
45#endif
46
47#ifdef USE_POLL
48#include <poll.h>
49#endif
50
51#include <algorithm>
52#include <array>
53#include <cmath>
54#include <cstdint>
55#include <functional>
56#include <limits>
57#include <optional>
58#include <unordered_map>
59
61static constexpr size_t MAX_BLOCK_RELAY_ONLY_ANCHORS = 2;
62static_assert(MAX_BLOCK_RELAY_ONLY_ANCHORS <=
63 static_cast<size_t>(MAX_BLOCK_RELAY_ONLY_CONNECTIONS),
64 "MAX_BLOCK_RELAY_ONLY_ANCHORS must not exceed "
65 "MAX_BLOCK_RELAY_ONLY_CONNECTIONS.");
67const char *const ANCHORS_DATABASE_FILENAME = "anchors.dat";
68
69// How often to dump addresses to peers.dat
70static constexpr std::chrono::minutes DUMP_PEERS_INTERVAL{15};
71
75static constexpr int DNSSEEDS_TO_QUERY_AT_ONCE = 3;
76
87static constexpr std::chrono::seconds DNSSEEDS_DELAY_FEW_PEERS{11};
88static constexpr std::chrono::minutes DNSSEEDS_DELAY_MANY_PEERS{5};
89// "many" vs "few" peers
90static constexpr int DNSSEEDS_DELAY_PEER_THRESHOLD = 1000;
91
93static constexpr std::chrono::seconds MAX_UPLOAD_TIMEFRAME{60 * 60 * 24};
94
95// A random time period (0 to 1 seconds) is added to feeler connections to
96// prevent synchronization.
97static constexpr auto FEELER_SLEEP_WINDOW{1s};
98
102 BF_EXPLICIT = (1U << 0),
103 BF_REPORT_ERROR = (1U << 1),
108 BF_DONT_ADVERTISE = (1U << 2),
109};
110
111// The set of sockets cannot be modified while waiting
112// The sleep time needs to be small to avoid new sockets stalling
113static const uint64_t SELECT_TIMEOUT_MILLISECONDS = 50;
114
115const std::string NET_MESSAGE_TYPE_OTHER = "*other*";
116
117// SHA256("netgroup")[0:8]
118static const uint64_t RANDOMIZER_ID_NETGROUP = 0x6c0edd8036ef4036ULL;
119// SHA256("localhostnonce")[0:8]
120static const uint64_t RANDOMIZER_ID_LOCALHOSTNONCE = 0xd93e69e2bbfa5735ULL;
121// SHA256("localhostnonce")[8:16]
122static const uint64_t RANDOMIZER_ID_EXTRAENTROPY = 0x94b05d41679a4ff7ULL;
123// SHA256("addrcache")[0:8]
124static const uint64_t RANDOMIZER_ID_ADDRCACHE = 0x1cf2e4ddd306dda9ULL;
125//
126// Global state variables
127//
128bool fDiscover = true;
129bool fListen = true;
131std::map<CNetAddr, LocalServiceInfo>
133static bool vfLimited[NET_MAX] GUARDED_BY(g_maplocalhost_mutex) = {};
134
135void CConnman::AddAddrFetch(const std::string &strDest) {
137 m_addr_fetches.push_back(strDest);
138}
139
140uint16_t GetListenPort() {
141 // If -bind= is provided with ":port" part, use that (first one if multiple
142 // are provided).
143 for (const std::string &bind_arg : gArgs.GetArgs("-bind")) {
144 constexpr uint16_t dummy_port = 0;
145
146 const std::optional<CService> bind_addr{
147 Lookup(bind_arg, dummy_port, /*fAllowLookup=*/false)};
148 if (bind_addr.has_value() && bind_addr->GetPort() != dummy_port) {
149 return bind_addr->GetPort();
150 }
151 }
152
153 // Otherwise, if -whitebind= without NetPermissionFlags::NoBan is provided,
154 // use that
155 // (-whitebind= is required to have ":port").
156 for (const std::string &whitebind_arg : gArgs.GetArgs("-whitebind")) {
157 NetWhitebindPermissions whitebind;
158 bilingual_str error;
159 if (NetWhitebindPermissions::TryParse(whitebind_arg, whitebind,
160 error)) {
161 if (!NetPermissions::HasFlag(whitebind.m_flags,
163 return whitebind.m_service.GetPort();
164 }
165 }
166 }
167
168 // Otherwise, if -port= is provided, use that. Otherwise use the default
169 // port.
170 return static_cast<uint16_t>(
171 gArgs.GetIntArg("-port", Params().GetDefaultPort()));
172}
173
174// find 'best' local address for a particular peer
175bool GetLocal(CService &addr, const CNetAddr *paddrPeer) {
176 if (!fListen) {
177 return false;
178 }
179
180 int nBestScore = -1;
181 int nBestReachability = -1;
182 {
184 for (const auto &entry : mapLocalHost) {
185 int nScore = entry.second.nScore;
186 int nReachability = entry.first.GetReachabilityFrom(paddrPeer);
187 if (nReachability > nBestReachability ||
188 (nReachability == nBestReachability && nScore > nBestScore)) {
189 addr = CService(entry.first, entry.second.nPort);
190 nBestReachability = nReachability;
191 nBestScore = nScore;
192 }
193 }
194 }
195 return nBestScore >= 0;
196}
197
199static std::vector<CAddress>
200convertSeed6(const std::vector<SeedSpec6> &vSeedsIn) {
201 // It'll only connect to one or two seed nodes because once it connects,
202 // it'll get a pile of addresses with newer timestamps. Seed nodes are given
203 // a random 'last seen time' of between one and two weeks ago.
204 const auto one_week{7 * 24h};
205 std::vector<CAddress> vSeedsOut;
206 vSeedsOut.reserve(vSeedsIn.size());
208 // TODO: apply core#25284 when backporting core#21560
209 for (const auto &seed_in : vSeedsIn) {
210 struct in6_addr ip;
211 memcpy(&ip, seed_in.addr, sizeof(ip));
212 CAddress addr(CService(ip, seed_in.port),
214 addr.nTime =
215 rng.rand_uniform_delay(Now<NodeSeconds>() - one_week, -one_week);
216 vSeedsOut.push_back(addr);
217 }
218 return vSeedsOut;
219}
220
221// Get best local address for a particular peer as a CService. Otherwise, return
222// the unroutable 0.0.0.0 but filled in with the normal parameters, since the IP
223// may be changed to a useful one by discovery.
226 CService addr;
227 if (GetLocal(addr, &addrPeer)) {
228 ret = CService{addr};
229 }
230 return ret;
231}
232
233static int GetnScore(const CService &addr) {
235 const auto it = mapLocalHost.find(addr);
236 return (it != mapLocalHost.end()) ? it->second.nScore : 0;
237}
238
239// Is our peer's addrLocal potentially useful as an external IP source?
241 CService addrLocal = pnode->GetAddrLocal();
242 return fDiscover && pnode->addr.IsRoutable() && addrLocal.IsRoutable() &&
243 IsReachable(addrLocal.GetNetwork());
244}
245
246std::optional<CService> GetLocalAddrForPeer(CNode &node) {
247 CService addrLocal{GetLocalAddress(node.addr)};
248 if (gArgs.GetBoolArg("-addrmantest", false)) {
249 // use IPv4 loopback during addrmantest
250 addrLocal = CService(LookupNumeric("127.0.0.1", GetListenPort()));
251 }
252 // If discovery is enabled, sometimes give our peer the address it
253 // tells us that it sees us as in case it has a better idea of our
254 // address than we do.
257 (!addrLocal.IsRoutable() ||
258 rng.randbits((GetnScore(addrLocal) > LOCAL_MANUAL) ? 3 : 1) == 0)) {
259 if (node.IsInboundConn()) {
260 // For inbound connections, assume both the address and the port
261 // as seen from the peer.
262 addrLocal = CService{node.GetAddrLocal()};
263 } else {
264 // For outbound connections, assume just the address as seen from
265 // the peer and leave the port in `addrLocal` as returned by
266 // `GetLocalAddress()` above. The peer has no way to observe our
267 // listening port when we have initiated the connection.
268 addrLocal.SetIP(node.GetAddrLocal());
269 }
270 }
271 if (addrLocal.IsRoutable() || gArgs.GetBoolArg("-addrmantest", false)) {
272 LogDebug(BCLog::NET, "Advertising address %s to peer=%d\n",
273 addrLocal.ToStringAddrPort(), node.GetId());
274 return addrLocal;
275 }
276 // Address is unroutable. Don't advertise.
277 return std::nullopt;
278}
279
280// Learn a new local address.
281bool AddLocal(const CService &addr, int nScore) {
282 if (!addr.IsRoutable()) {
283 return false;
284 }
285
286 if (!fDiscover && nScore < LOCAL_MANUAL) {
287 return false;
288 }
289
290 if (!IsReachable(addr)) {
291 return false;
292 }
293
294 LogPrintf("AddLocal(%s,%i)\n", addr.ToStringAddrPort(), nScore);
295
296 {
298 const auto [it, is_newly_added] =
299 mapLocalHost.emplace(addr, LocalServiceInfo());
300 LocalServiceInfo &info = it->second;
301 if (is_newly_added || nScore >= info.nScore) {
302 info.nScore = nScore + !is_newly_added;
303 info.nPort = addr.GetPort();
304 }
305 }
306
307 return true;
308}
309
310bool AddLocal(const CNetAddr &addr, int nScore) {
311 return AddLocal(CService(addr, GetListenPort()), nScore);
312}
313
314void RemoveLocal(const CService &addr) {
316 LogPrintf("RemoveLocal(%s)\n", addr.ToStringAddrPort());
317 mapLocalHost.erase(addr);
318}
319
320void SetReachable(enum Network net, bool reachable) {
321 if (net == NET_UNROUTABLE || net == NET_INTERNAL) {
322 return;
323 }
325 vfLimited[net] = !reachable;
326}
327
328bool IsReachable(enum Network net) {
330 return !vfLimited[net];
331}
332
333bool IsReachable(const CNetAddr &addr) {
334 return IsReachable(addr.GetNetwork());
335}
336
338bool SeenLocal(const CService &addr) {
340 const auto it = mapLocalHost.find(addr);
341 if (it == mapLocalHost.end()) {
342 return false;
343 }
344 ++it->second.nScore;
345 return true;
346}
347
349bool IsLocal(const CService &addr) {
351 return mapLocalHost.count(addr) > 0;
352}
353
356 for (CNode *pnode : m_nodes) {
357 if (static_cast<CNetAddr>(pnode->addr) == ip) {
358 return pnode;
359 }
360 }
361 return nullptr;
362}
363
366 for (CNode *pnode : m_nodes) {
367 if (subNet.Match(static_cast<CNetAddr>(pnode->addr))) {
368 return pnode;
369 }
370 }
371 return nullptr;
372}
373
374CNode *CConnman::FindNode(const std::string &addrName) {
376 for (CNode *pnode : m_nodes) {
377 if (pnode->m_addr_name == addrName) {
378 return pnode;
379 }
380 }
381 return nullptr;
382}
383
386 for (CNode *pnode : m_nodes) {
387 if (static_cast<CService>(pnode->addr) == addr) {
388 return pnode;
389 }
390 }
391 return nullptr;
392}
393
395 return FindNode(static_cast<CNetAddr>(addr)) ||
397}
398
399bool CConnman::CheckIncomingNonce(uint64_t nonce) {
401 for (const CNode *pnode : m_nodes) {
402 if (!pnode->fSuccessfullyConnected && !pnode->IsInboundConn() &&
403 pnode->GetLocalNonce() == nonce) {
404 return false;
405 }
406 }
407 return true;
408}
409
411static CAddress GetBindAddress(const Sock &sock) {
412 CAddress addr_bind;
413 struct sockaddr_storage sockaddr_bind;
414 socklen_t sockaddr_bind_len = sizeof(sockaddr_bind);
415 if (!sock.GetSockName((struct sockaddr *)&sockaddr_bind,
416 &sockaddr_bind_len)) {
417 addr_bind.SetSockAddr((const struct sockaddr *)&sockaddr_bind,
418 sockaddr_bind_len);
419 } else {
421 "getsockname failed\n");
422 }
423 return addr_bind;
424}
425
426CNode *CConnman::ConnectNode(CAddress addrConnect, const char *pszDest,
427 bool fCountFailure, ConnectionType conn_type) {
429 assert(conn_type != ConnectionType::INBOUND);
430
431 if (pszDest == nullptr) {
432 if (IsLocal(addrConnect)) {
433 return nullptr;
434 }
435
436 // Look for an existing connection
437 CNode *pnode = FindNode(static_cast<CService>(addrConnect));
438 if (pnode) {
439 LogPrintf("Failed to open new connection, already connected\n");
440 return nullptr;
441 }
442 }
443
445 "trying connection %s lastseen=%.1fhrs\n",
446 pszDest ? pszDest : addrConnect.ToStringAddrPort(),
447 Ticks<HoursDouble>(
448 pszDest ? 0h : Now<NodeSeconds>() - addrConnect.nTime));
449
450 // Resolve
451 const uint16_t default_port{pszDest != nullptr
452 ? Params().GetDefaultPort(pszDest)
453 : Params().GetDefaultPort()};
454 if (pszDest) {
455 const std::vector<CService> resolved{Lookup(
456 pszDest, default_port, fNameLookup && !HaveNameProxy(), 256)};
457 if (!resolved.empty()) {
458 addrConnect = CAddress(
459 resolved[FastRandomContext().randrange(resolved.size())],
460 NODE_NONE);
461 if (!addrConnect.IsValid()) {
463 "Resolver returned invalid address %s for %s\n",
464 addrConnect.ToStringAddrPort(), pszDest);
465 return nullptr;
466 }
467 // It is possible that we already have a connection to the IP/port
468 // pszDest resolved to. In that case, drop the connection that was
469 // just created.
471 CNode *pnode = FindNode(static_cast<CService>(addrConnect));
472 if (pnode) {
473 LogPrintf("Failed to open new connection, already connected\n");
474 return nullptr;
475 }
476 }
477 }
478
479 // Connect
480 std::unique_ptr<Sock> sock;
481 Proxy proxy;
482 CAddress addr_bind;
483 assert(!addr_bind.IsValid());
484 std::unique_ptr<i2p::sam::Session> i2p_transient_session;
485
486 if (addrConnect.IsValid()) {
487 const bool use_proxy{GetProxy(addrConnect.GetNetwork(), proxy)};
488 bool proxyConnectionFailed = false;
489
490 if (addrConnect.GetNetwork() == NET_I2P && use_proxy) {
491 i2p::Connection conn;
492 bool connected{false};
493
494 if (m_i2p_sam_session) {
495 connected = m_i2p_sam_session->Connect(addrConnect, conn,
496 proxyConnectionFailed);
497 } else {
498 {
500 if (m_unused_i2p_sessions.empty()) {
501 i2p_transient_session =
502 std::make_unique<i2p::sam::Session>(proxy,
503 &interruptNet);
504 } else {
505 i2p_transient_session.swap(
506 m_unused_i2p_sessions.front());
507 m_unused_i2p_sessions.pop();
508 }
509 }
510 connected = i2p_transient_session->Connect(
511 addrConnect, conn, proxyConnectionFailed);
512 if (!connected) {
514 if (m_unused_i2p_sessions.size() <
516 m_unused_i2p_sessions.emplace(
517 i2p_transient_session.release());
518 }
519 }
520 }
521
522 if (connected) {
523 sock = std::move(conn.sock);
524 addr_bind = CAddress{conn.me, NODE_NONE};
525 }
526 } else if (use_proxy) {
528 "Using proxy: %s to connect to %s:%s\n",
529 proxy.ToString(), addrConnect.ToStringAddr(),
530 addrConnect.GetPort());
531 sock = ConnectThroughProxy(proxy, addrConnect.ToStringAddr(),
532 addrConnect.GetPort(),
533 proxyConnectionFailed);
534 } else {
535 // no proxy needed (none set for target network)
536 sock = ConnectDirectly(addrConnect,
537 conn_type == ConnectionType::MANUAL);
538 }
539 if (!proxyConnectionFailed) {
540 // If a connection to the node was attempted, and failure (if any)
541 // is not caused by a problem connecting to the proxy, mark this as
542 // an attempt.
543 addrman.Attempt(addrConnect, fCountFailure);
544 }
545 } else if (pszDest && GetNameProxy(proxy)) {
546 std::string host;
547 uint16_t port{default_port};
548 SplitHostPort(std::string(pszDest), port, host);
549 bool proxyConnectionFailed;
550 sock = ConnectThroughProxy(proxy, host, port, proxyConnectionFailed);
551 }
552 if (!sock) {
553 return nullptr;
554 }
555
557 std::vector<NetWhitelistPermissions> whitelist_permissions =
558 conn_type == ConnectionType::MANUAL
560 : std::vector<NetWhitelistPermissions>{};
561 AddWhitelistPermissionFlags(permission_flags, addrConnect,
562 whitelist_permissions);
563
564 // Add node
565 NodeId id = GetNewNodeId();
567 .Write(id)
568 .Finalize();
569 uint64_t extra_entropy =
571 .Write(id)
572 .Finalize();
573 if (!addr_bind.IsValid()) {
574 addr_bind = GetBindAddress(*sock);
575 }
576 CNode *pnode = new CNode(
577 id, std::move(sock), addrConnect, CalculateKeyedNetGroup(addrConnect),
578 nonce, extra_entropy, addr_bind, pszDest ? pszDest : "", conn_type,
579 /* inbound_onion */ false,
581 .i2p_sam_session = std::move(i2p_transient_session),
582 .permission_flags = permission_flags,
583 .recv_flood_size = nReceiveFloodSize,
584 });
585 pnode->AddRef();
586
587 // We're making a new connection, harvest entropy from the time (and our
588 // peer count)
589 RandAddEvent(uint32_t(id));
590
591 return pnode;
592}
593
595 fDisconnect = true;
597 if (m_sock) {
598 LogDebug(BCLog::NET, "disconnecting peer=%d\n", id);
599 m_sock.reset();
600 }
601 m_i2p_sam_session.reset();
602}
603
605 NetPermissionFlags &flags, std::optional<CNetAddr> addr,
606 const std::vector<NetWhitelistPermissions> &ranges) const {
607 for (const auto &subnet : ranges) {
608 if (addr.has_value() && subnet.m_subnet.Match(addr.value())) {
609 NetPermissions::AddFlag(flags, subnet.m_flags);
610 }
611 }
616 }
617 if (whitelist_relay) {
619 }
622 }
623}
624
630
631void CNode::SetAddrLocal(const CService &addrLocalIn) {
634 if (addrLocal.IsValid()) {
635 LogError(
636 "Addr local already set for node: %i. Refusing to change from %s "
637 "to %s\n",
638 id, addrLocal.ToStringAddrPort(), addrLocalIn.ToStringAddrPort());
639 } else {
640 addrLocal = addrLocalIn;
641 }
642}
643
647
649 stats.nodeid = this->GetId();
650 stats.addr = addr;
651 stats.addrBind = addrBind;
653 stats.m_last_send = m_last_send;
654 stats.m_last_recv = m_last_recv;
659 stats.m_connected = m_connected;
660 stats.nTimeOffset = nTimeOffset;
661 stats.m_addr_name = m_addr_name;
662 stats.nVersion = nVersion;
663 {
665 stats.cleanSubVer = cleanSubVer;
666 }
667 stats.fInbound = IsInboundConn();
670 {
671 LOCK(cs_vSend);
672 stats.mapSendBytesPerMsgType = mapSendBytesPerMsgType;
673 stats.nSendBytes = nSendBytes;
674 }
675 {
676 LOCK(cs_vRecv);
677 stats.mapRecvBytesPerMsgType = mapRecvBytesPerMsgType;
678 stats.nRecvBytes = nRecvBytes;
679 }
682
685
686 // Leave string empty if addrLocal invalid (not filled in yet)
687 CService addrLocalUnlocked = GetAddrLocal();
688 stats.addrLocal =
689 addrLocalUnlocked.IsValid() ? addrLocalUnlocked.ToStringAddrPort() : "";
690
691 stats.m_conn_type = m_conn_type;
692
694 ? std::make_optional(getAvailabilityScore())
695 : std::nullopt;
696}
697
698void CNode::pauseRecv(bool pause) {
699 bool wasPaused = fPauseRecv.exchange(pause);
700 if (wasPaused && !pause) {
701 // We were paused and are now unpaused, so update the last receive time
702 // to prevent us from being disconnected for inactivity.
703 const auto time = GetTime<std::chrono::microseconds>();
704 m_last_recv = std::chrono::duration_cast<std::chrono::seconds>(time);
706 std::chrono::duration_cast<std::chrono::seconds>(time);
707 }
708}
709
711 bool &complete) {
712 complete = false;
713 const auto time = GetTime<std::chrono::microseconds>();
714 LOCK(cs_vRecv);
715 m_last_recv = std::chrono::duration_cast<std::chrono::seconds>(time);
716 if (!m_deserializer->HasData()) {
717 // If deserializer has no data, then we're starting to receive a new
718 // message. Record the time that we started receiving the message.
720 std::chrono::duration_cast<std::chrono::seconds>(time);
721 }
722
723 nRecvBytes += msg_bytes.size();
724 nInflightBytes += msg_bytes.size();
725
726 while (msg_bytes.size() > 0) {
727 // Absorb network data.
728 int handled = m_deserializer->Read(config, msg_bytes);
729 if (handled < 0) {
730 // Serious header problem, disconnect from the peer.
731 return false;
732 }
733
734 if (m_deserializer->Complete()) {
735 // decompose a transport agnostic CNetMessage from the deserializer
736 bool reject_message{false};
737 CNetMessage msg = m_deserializer->GetMessage(time, reject_message);
738 if (reject_message) {
739 // Message deserialization failed.
740 // Drop the message and disconnect the peer.
741 // store the size of the corrupt message
742 mapRecvBytesPerMsgType.at(NET_MESSAGE_TYPE_OTHER) +=
743 msg.m_raw_message_size;
744 return false;
745 }
746
747 // Store received bytes per message command
748 // to prevent a memory DOS, only allow valid commands
749 auto i = mapRecvBytesPerMsgType.find(msg.m_type);
750 if (i == mapRecvBytesPerMsgType.end()) {
751 i = mapRecvBytesPerMsgType.find(NET_MESSAGE_TYPE_OTHER);
752 }
753
754 assert(i != mapRecvBytesPerMsgType.end());
755 i->second += msg.m_raw_message_size;
756
757 // push the message to the process queue,
758 vRecvMsg.push_back(std::move(msg));
759
760 nInflightBytes -= msg.m_raw_message_size;
761 complete = true;
762
763 // If we completed a message but still have more bytes, then we
764 // started a new message.
765 if (m_deserializer->HasData()) {
767 std::chrono::duration_cast<std::chrono::seconds>(time);
768 }
769 }
770 }
771
772 return true;
773}
774
776 Span<const uint8_t> msg_bytes) {
777 // copy data to temporary parsing buffer
778 uint32_t nRemaining = CMessageHeader::HEADER_SIZE - nHdrPos;
779 uint32_t nCopy = std::min<unsigned int>(nRemaining, msg_bytes.size());
780
781 memcpy(&hdrbuf[nHdrPos], msg_bytes.data(), nCopy);
782 nHdrPos += nCopy;
783
784 // if header incomplete, exit
786 return nCopy;
787 }
788
789 // deserialize to CMessageHeader
790 try {
791 hdrbuf >> hdr;
792 } catch (const std::exception &) {
793 LogDebug(BCLog::NET, "Header error: Unable to deserialize, peer=%d\n",
794 m_node_id);
795 return -1;
796 }
797
798 // Check start string, network magic
799 if (memcmp(std::begin(hdr.pchMessageStart),
800 std::begin(m_config.GetChainParams().NetMagic()),
803 "Header error: Wrong MessageStart %s received, peer=%d\n",
805 return -1;
806 }
807
808 // Reject oversized messages
809 if (hdr.IsOversized(config)) {
811 "Header error: Size too large (%s, %u bytes), peer=%d\n",
813 m_node_id);
814 return -1;
815 }
816
817 // switch state to reading message data
818 in_data = true;
819
820 return nCopy;
821}
822
824 unsigned int nRemaining = hdr.nMessageSize - nDataPos;
825 unsigned int nCopy = std::min<unsigned int>(nRemaining, msg_bytes.size());
826
827 if (vRecv.size() < nDataPos + nCopy) {
828 // Allocate up to 256 KiB ahead, but never more than the total message
829 // size.
830 vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024));
831 }
832
833 hasher.Write(msg_bytes.first(nCopy));
834 memcpy(&vRecv[nDataPos], msg_bytes.data(), nCopy);
835 nDataPos += nCopy;
836
837 return nCopy;
838}
839
841 assert(Complete());
842 if (data_hash.IsNull()) {
844 }
845 return data_hash;
846}
847
849V1TransportDeserializer::GetMessage(const std::chrono::microseconds time,
850 bool &reject_message) {
851 // Initialize out parameter
852 reject_message = false;
853 // decompose a single CNetMessage from the TransportDeserializer
854 CNetMessage msg(std::move(vRecv));
855
856 // store message type string, time and sizes
857 msg.m_type = hdr.GetMessageType();
858 msg.m_time = time;
859 msg.m_message_size = hdr.nMessageSize;
860 msg.m_raw_message_size = hdr.nMessageSize + CMessageHeader::HEADER_SIZE;
861
862 uint256 hash = GetMessageHash();
863
864 // We just received a message off the wire, harvest entropy from the time
865 // (and the message checksum)
866 RandAddEvent(ReadLE32(hash.begin()));
867
868 // Check checksum and header command string
869 if (memcmp(hash.begin(), hdr.pchChecksum, CMessageHeader::CHECKSUM_SIZE) !=
870 0) {
871 LogDebug(
873 "Header error: Wrong checksum (%s, %u bytes), expected %s was %s, "
874 "peer=%d\n",
875 SanitizeString(msg.m_type), msg.m_message_size,
879 reject_message = true;
880 } else if (!hdr.IsMessageTypeValid()) {
882 "Header error: Invalid message type (%s, %u bytes), peer=%d\n",
883 SanitizeString(hdr.GetMessageType()), msg.m_message_size,
884 m_node_id);
885 reject_message = true;
886 }
887
888 // Always reset the network deserializer (prepare for the next message)
889 Reset();
890 return msg;
891}
892
894 const Config &config, CSerializedNetMsg &msg,
895 std::vector<uint8_t> &header) const {
896 // create dbl-sha256 checksum
897 uint256 hash = Hash(msg.data);
898
899 // create header
900 CMessageHeader hdr(config.GetChainParams().NetMagic(), msg.m_type.c_str(),
901 msg.data.size());
903
904 // serialize header
905 header.reserve(CMessageHeader::HEADER_SIZE);
906 VectorWriter{header, 0, hdr};
907}
908
909std::pair<size_t, bool> CConnman::SocketSendData(CNode &node) const {
910 size_t nSentSize = 0;
911 size_t nMsgCount = 0;
912
913 for (auto it = node.vSendMsg.begin(); it != node.vSendMsg.end(); ++it) {
914 const auto &data = *it;
915 assert(data.size() > node.nSendOffset);
916 int nBytes = 0;
917
918 {
919 LOCK(node.m_sock_mutex);
920 if (!node.m_sock) {
921 break;
922 }
924#ifdef MSG_MORE
925 if (it + 1 != node.vSendMsg.end()) {
926 flags |= MSG_MORE;
927 }
928#endif
929 nBytes = node.m_sock->Send(
930 reinterpret_cast<const char *>(data.data()) + node.nSendOffset,
931 data.size() - node.nSendOffset, flags);
932 }
933
934 if (nBytes == 0) {
935 // couldn't send anything at all
936 break;
937 }
938
939 if (nBytes < 0) {
940 // error
941 int nErr = WSAGetLastError();
942 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE &&
943 nErr != WSAEINTR && nErr != WSAEINPROGRESS) {
944 LogDebug(BCLog::NET, "socket send error for peer=%d: %s\n",
945 node.GetId(), NetworkErrorString(nErr));
946 node.CloseSocketDisconnect();
947 }
948
949 break;
950 }
951
952 assert(nBytes > 0);
953 node.m_last_send = GetTime<std::chrono::seconds>();
954 node.nSendBytes += nBytes;
955 node.nSendOffset += nBytes;
956 nSentSize += nBytes;
957 if (node.nSendOffset != data.size()) {
958 // could not send full message; stop sending more
959 break;
960 }
961
962 node.nSendOffset = 0;
963 node.nSendSize -= data.size();
964 node.fPauseSend = node.nSendSize > nSendBufferMaxSize;
965 nMsgCount++;
966 }
967
968 node.vSendMsg.erase(node.vSendMsg.begin(),
969 node.vSendMsg.begin() + nMsgCount);
970
971 if (node.vSendMsg.empty()) {
972 assert(node.nSendOffset == 0);
973 assert(node.nSendSize == 0);
974 }
975
976 return {nSentSize, !node.vSendMsg.empty()};
977}
987 std::vector<NodeEvictionCandidate> vEvictionCandidates;
988 {
990 for (const CNode *node : m_nodes) {
991 if (node->fDisconnect) {
992 continue;
993 }
994
995 NodeEvictionCandidate candidate = {
996 .id = node->GetId(),
997 .m_connected = node->m_connected,
998 .m_min_ping_time = node->m_min_ping_time,
999 .m_last_block_time = node->m_last_block_time,
1000 .m_last_proof_time = node->m_last_proof_time,
1001 .m_last_tx_time = node->m_last_tx_time,
1002 .fRelevantServices = node->m_has_all_wanted_services,
1003 .m_relay_txs = node->m_relays_txs.load(),
1004 .fBloomFilter = node->m_bloom_filter_loaded.load(),
1005 .nKeyedNetGroup = node->nKeyedNetGroup,
1006 .prefer_evict = node->m_prefer_evict,
1007 .m_is_local = node->addr.IsLocal(),
1008 .m_network = node->ConnectedThroughNetwork(),
1009 .m_noban = node->HasPermission(NetPermissionFlags::NoBan),
1010 .m_conn_type = node->m_conn_type,
1011 .availabilityScore =
1012 node->m_avalanche_enabled
1013 ? node->getAvailabilityScore()
1014 : -std::numeric_limits<double>::infinity()};
1015 vEvictionCandidates.push_back(candidate);
1016 }
1017 }
1018 const std::optional<NodeId> node_id_to_evict =
1019 SelectNodeToEvict(std::move(vEvictionCandidates));
1020 if (!node_id_to_evict) {
1021 return false;
1022 }
1024 for (CNode *pnode : m_nodes) {
1025 if (pnode->GetId() == *node_id_to_evict) {
1026 LogDebug(
1027 BCLog::NET,
1028 "selected %s connection for eviction peer=%d; disconnecting\n",
1029 pnode->ConnectionTypeAsString(), pnode->GetId());
1030 pnode->fDisconnect = true;
1031 return true;
1032 }
1033 }
1034 return false;
1035}
1036
1037void CConnman::AcceptConnection(const ListenSocket &hListenSocket) {
1038 struct sockaddr_storage sockaddr;
1039 socklen_t len = sizeof(sockaddr);
1040 auto sock = hListenSocket.sock->Accept((struct sockaddr *)&sockaddr, &len);
1041 CAddress addr;
1042
1043 if (!sock) {
1044 const int nErr = WSAGetLastError();
1045 if (nErr != WSAEWOULDBLOCK) {
1046 LogPrintf("socket error accept failed: %s\n",
1047 NetworkErrorString(nErr));
1048 }
1049 return;
1050 }
1051
1052 if (!addr.SetSockAddr((const struct sockaddr *)&sockaddr, len)) {
1054 "Unknown socket family\n");
1055 }
1056
1057 const CAddress addr_bind = GetBindAddress(*sock);
1058
1060 hListenSocket.AddSocketPermissionFlags(permission_flags);
1061
1062 CreateNodeFromAcceptedSocket(std::move(sock), permission_flags, addr_bind,
1063 addr);
1064}
1065
1066void CConnman::CreateNodeFromAcceptedSocket(std::unique_ptr<Sock> &&sock,
1067 NetPermissionFlags permission_flags,
1068 const CAddress &addr_bind,
1069 const CAddress &addr) {
1070 int nInbound = 0;
1071 int nMaxInbound = nMaxConnections - m_max_outbound;
1072
1073 const bool inbound_onion =
1074 std::find(m_onion_binds.begin(), m_onion_binds.end(), addr_bind) !=
1075 m_onion_binds.end();
1076
1077 // Tor inbound connections do not reveal the peer's actual network address.
1078 // Therefore do not apply address-based whitelist permissions to them.
1079 AddWhitelistPermissionFlags(permission_flags,
1080 inbound_onion ? std::nullopt
1081 : std::make_optional(addr),
1083
1084 {
1086 for (const CNode *pnode : m_nodes) {
1087 if (pnode->IsInboundConn()) {
1088 nInbound++;
1089 }
1090 }
1091 }
1092
1093 if (!fNetworkActive) {
1095 "connection from %s dropped: not accepting new connections\n",
1096 addr.ToStringAddrPort());
1097 return;
1098 }
1099
1100 if (!sock->IsSelectable()) {
1101 LogPrintf("connection from %s dropped: non-selectable socket\n",
1102 addr.ToStringAddrPort());
1103 return;
1104 }
1105
1106 // According to the internet TCP_NODELAY is not carried into accepted
1107 // sockets on all platforms. Set it again here just to be sure.
1108 const int on{1};
1109 if (sock->SetSockOpt(IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) ==
1110 SOCKET_ERROR) {
1112 "connection from %s: unable to set TCP_NODELAY, continuing "
1113 "anyway\n",
1114 addr.ToStringAddrPort());
1115 }
1116
1117 // Don't accept connections from banned peers.
1118 bool banned = m_banman && m_banman->IsBanned(addr);
1119 if (!NetPermissions::HasFlag(permission_flags, NetPermissionFlags::NoBan) &&
1120 banned) {
1121 LogDebug(BCLog::NET, "connection from %s dropped (banned)\n",
1122 addr.ToStringAddrPort());
1123 return;
1124 }
1125
1126 // Only accept connections from discouraged peers if our inbound slots
1127 // aren't (almost) full.
1128 bool discouraged = m_banman && m_banman->IsDiscouraged(addr);
1129 if (!NetPermissions::HasFlag(permission_flags, NetPermissionFlags::NoBan) &&
1130 nInbound + 1 >= nMaxInbound && discouraged) {
1131 LogDebug(BCLog::NET, "connection from %s dropped (discouraged)\n",
1132 addr.ToStringAddrPort());
1133 return;
1134 }
1135
1136 if (nInbound >= nMaxInbound) {
1137 if (!AttemptToEvictConnection()) {
1138 // No connection to evict, disconnect the new connection
1139 LogDebug(BCLog::NET, "failed to find an eviction candidate - "
1140 "connection dropped (full)\n");
1141 return;
1142 }
1143 }
1144
1145 NodeId id = GetNewNodeId();
1147 .Write(id)
1148 .Finalize();
1149 uint64_t extra_entropy =
1151 .Write(id)
1152 .Finalize();
1153
1154 CNode *pnode = new CNode(
1155 id, std::move(sock), addr, CalculateKeyedNetGroup(addr), nonce,
1156 extra_entropy, addr_bind, "", ConnectionType::INBOUND, inbound_onion,
1158 .permission_flags = permission_flags,
1159 .prefer_evict = discouraged,
1160 .recv_flood_size = nReceiveFloodSize,
1161 });
1162 pnode->AddRef();
1163 for (auto interface : m_msgproc) {
1164 interface->InitializeNode(*config, *pnode, GetLocalServices());
1165 }
1166
1167 LogDebug(BCLog::NET, "connection from %s accepted\n",
1168 addr.ToStringAddrPort());
1169
1170 {
1172 m_nodes.push_back(pnode);
1173 }
1174
1175 // We received a new connection, harvest entropy from the time (and our peer
1176 // count)
1177 RandAddEvent(uint32_t(id));
1178}
1179
1180bool CConnman::AddConnection(const std::string &address,
1181 ConnectionType conn_type) {
1183 std::optional<int> max_connections;
1184 switch (conn_type) {
1187 return false;
1189 max_connections = m_max_outbound_full_relay;
1190 break;
1192 max_connections = m_max_outbound_block_relay;
1193 break;
1194 // no limit for ADDR_FETCH because -seednode has no limit either
1196 break;
1197 // no limit for FEELER connections since they're short-lived
1199 break;
1201 max_connections = m_max_avalanche_outbound;
1202 break;
1203 } // no default case, so the compiler can warn about missing cases
1204
1205 // Count existing connections
1206 int existing_connections =
1208 return std::count_if(
1209 m_nodes.begin(), m_nodes.end(), [conn_type](CNode *node) {
1210 return node->m_conn_type == conn_type;
1211 }););
1212
1213 // Max connections of specified type already exist
1214 if (max_connections != std::nullopt &&
1215 existing_connections >= max_connections) {
1216 return false;
1217 }
1218
1219 // Max total outbound connections already exist
1220 CSemaphoreGrant grant(*semOutbound, true);
1221 if (!grant) {
1222 return false;
1223 }
1224
1225 OpenNetworkConnection(CAddress(), false, &grant, address.c_str(),
1226 conn_type);
1227 return true;
1228}
1229
1231 {
1233
1234 if (!fNetworkActive) {
1235 // Disconnect any connected nodes
1236 for (CNode *pnode : m_nodes) {
1237 if (!pnode->fDisconnect) {
1239 "Network not active, dropping peer=%d\n",
1240 pnode->GetId());
1241 pnode->fDisconnect = true;
1242 }
1243 }
1244 }
1245
1246 // Disconnect unused nodes
1247 std::vector<CNode *> nodes_copy = m_nodes;
1248 for (CNode *pnode : nodes_copy) {
1249 if (pnode->fDisconnect) {
1250 // remove from m_nodes
1251 m_nodes.erase(remove(m_nodes.begin(), m_nodes.end(), pnode),
1252 m_nodes.end());
1253
1254 // release outbound grant (if any)
1255 pnode->grantOutbound.Release();
1256
1257 // close socket and cleanup
1258 pnode->CloseSocketDisconnect();
1259
1260 // hold in disconnected pool until all refs are released
1261 pnode->Release();
1262 m_nodes_disconnected.push_back(pnode);
1263 }
1264 }
1265 }
1266 {
1267 // Delete disconnected nodes
1268 std::list<CNode *> nodes_disconnected_copy = m_nodes_disconnected;
1269 for (CNode *pnode : nodes_disconnected_copy) {
1270 // Destroy the object only after other threads have stopped using
1271 // it.
1272 if (pnode->GetRefCount() <= 0) {
1273 m_nodes_disconnected.remove(pnode);
1274 DeleteNode(pnode);
1275 }
1276 }
1277 }
1278}
1279
1281 size_t nodes_size;
1282 {
1284 nodes_size = m_nodes.size();
1285 }
1286 if (nodes_size != nPrevNodeCount) {
1287 nPrevNodeCount = nodes_size;
1288 if (m_client_interface) {
1289 m_client_interface->NotifyNumConnectionsChanged(nodes_size);
1290 }
1291 }
1292}
1293
1295 std::chrono::seconds now) const {
1296 return node.m_connected + m_peer_connect_timeout < now;
1297}
1298
1300 // Tests that see disconnects after using mocktime can start nodes with a
1301 // large timeout. For example, -peertimeout=999999999.
1302 const auto now{GetTime<std::chrono::seconds>()};
1303 const auto last_send{node.m_last_send.load()};
1304 const auto last_recv{node.m_last_recv.load()};
1305 const auto last_msg_start{node.m_last_msg_start.load()};
1306
1307 if (!ShouldRunInactivityChecks(node, now)) {
1308 return false;
1309 }
1310
1311 if (last_recv.count() == 0 || last_send.count() == 0) {
1313 "socket no message in first %i seconds, %d %d peer=%d\n",
1314 count_seconds(m_peer_connect_timeout), last_recv.count() != 0,
1315 last_send.count() != 0, node.GetId());
1316 return true;
1317 }
1318
1319 if (now > last_send + TIMEOUT_INTERVAL) {
1320 LogDebug(BCLog::NET, "socket sending timeout: %is peer=%d\n",
1321 count_seconds(now - last_send), node.GetId());
1322 return true;
1323 }
1324
1325 if (now > last_recv + TIMEOUT_INTERVAL) {
1326 LogDebug(BCLog::NET, "socket receive timeout: %is peer=%d\n",
1327 count_seconds(now - last_recv), node.GetId());
1328 return true;
1329 }
1330
1331 uint64_t inflight_bytes = node.nInflightBytes.load();
1332 if (inflight_bytes > 0 && !node.fPauseRecv) {
1333 // First check if the peer started sending us a message, but then
1334 // stalled without finishing it.
1335 if (now > last_recv + m_peer_connect_timeout) {
1337 "socket receive timeout: stalled message, last data "
1338 "received %i seconds ago, bytes=%d peer=%d\n",
1339 count_seconds(now - last_recv), inflight_bytes,
1340 node.GetId());
1341 return true;
1342 }
1343
1344 // Second check if the peer sent us a message, but is too slow to
1345 // complete it in reasonable time (~2.13Mb/s for a 32MB block under
1346 // default settings).
1347 if (now > last_msg_start + 2 * m_peer_connect_timeout) {
1349 "socket receive timeout: stalled message started %i "
1350 "seconds ago, bytes=%d peer=%d\n",
1351 count_seconds(now - last_msg_start), inflight_bytes,
1352 node.GetId());
1353 return true;
1354 }
1355 }
1356
1357 if (!node.fSuccessfullyConnected) {
1358 LogDebug(BCLog::NET, "version handshake timeout peer=%d\n",
1359 node.GetId());
1360 return true;
1361 }
1362
1363 return false;
1364}
1365
1367 Sock::EventsPerSock events_per_sock;
1368
1369 for (const ListenSocket &hListenSocket : vhListenSocket) {
1370 events_per_sock.emplace(hListenSocket.sock, Sock::Events{Sock::RECV});
1371 }
1372
1373 int inbound_candidates{0};
1374 for (CNode *pnode : nodes) {
1375 inbound_candidates += pnode->IsInboundConn();
1376
1377 // Stop receiving if the peer is paused, or if we have enough inflight
1378 // data to process already in wich case we limit to outbounds and up to
1379 // 3 inbounds.
1380 bool select_recv = !pnode->fPauseRecv &&
1381 (!inflight_throttle || !pnode->IsInboundConn() ||
1382 inbound_candidates <= 3);
1383 bool select_send =
1384 WITH_LOCK(pnode->cs_vSend, return !pnode->vSendMsg.empty());
1385 if (!select_recv && !select_send) {
1386 continue;
1387 }
1388
1389 LOCK(pnode->m_sock_mutex);
1390 if (pnode->m_sock) {
1391 Sock::Event event =
1392 (select_send ? Sock::SEND : 0) | (select_recv ? Sock::RECV : 0);
1393 events_per_sock.emplace(pnode->m_sock, Sock::Events{event});
1394 }
1395 }
1396
1397 return events_per_sock;
1398}
1399
1401 Sock::EventsPerSock events_per_sock;
1402
1403 {
1404 const NodesSnapshot snap{*this, /*shuffle=*/false};
1405
1406 const auto timeout =
1407 std::chrono::milliseconds(SELECT_TIMEOUT_MILLISECONDS);
1408
1409 // Check for the readiness of the already connected sockets and the
1410 // listening sockets in one call ("readiness" as in poll(2) or
1411 // select(2)). If none are ready, wait for a short while and return
1412 // empty sets.
1413 events_per_sock = GenerateWaitSockets(snap.Nodes());
1414 if (events_per_sock.empty() ||
1415 !events_per_sock.begin()->first->WaitMany(timeout,
1416 events_per_sock)) {
1417 interruptNet.sleep_for(timeout);
1418 }
1419
1420 // Service (send/receive) each of the already connected nodes.
1421 SocketHandlerConnected(snap.Nodes(), events_per_sock);
1422 }
1423
1424 // Accept new connections from listening sockets.
1425 SocketHandlerListening(events_per_sock);
1426}
1427
1429 const std::vector<CNode *> &nodes,
1430 const Sock::EventsPerSock &events_per_sock) {
1431 uint64_t nTotalInflightBytes{0};
1432 for (CNode *pnode : nodes) {
1433 if (interruptNet) {
1434 return;
1435 }
1436
1437 // Always account for the node inflight bytes, even if the socket is
1438 // paused.
1439 nTotalInflightBytes += pnode->nInflightBytes;
1440
1441 //
1442 // Receive
1443 //
1444 bool recvSet = false;
1445 bool sendSet = false;
1446 bool errorSet = false;
1447 {
1448 LOCK(pnode->m_sock_mutex);
1449 if (!pnode->m_sock) {
1450 continue;
1451 }
1452 const auto it = events_per_sock.find(pnode->m_sock);
1453 if (it != events_per_sock.end()) {
1454 recvSet = it->second.occurred & Sock::RECV;
1455 sendSet = it->second.occurred & Sock::SEND;
1456 errorSet = it->second.occurred & Sock::ERR;
1457 }
1458 }
1459
1460 if (sendSet) {
1461 // Send data
1462 auto [bytes_sent, data_left] =
1463 WITH_LOCK(pnode->cs_vSend, return SocketSendData(*pnode));
1464 if (bytes_sent) {
1465 RecordBytesSent(bytes_sent);
1466
1467 // If both receiving and (non-optimistic) sending were possible,
1468 // we first attempt sending. If that succeeds, but does not
1469 // fully drain the send queue, do not attempt to receive. This
1470 // avoids needlessly queueing data if the remote peer is slow at
1471 // receiving data, by means of TCP flow control. We only do this
1472 // when sending actually succeeded to make sure progress is
1473 // always made; otherwise a deadlock would be possible when both
1474 // sides have data to send, but neither is receiving.
1475 if (data_left) {
1476 recvSet = false;
1477 }
1478 }
1479 }
1480
1481 if (recvSet || errorSet) {
1482 // typical socket buffer is 8K-64K
1483 uint8_t pchBuf[0x10000];
1484 int32_t nBytes = 0;
1485 {
1486 LOCK(pnode->m_sock_mutex);
1487 if (!pnode->m_sock) {
1488 continue;
1489 }
1490 nBytes =
1491 pnode->m_sock->Recv(pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
1492 }
1493 if (nBytes > 0) {
1494 bool notify = false;
1495 if (!pnode->ReceiveMsgBytes(*config, {pchBuf, (size_t)nBytes},
1496 notify)) {
1497 pnode->CloseSocketDisconnect();
1498 }
1499 RecordBytesRecv(nBytes);
1500 if (notify) {
1501 pnode->MarkReceivedMsgsForProcessing();
1503 }
1504 } else if (nBytes == 0) {
1505 // socket closed gracefully
1506 if (!pnode->fDisconnect) {
1507 LogDebug(BCLog::NET, "socket closed for peer=%d\n",
1508 pnode->GetId());
1509 }
1510 pnode->CloseSocketDisconnect();
1511 } else if (nBytes < 0) {
1512 // error
1513 int nErr = WSAGetLastError();
1514 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE &&
1515 nErr != WSAEINTR && nErr != WSAEINPROGRESS) {
1516 if (!pnode->fDisconnect) {
1518 "socket recv error for peer=%d: %s\n",
1519 pnode->GetId(), NetworkErrorString(nErr));
1520 }
1521 pnode->CloseSocketDisconnect();
1522 }
1523 }
1524 }
1525
1526 if (InactivityCheck(*pnode)) {
1527 pnode->fDisconnect = true;
1528 }
1529 }
1530
1531 const size_t max_inflight_bytes = DEFAULT_MAXINFLIGHTBUFFER * 1000;
1532
1533 bool prev_inflight_throttle = inflight_throttle;
1534 inflight_throttle = nTotalInflightBytes > max_inflight_bytes;
1535 if (prev_inflight_throttle != inflight_throttle) {
1536 LogPrintf("Inflight throttling %s (%d/%d)\n",
1537 inflight_throttle ? "enabled" : "disabled",
1538 nTotalInflightBytes, max_inflight_bytes);
1539 }
1540}
1541
1543 const Sock::EventsPerSock &events_per_sock) {
1544 for (const ListenSocket &listen_socket : vhListenSocket) {
1545 if (interruptNet) {
1546 return;
1547 }
1548 const auto it = events_per_sock.find(listen_socket.sock);
1549 if (it != events_per_sock.end() && it->second.occurred & Sock::RECV) {
1550 AcceptConnection(listen_socket);
1551 }
1552 }
1553}
1554
1562
1564 {
1566 fMsgProcWake = true;
1567 }
1568 condMsgProc.notify_one();
1569}
1570
1573 std::vector<std::string> seeds =
1575 // Number of seeds left before testing if we have enough connections
1576 int seeds_right_now = 0;
1577 int found = 0;
1578
1579 if (gArgs.GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED)) {
1580 // When -forcednsseed is provided, query all.
1581 seeds_right_now = seeds.size();
1582 } else if (addrman.size() == 0) {
1583 // If we have no known peers, query all.
1584 // This will occur on the first run, or if peers.dat has been
1585 // deleted.
1586 seeds_right_now = seeds.size();
1587 }
1588
1589 // goal: only query DNS seed if address need is acute
1590 // * If we have a reasonable number of peers in addrman, spend
1591 // some time trying them first. This improves user privacy by
1592 // creating fewer identifying DNS requests, reduces trust by
1593 // giving seeds less influence on the network topology, and
1594 // reduces traffic to the seeds.
1595 // * When querying DNS seeds query a few at once, this ensures
1596 // that we don't give DNS seeds the ability to eclipse nodes
1597 // that query them.
1598 // * If we continue having problems, eventually query all the
1599 // DNS seeds, and if that fails too, also try the fixed seeds.
1600 // (done in ThreadOpenConnections)
1601 const std::chrono::seconds seeds_wait_time =
1605
1606 for (const std::string &seed : seeds) {
1607 if (seeds_right_now == 0) {
1608 seeds_right_now += DNSSEEDS_TO_QUERY_AT_ONCE;
1609
1610 if (addrman.size() > 0) {
1611 LogPrintf("Waiting %d seconds before querying DNS seeds.\n",
1612 seeds_wait_time.count());
1613 std::chrono::seconds to_wait = seeds_wait_time;
1614 while (to_wait.count() > 0) {
1615 // if sleeping for the MANY_PEERS interval, wake up
1616 // early to see if we have enough peers and can stop
1617 // this thread entirely freeing up its resources
1618 std::chrono::seconds w =
1619 std::min(DNSSEEDS_DELAY_FEW_PEERS, to_wait);
1620 if (!interruptNet.sleep_for(w)) {
1621 return;
1622 }
1623 to_wait -= w;
1624
1625 int nRelevant = 0;
1626 {
1628 for (const CNode *pnode : m_nodes) {
1629 if (pnode->fSuccessfullyConnected &&
1630 pnode->IsFullOutboundConn()) {
1631 ++nRelevant;
1632 }
1633 }
1634 }
1635 if (nRelevant >= 2) {
1636 if (found > 0) {
1637 LogPrintf("%d addresses found from DNS seeds\n",
1638 found);
1639 LogPrintf(
1640 "P2P peers available. Finished DNS seeding.\n");
1641 } else {
1642 LogPrintf(
1643 "P2P peers available. Skipped DNS seeding.\n");
1644 }
1645 return;
1646 }
1647 }
1648 }
1649 }
1650
1651 if (interruptNet) {
1652 return;
1653 }
1654
1655 // hold off on querying seeds if P2P network deactivated
1656 if (!fNetworkActive) {
1657 LogPrintf("Waiting for network to be reactivated before querying "
1658 "DNS seeds.\n");
1659 do {
1660 if (!interruptNet.sleep_for(std::chrono::seconds{1})) {
1661 return;
1662 }
1663 } while (!fNetworkActive);
1664 }
1665
1666 LogPrintf("Loading addresses from DNS seed %s\n", seed);
1667 if (HaveNameProxy()) {
1668 AddAddrFetch(seed);
1669 } else {
1670 std::vector<CAddress> vAdd;
1671 ServiceFlags requiredServiceBits =
1673 std::string host = strprintf("x%x.%s", requiredServiceBits, seed);
1674 CNetAddr resolveSource;
1675 if (!resolveSource.SetInternal(host)) {
1676 continue;
1677 }
1678
1679 // Limits number of IPs learned from a DNS seed
1680 unsigned int nMaxIPs = 256;
1681 const auto addresses{LookupHost(host, nMaxIPs, true)};
1682 if (!addresses.empty()) {
1683 for (const CNetAddr &ip : addresses) {
1684 CAddress addr = CAddress(
1686 requiredServiceBits);
1687 // Use a random age between 3 and 7 days old.
1688 addr.nTime = rng.rand_uniform_delay(
1689 Now<NodeSeconds>() - 3 * 24h, -4 * 24h);
1690 vAdd.push_back(addr);
1691 found++;
1692 }
1693 addrman.Add(vAdd, resolveSource);
1694 } else {
1695 // We now avoid directly using results from DNS Seeds which do
1696 // not support service bit filtering, instead using them as a
1697 // addrfetch to get nodes with our desired service bits.
1698 AddAddrFetch(seed);
1699 }
1700 }
1701 --seeds_right_now;
1702 }
1703 LogPrintf("%d addresses found from DNS seeds\n", found);
1704}
1705
1707 int64_t nStart = GetTimeMillis();
1708
1710
1711 LogDebug(BCLog::NET, "Flushed %d addresses to peers.dat %dms\n",
1712 addrman.size(), GetTimeMillis() - nStart);
1713}
1714
1717 std::string strDest;
1718 {
1720 if (m_addr_fetches.empty()) {
1721 return;
1722 }
1723 strDest = m_addr_fetches.front();
1724 m_addr_fetches.pop_front();
1725 }
1726 CAddress addr;
1727 CSemaphoreGrant grant(*semOutbound, true);
1728 if (grant) {
1729 OpenNetworkConnection(addr, false, &grant, strDest.c_str(),
1731 }
1732}
1733
1737
1740 LogDebug(BCLog::NET, "net: setting try another outbound peer=%s\n",
1741 flag ? "true" : "false");
1742}
1743
1744// Return the number of peers we have over our outbound connection limit.
1745// Exclude peers that are marked for disconnect, or are going to be disconnected
1746// soon (eg ADDR_FETCH and FEELER).
1747// Also exclude peers that haven't finished initial connection handshake yet (so
1748// that we don't decide we're over our desired connection limit, and then evict
1749// some peer that has finished the handshake).
1751 int full_outbound_peers = 0;
1752 {
1754 for (const CNode *pnode : m_nodes) {
1755 if (pnode->fSuccessfullyConnected && !pnode->fDisconnect &&
1756 pnode->IsFullOutboundConn()) {
1757 ++full_outbound_peers;
1758 }
1759 }
1760 }
1761 return std::max(full_outbound_peers - m_max_outbound_full_relay -
1763 0);
1764}
1765
1767 int block_relay_peers = 0;
1768 {
1770 for (const CNode *pnode : m_nodes) {
1771 if (pnode->fSuccessfullyConnected && !pnode->fDisconnect &&
1772 pnode->IsBlockOnlyConn()) {
1773 ++block_relay_peers;
1774 }
1775 }
1776 }
1777 return std::max(block_relay_peers - m_max_outbound_block_relay, 0);
1778}
1779
1781 const std::vector<std::string> connect,
1782 std::function<void(const CAddress &, ConnectionType)> mockOpenConnection) {
1785 // Connect to specific addresses
1786 if (!connect.empty()) {
1787 for (int64_t nLoop = 0;; nLoop++) {
1789 for (const std::string &strAddr : connect) {
1790 CAddress addr(CService(), NODE_NONE);
1791 OpenNetworkConnection(addr, false, nullptr, strAddr.c_str(),
1793 for (int i = 0; i < 10 && i < nLoop; i++) {
1795 std::chrono::milliseconds(500))) {
1796 return;
1797 }
1798 }
1799 }
1800 if (!interruptNet.sleep_for(std::chrono::milliseconds(500))) {
1801 return;
1802 }
1803 }
1804 }
1805
1806 // Initiate network connections
1807 auto start = GetTime<std::chrono::microseconds>();
1808
1809 // Minimum time before next feeler connection (in microseconds
1810 auto next_feeler = start + rng.rand_exp_duration(FEELER_INTERVAL);
1811 auto next_extra_block_relay =
1813 const bool dnsseed = gArgs.GetBoolArg("-dnsseed", DEFAULT_DNSSEED);
1814 bool add_fixed_seeds = gArgs.GetBoolArg("-fixedseeds", DEFAULT_FIXEDSEEDS);
1815 const bool use_seednodes{gArgs.IsArgSet("-seednode")};
1816
1817 if (!add_fixed_seeds) {
1818 LogPrintf("Fixed seeds are disabled\n");
1819 }
1820
1821 while (!interruptNet) {
1823
1824 // No need to sleep the thread if we are mocking the network connection
1825 if (!mockOpenConnection &&
1826 !interruptNet.sleep_for(std::chrono::milliseconds(500))) {
1827 return;
1828 }
1829
1831 if (interruptNet) {
1832 return;
1833 }
1834
1835 if (add_fixed_seeds && addrman.size() == 0) {
1836 // When the node starts with an empty peers.dat, there are a few
1837 // other sources of peers before we fallback on to fixed seeds:
1838 // -dnsseed, -seednode, -addnode If none of those are available, we
1839 // fallback on to fixed seeds immediately, else we allow 60 seconds
1840 // for any of those sources to populate addrman.
1841 bool add_fixed_seeds_now = false;
1842 // It is cheapest to check if enough time has passed first.
1843 if (GetTime<std::chrono::seconds>() >
1844 start + std::chrono::minutes{1}) {
1845 add_fixed_seeds_now = true;
1846 LogPrintf("Adding fixed seeds as 60 seconds have passed and "
1847 "addrman is empty\n");
1848 } else if (!dnsseed && !use_seednodes) {
1849 // Lock the mutex after performing the above cheap checks.
1851 if (m_added_nodes.empty()) {
1852 add_fixed_seeds_now = true;
1853 LogPrintf("Adding fixed seeds as -dnsseed=0 and neither "
1854 "-addnode nor -seednode are provided\n");
1855 }
1856 }
1857
1858 if (add_fixed_seeds_now) {
1859 CNetAddr local;
1860 local.SetInternal("fixedseeds");
1862 local);
1863 add_fixed_seeds = false;
1864 }
1865 }
1866
1867 //
1868 // Choose an address to connect to based on most recently seen
1869 //
1870 CAddress addrConnect;
1871
1872 // Only connect out to one peer per network group (/16 for IPv4).
1873 int nOutboundFullRelay = 0;
1874 int nOutboundBlockRelay = 0;
1875 int nOutboundAvalanche = 0;
1876 std::set<std::vector<uint8_t>> setConnected;
1877
1878 {
1880 for (const CNode *pnode : m_nodes) {
1881 if (pnode->IsAvalancheOutboundConnection()) {
1882 nOutboundAvalanche++;
1883 } else if (pnode->IsFullOutboundConn()) {
1884 nOutboundFullRelay++;
1885 } else if (pnode->IsBlockOnlyConn()) {
1886 nOutboundBlockRelay++;
1887 }
1888
1889 // Netgroups for inbound and manual peers are not excluded
1890 // because our goal here is to not use multiple of our
1891 // limited outbound slots on a single netgroup but inbound
1892 // and manual peers do not use our outbound slots. Inbound
1893 // peers also have the added issue that they could be attacker
1894 // controlled and could be used to prevent us from connecting
1895 // to particular hosts if we used them here.
1896 switch (pnode->m_conn_type) {
1899 break;
1905 setConnected.insert(
1906 pnode->addr.GetGroup(addrman.GetAsmap()));
1907 } // no default case, so the compiler can warn about missing
1908 // cases
1909 }
1910 }
1911
1913 auto now = GetTime<std::chrono::microseconds>();
1914 bool anchor = false;
1915 bool fFeeler = false;
1916
1917 // Determine what type of connection to open. Opening
1918 // BLOCK_RELAY connections to addresses from anchors.dat gets the
1919 // highest priority. Then we open AVALANCHE_OUTBOUND connection until we
1920 // hit our avalanche outbound peer limit, which is 0 if avalanche is not
1921 // enabled. We fallback after 50 retries to OUTBOUND_FULL_RELAY if the
1922 // peer is not avalanche capable until we meet our full-relay capacity.
1923 // Then we open BLOCK_RELAY connection until we hit our block-relay-only
1924 // peer limit.
1925 // GetTryNewOutboundPeer() gets set when a stale tip is detected, so we
1926 // try opening an additional OUTBOUND_FULL_RELAY connection. If none of
1927 // these conditions are met, check to see if it's time to try an extra
1928 // block-relay-only peer (to confirm our tip is current, see below) or
1929 // the next_feeler timer to decide if we should open a FEELER.
1930
1931 if (!m_anchors.empty() &&
1932 (nOutboundBlockRelay < m_max_outbound_block_relay)) {
1933 conn_type = ConnectionType::BLOCK_RELAY;
1934 anchor = true;
1935 } else if (nOutboundAvalanche < m_max_avalanche_outbound) {
1937 } else if (nOutboundFullRelay < m_max_outbound_full_relay) {
1938 // OUTBOUND_FULL_RELAY
1939 } else if (nOutboundBlockRelay < m_max_outbound_block_relay) {
1940 conn_type = ConnectionType::BLOCK_RELAY;
1941 } else if (GetTryNewOutboundPeer()) {
1942 // OUTBOUND_FULL_RELAY
1943 } else if (now > next_extra_block_relay &&
1945 // Periodically connect to a peer (using regular outbound selection
1946 // methodology from addrman) and stay connected long enough to sync
1947 // headers, but not much else.
1948 //
1949 // Then disconnect the peer, if we haven't learned anything new.
1950 //
1951 // The idea is to make eclipse attacks very difficult to pull off,
1952 // because every few minutes we're finding a new peer to learn
1953 // headers from.
1954 //
1955 // This is similar to the logic for trying extra outbound
1956 // (full-relay) peers, except:
1957 // - we do this all the time on an exponential timer, rather than
1958 // just when our tip is stale
1959 // - we potentially disconnect our next-youngest block-relay-only
1960 // peer, if our newest block-relay-only peer delivers a block more
1961 // recently.
1962 // See the eviction logic in net_processing.cpp.
1963 //
1964 // Because we can promote these connections to block-relay-only
1965 // connections, they do not get their own ConnectionType enum
1966 // (similar to how we deal with extra outbound peers).
1967 next_extra_block_relay =
1968 now +
1970 conn_type = ConnectionType::BLOCK_RELAY;
1971 } else if (now > next_feeler) {
1972 next_feeler = now + rng.rand_exp_duration(FEELER_INTERVAL);
1973 conn_type = ConnectionType::FEELER;
1974 fFeeler = true;
1975 } else {
1976 // skip to next iteration of while loop
1977 continue;
1978 }
1979
1981
1982 const auto current_time{NodeClock::now()};
1983 int nTries = 0;
1984 while (!interruptNet) {
1985 if (anchor && !m_anchors.empty()) {
1986 const CAddress addr = m_anchors.back();
1987 m_anchors.pop_back();
1988 if (!addr.IsValid() || IsLocal(addr) || !IsReachable(addr) ||
1990 setConnected.count(addr.GetGroup(addrman.GetAsmap()))) {
1991 continue;
1992 }
1993 addrConnect = addr;
1995 "Trying to make an anchor connection to %s\n",
1996 addrConnect.ToStringAddrPort());
1997 break;
1998 }
1999 // If we didn't find an appropriate destination after trying 100
2000 // addresses fetched from addrman, stop this loop, and let the outer
2001 // loop run again (which sleeps, adds seed nodes, recalculates
2002 // already-connected network ranges, ...) before trying new addrman
2003 // addresses.
2004 nTries++;
2005 if (nTries > 100) {
2006 break;
2007 }
2008
2009 CAddress addr;
2010 NodeSeconds addr_last_try{0s};
2011
2012 if (fFeeler) {
2013 // First, try to get a tried table collision address. This
2014 // returns an empty (invalid) address if there are no collisions
2015 // to try.
2016 std::tie(addr, addr_last_try) = addrman.SelectTriedCollision();
2017
2018 if (!addr.IsValid()) {
2019 // No tried table collisions. Select a new table address
2020 // for our feeler.
2021 std::tie(addr, addr_last_try) = addrman.Select(true);
2022 } else if (AlreadyConnectedToAddress(addr)) {
2023 // If test-before-evict logic would have us connect to a
2024 // peer that we're already connected to, just mark that
2025 // address as Good(). We won't be able to initiate the
2026 // connection anyway, so this avoids inadvertently evicting
2027 // a currently-connected peer.
2028 addrman.Good(addr);
2029 // Select a new table address for our feeler instead.
2030 std::tie(addr, addr_last_try) = addrman.Select(true);
2031 }
2032 } else {
2033 // Not a feeler
2034 std::tie(addr, addr_last_try) = addrman.Select();
2035 }
2036
2037 // Require outbound connections, other than feelers and avalanche,
2038 // to be to distinct network groups
2039 if (!fFeeler && conn_type != ConnectionType::AVALANCHE_OUTBOUND &&
2040 setConnected.count(addr.GetGroup(addrman.GetAsmap()))) {
2041 break;
2042 }
2043
2044 // if we selected an invalid or local address, restart
2045 if (!addr.IsValid() || IsLocal(addr)) {
2046 break;
2047 }
2048
2049 if (!IsReachable(addr)) {
2050 continue;
2051 }
2052
2053 // only consider very recently tried nodes after 30 failed attempts
2054 if (current_time - addr_last_try < 10min && nTries < 30) {
2055 continue;
2056 }
2057
2058 // for non-feelers, require all the services we'll want,
2059 // for feelers, only require they be a full node (only because most
2060 // SPV clients don't have a good address DB available)
2061 if (!fFeeler && !HasAllDesirableServiceFlags(addr.nServices)) {
2062 continue;
2063 }
2064
2065 if (fFeeler && !MayHaveUsefulAddressDB(addr.nServices)) {
2066 continue;
2067 }
2068
2069 // Do not connect to bad ports, unless 50 invalid addresses have
2070 // been selected already.
2071 if (nTries < 50 && (addr.IsIPv4() || addr.IsIPv6()) &&
2072 IsBadPort(addr.GetPort())) {
2073 continue;
2074 }
2075
2076 // For avalanche peers, check they have the avalanche service bit
2077 // set.
2078 if (conn_type == ConnectionType::AVALANCHE_OUTBOUND &&
2079 !(addr.nServices & NODE_AVALANCHE)) {
2080 // If this peer is not suitable as an avalanche one and we tried
2081 // over 20 addresses already, see if we can fallback to a non
2082 // avalanche full outbound.
2083 if (nTries < 20 ||
2084 nOutboundFullRelay >= m_max_outbound_full_relay ||
2085 setConnected.count(addr.GetGroup(addrman.GetAsmap()))) {
2086 // Fallback is not desirable or possible, try another one
2087 continue;
2088 }
2089
2090 // Fallback is possible, update the connection type accordingly
2092 }
2093
2094 addrConnect = addr;
2095 break;
2096 }
2097
2098 if (addrConnect.IsValid()) {
2099 if (fFeeler) {
2100 // Add small amount of random noise before connection to avoid
2101 // synchronization.
2105 return;
2106 }
2107 LogDebug(BCLog::NET, "Making feeler connection to %s\n",
2108 addrConnect.ToStringAddrPort());
2109 }
2110
2111 // This mock is for testing purpose only. It prevents the thread
2112 // from attempting the connection which is useful for testing.
2113 if (mockOpenConnection) {
2114 mockOpenConnection(addrConnect, conn_type);
2115 } else {
2116 OpenNetworkConnection(addrConnect,
2117 int(setConnected.size()) >=
2118 std::min(nMaxConnections - 1, 2),
2119 &grant, nullptr, conn_type);
2120 }
2121 }
2122 }
2123}
2124
2125std::vector<CAddress> CConnman::GetCurrentBlockRelayOnlyConns() const {
2126 std::vector<CAddress> ret;
2128 for (const CNode *pnode : m_nodes) {
2129 if (pnode->IsBlockOnlyConn()) {
2130 ret.push_back(pnode->addr);
2131 }
2132 }
2133
2134 return ret;
2135}
2136
2137std::vector<AddedNodeInfo> CConnman::GetAddedNodeInfo() const {
2138 std::vector<AddedNodeInfo> ret;
2139
2140 std::list<std::string> lAddresses(0);
2141 {
2143 ret.reserve(m_added_nodes.size());
2144 std::copy(m_added_nodes.cbegin(), m_added_nodes.cend(),
2145 std::back_inserter(lAddresses));
2146 }
2147
2148 // Build a map of all already connected addresses (by IP:port and by name)
2149 // to inbound/outbound and resolved CService
2150 std::map<CService, bool> mapConnected;
2151 std::map<std::string, std::pair<bool, CService>> mapConnectedByName;
2152 {
2154 for (const CNode *pnode : m_nodes) {
2155 if (pnode->addr.IsValid()) {
2156 mapConnected[pnode->addr] = pnode->IsInboundConn();
2157 }
2158 std::string addrName{pnode->m_addr_name};
2159 if (!addrName.empty()) {
2160 mapConnectedByName[std::move(addrName)] =
2161 std::make_pair(pnode->IsInboundConn(),
2162 static_cast<const CService &>(pnode->addr));
2163 }
2164 }
2165 }
2166
2167 for (const std::string &strAddNode : lAddresses) {
2168 CService service(
2169 LookupNumeric(strAddNode, Params().GetDefaultPort(strAddNode)));
2170 AddedNodeInfo addedNode{strAddNode, CService(), false, false};
2171 if (service.IsValid()) {
2172 // strAddNode is an IP:port
2173 auto it = mapConnected.find(service);
2174 if (it != mapConnected.end()) {
2175 addedNode.resolvedAddress = service;
2176 addedNode.fConnected = true;
2177 addedNode.fInbound = it->second;
2178 }
2179 } else {
2180 // strAddNode is a name
2181 auto it = mapConnectedByName.find(strAddNode);
2182 if (it != mapConnectedByName.end()) {
2183 addedNode.resolvedAddress = it->second.second;
2184 addedNode.fConnected = true;
2185 addedNode.fInbound = it->second.first;
2186 }
2187 }
2188 ret.emplace_back(std::move(addedNode));
2189 }
2190
2191 return ret;
2192}
2193
2196 while (true) {
2198 std::vector<AddedNodeInfo> vInfo = GetAddedNodeInfo();
2199 bool tried = false;
2200 for (const AddedNodeInfo &info : vInfo) {
2201 if (!info.fConnected) {
2202 if (!grant.TryAcquire()) {
2203 // If we've used up our semaphore and need a new one, let's
2204 // not wait here since while we are waiting the
2205 // addednodeinfo state might change.
2206 break;
2207 }
2208 tried = true;
2209 CAddress addr(CService(), NODE_NONE);
2210 OpenNetworkConnection(addr, false, &grant,
2211 info.strAddedNode.c_str(),
2213 if (!interruptNet.sleep_for(std::chrono::milliseconds(500))) {
2214 return;
2215 }
2216 }
2217 }
2218 // Retry every 60 seconds if a connection was attempted, otherwise two
2219 // seconds.
2220 if (!interruptNet.sleep_for(std::chrono::seconds(tried ? 60 : 2))) {
2221 return;
2222 }
2223 }
2224}
2225
2226// If successful, this moves the passed grant to the constructed node.
2228 bool fCountFailure,
2229 CSemaphoreGrant *grantOutbound,
2230 const char *pszDest,
2231 ConnectionType conn_type) {
2233 assert(conn_type != ConnectionType::INBOUND);
2234
2235 //
2236 // Initiate outbound network connection
2237 //
2238 if (interruptNet) {
2239 return;
2240 }
2241 if (!fNetworkActive) {
2242 return;
2243 }
2244 if (!pszDest) {
2245 bool banned_or_discouraged =
2246 m_banman && (m_banman->IsDiscouraged(addrConnect) ||
2247 m_banman->IsBanned(addrConnect));
2248 if (IsLocal(addrConnect) || banned_or_discouraged ||
2249 AlreadyConnectedToAddress(addrConnect)) {
2250 return;
2251 }
2252 } else if (FindNode(std::string(pszDest))) {
2253 return;
2254 }
2255
2256 CNode *pnode = ConnectNode(addrConnect, pszDest, fCountFailure, conn_type);
2257
2258 if (!pnode) {
2259 return;
2260 }
2261 if (grantOutbound) {
2262 grantOutbound->MoveTo(pnode->grantOutbound);
2263 }
2264
2265 for (auto interface : m_msgproc) {
2266 interface->InitializeNode(*config, *pnode, nLocalServices);
2267 }
2268
2269 {
2271 m_nodes.push_back(pnode);
2272 }
2273}
2274
2276
2279
2280 while (!flagInterruptMsgProc) {
2281 bool fMoreWork = false;
2282
2283 {
2284 // Randomize the order in which we process messages from/to our
2285 // peers. This prevents attacks in which an attacker exploits having
2286 // multiple consecutive connections in the vNodes list.
2287 const NodesSnapshot snap{*this, /*shuffle=*/true};
2288
2289 for (CNode *pnode : snap.Nodes()) {
2290 if (pnode->fDisconnect) {
2291 continue;
2292 }
2293
2294 bool fMoreNodeWork = false;
2295 // Receive messages
2296 for (auto interface : m_msgproc) {
2297 fMoreNodeWork |= interface->ProcessMessages(
2298 *config, pnode, flagInterruptMsgProc);
2299 }
2300 fMoreWork |= (fMoreNodeWork && !pnode->fPauseSend);
2302 return;
2303 }
2304
2305 // Send messages
2306 for (auto interface : m_msgproc) {
2307 interface->SendMessages(*config, pnode);
2308 }
2309
2311 return;
2312 }
2313 }
2314 }
2315
2316 WAIT_LOCK(mutexMsgProc, lock);
2317 if (!fMoreWork) {
2318 condMsgProc.wait_until(lock,
2319 std::chrono::steady_clock::now() +
2320 std::chrono::milliseconds(100),
2321 [this]() EXCLUSIVE_LOCKS_REQUIRED(
2322 mutexMsgProc) { return fMsgProcWake; });
2323 }
2324 fMsgProcWake = false;
2325 }
2326}
2327
2329 static constexpr auto err_wait_begin = 1s;
2330 static constexpr auto err_wait_cap = 5min;
2331 auto err_wait = err_wait_begin;
2332
2333 bool advertising_listen_addr = false;
2334 i2p::Connection conn;
2335
2336 while (!interruptNet) {
2337 if (!m_i2p_sam_session->Listen(conn)) {
2338 if (advertising_listen_addr && conn.me.IsValid()) {
2339 RemoveLocal(conn.me);
2340 advertising_listen_addr = false;
2341 }
2342
2343 interruptNet.sleep_for(err_wait);
2344 if (err_wait < err_wait_cap) {
2345 err_wait *= 2;
2346 }
2347
2348 continue;
2349 }
2350
2351 if (!advertising_listen_addr) {
2352 AddLocal(conn.me, LOCAL_MANUAL);
2353 advertising_listen_addr = true;
2354 }
2355
2356 if (!m_i2p_sam_session->Accept(conn)) {
2357 continue;
2358 }
2359
2361 std::move(conn.sock), NetPermissionFlags::None,
2362 CAddress{conn.me, NODE_NONE}, CAddress{conn.peer, NODE_NONE});
2363 }
2364}
2365
2366bool CConnman::BindListenPort(const CService &addrBind, bilingual_str &strError,
2367 NetPermissionFlags permissions) {
2368 int nOne = 1;
2369
2370 // Create socket for listening for incoming connections
2371 struct sockaddr_storage sockaddr;
2372 socklen_t len = sizeof(sockaddr);
2373 if (!addrBind.GetSockAddr((struct sockaddr *)&sockaddr, &len)) {
2374 strError =
2375 strprintf(Untranslated("Bind address family for %s not supported"),
2376 addrBind.ToStringAddrPort());
2378 strError.original);
2379 return false;
2380 }
2381
2382 std::unique_ptr<Sock> sock =
2383 CreateSock(addrBind.GetSAFamily(), SOCK_STREAM, IPPROTO_TCP);
2384 if (!sock) {
2385 strError =
2386 strprintf(Untranslated("Couldn't open socket for incoming "
2387 "connections (socket returned error %s)"),
2390 strError.original);
2391 return false;
2392 }
2393
2394 // Allow binding if the port is still in TIME_WAIT state after
2395 // the program was closed and restarted.
2396 if (sock->SetSockOpt(SOL_SOCKET, SO_REUSEADDR, (sockopt_arg_type)&nOne,
2397 sizeof(int)) == SOCKET_ERROR) {
2398 strError = strprintf(
2400 "Error setting SO_REUSEADDR on socket: %s, continuing anyway"),
2402 LogPrintf("%s\n", strError.original);
2403 }
2404
2405 // Some systems don't have IPV6_V6ONLY but are always v6only; others do have
2406 // the option and enable it by default or not. Try to enable it, if
2407 // possible.
2408 if (addrBind.IsIPv6()) {
2409#ifdef IPV6_V6ONLY
2410 if (sock->SetSockOpt(IPPROTO_IPV6, IPV6_V6ONLY, (sockopt_arg_type)&nOne,
2411 sizeof(int)) == SOCKET_ERROR) {
2412 strError = strprintf(Untranslated("Error setting IPV6_V6ONLY on "
2413 "socket: %s, continuing anyway"),
2415 LogPrintf("%s\n", strError.original);
2416 }
2417#endif
2418#ifdef WIN32
2419 int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED;
2420 if (sock->SetSockOpt(IPPROTO_IPV6, IPV6_PROTECTION_LEVEL,
2421 (sockopt_arg_type)&nProtLevel,
2422 sizeof(int)) == SOCKET_ERROR) {
2423 strError =
2424 strprintf(Untranslated("Error setting IPV6_PROTECTION_LEVEL on "
2425 "socket: %s, continuing anyway"),
2427 LogPrintf("%s\n", strError.original);
2428 }
2429#endif
2430 }
2431
2432 if (sock->Bind(reinterpret_cast<struct sockaddr *>(&sockaddr), len) ==
2433 SOCKET_ERROR) {
2434 int nErr = WSAGetLastError();
2435 if (nErr == WSAEADDRINUSE) {
2436 strError = strprintf(_("Unable to bind to %s on this computer. %s "
2437 "is probably already running."),
2438 addrBind.ToStringAddrPort(), PACKAGE_NAME);
2439 } else {
2440 strError = strprintf(_("Unable to bind to %s on this computer "
2441 "(bind returned error %s)"),
2442 addrBind.ToStringAddrPort(),
2443 NetworkErrorString(nErr));
2444 }
2445
2447 strError.original);
2448 return false;
2449 }
2450 LogPrintf("Bound to %s\n", addrBind.ToStringAddrPort());
2451
2452 // Listen for incoming connections
2453 if (sock->Listen(SOMAXCONN) == SOCKET_ERROR) {
2454 strError = strprintf(_("Listening for incoming connections "
2455 "failed (listen returned error %s)"),
2458 strError.original);
2459 return false;
2460 }
2461
2462 vhListenSocket.emplace_back(std::move(sock), permissions);
2463 return true;
2464}
2465
2466void Discover() {
2467 if (!fDiscover) {
2468 return;
2469 }
2470
2471 for (const CNetAddr &addr : GetLocalAddresses()) {
2472 if (AddLocal(addr, LOCAL_IF)) {
2473 LogPrintf("%s: %s\n", __func__, addr.ToStringAddr());
2474 }
2475 }
2476}
2477
2479 LogPrintf("%s: %s\n", __func__, active);
2480
2481 if (fNetworkActive == active) {
2482 return;
2483 }
2484
2485 fNetworkActive = active;
2486
2487 if (m_client_interface) {
2488 m_client_interface->NotifyNetworkActiveChanged(fNetworkActive);
2489 }
2490}
2491
2492CConnman::CConnman(const Config &configIn, uint64_t nSeed0In, uint64_t nSeed1In,
2493 AddrMan &addrmanIn, bool network_active)
2494 : config(&configIn), addrman(addrmanIn), nSeed0(nSeed0In),
2495 nSeed1(nSeed1In) {
2496 SetTryNewOutboundPeer(false);
2497
2498 Options connOptions;
2499 Init(connOptions);
2500 SetNetworkActive(network_active);
2501}
2502
2504 return nLastNodeId.fetch_add(1);
2505}
2506
2507bool CConnman::Bind(const CService &addr, unsigned int flags,
2508 NetPermissionFlags permissions) {
2509 if (!(flags & BF_EXPLICIT) && !IsReachable(addr)) {
2510 return false;
2511 }
2512 bilingual_str strError;
2513 if (!BindListenPort(addr, strError, permissions)) {
2515 m_client_interface->ThreadSafeMessageBox(
2516 strError, "", CClientUIInterface::MSG_ERROR);
2517 }
2518 return false;
2519 }
2520
2521 if (addr.IsRoutable() && fDiscover && !(flags & BF_DONT_ADVERTISE) &&
2523 AddLocal(addr, LOCAL_BIND);
2524 }
2525
2526 return true;
2527}
2528
2529bool CConnman::InitBinds(const Options &options) {
2530 for (const auto &addrBind : options.vBinds) {
2531 if (!Bind(addrBind, BF_EXPLICIT | BF_REPORT_ERROR,
2533 return false;
2534 }
2535 }
2536 for (const auto &addrBind : options.vWhiteBinds) {
2537 if (!Bind(addrBind.m_service, BF_EXPLICIT | BF_REPORT_ERROR,
2538 addrBind.m_flags)) {
2539 return false;
2540 }
2541 }
2542 for (const auto &addr_bind : options.onion_binds) {
2545 return false;
2546 }
2547 }
2548 if (options.bind_on_any) {
2549 // Don't consider errors to bind on IPv6 "::" fatal because the host OS
2550 // may not have IPv6 support and the user did not explicitly ask us to
2551 // bind on that.
2552 const CService ipv6_any{in6_addr(IN6ADDR_ANY_INIT),
2553 GetListenPort()}; // ::
2555
2556 struct in_addr inaddr_any;
2557 inaddr_any.s_addr = htonl(INADDR_ANY);
2558 const CService ipv4_any{inaddr_any, GetListenPort()}; // 0.0.0.0
2560 return false;
2561 }
2562 }
2563 return true;
2564}
2565
2566bool CConnman::Start(CScheduler &scheduler, const Options &connOptions) {
2567 Init(connOptions);
2568
2569 if (fListen && !InitBinds(connOptions)) {
2570 if (m_client_interface) {
2571 m_client_interface->ThreadSafeMessageBox(
2572 _("Failed to listen on any port. Use -listen=0 if you want "
2573 "this."),
2575 }
2576 return false;
2577 }
2578
2579 Proxy i2p_sam;
2580 if (GetProxy(NET_I2P, i2p_sam) && connOptions.m_i2p_accept_incoming) {
2581 m_i2p_sam_session = std::make_unique<i2p::sam::Session>(
2582 gArgs.GetDataDirNet() / "i2p_private_key", i2p_sam, &interruptNet);
2583 }
2584
2585 for (const auto &strDest : connOptions.vSeedNodes) {
2586 AddAddrFetch(strDest);
2587 }
2588
2590 // Load addresses from anchors.dat
2591 m_anchors =
2596 }
2597 LogPrintf(
2598 "%i block-relay-only anchors will be tried for connections.\n",
2599 m_anchors.size());
2600 }
2601
2602 if (m_client_interface) {
2603 m_client_interface->InitMessage(
2604 _("Starting network threads...").translated);
2605 }
2606
2607 fAddressesInitialized = true;
2608
2609 if (semOutbound == nullptr) {
2610 // initialize semaphore
2611 semOutbound = std::make_unique<CSemaphore>(
2612 std::min(m_max_outbound, nMaxConnections));
2613 }
2614 if (semAddnode == nullptr) {
2615 // initialize semaphore
2616 semAddnode = std::make_unique<CSemaphore>(nMaxAddnode);
2617 }
2618
2619 //
2620 // Start threads
2621 //
2622 assert(m_msgproc.size() > 0);
2623 InterruptSocks5(false);
2625 flagInterruptMsgProc = false;
2626
2627 {
2629 fMsgProcWake = false;
2630 }
2631
2632 // Send and receive from sockets, accept connections
2633 threadSocketHandler = std::thread(&util::TraceThread, "net",
2634 [this] { ThreadSocketHandler(); });
2635
2636 if (!gArgs.GetBoolArg("-dnsseed", DEFAULT_DNSSEED)) {
2637 LogPrintf("DNS seeding disabled\n");
2638 } else {
2639 threadDNSAddressSeed = std::thread(&util::TraceThread, "dnsseed",
2640 [this] { ThreadDNSAddressSeed(); });
2641 }
2642
2643 // Initiate manual connections
2644 threadOpenAddedConnections = std::thread(
2645 &util::TraceThread, "addcon", [this] { ThreadOpenAddedConnections(); });
2646
2647 if (connOptions.m_use_addrman_outgoing &&
2648 !connOptions.m_specified_outgoing.empty()) {
2649 if (m_client_interface) {
2650 m_client_interface->ThreadSafeMessageBox(
2651 _("Cannot provide specific connections and have addrman find "
2652 "outgoing connections at the same."),
2654 }
2655 return false;
2656 }
2657 if (connOptions.m_use_addrman_outgoing ||
2658 !connOptions.m_specified_outgoing.empty()) {
2660 std::thread(&util::TraceThread, "opencon",
2661 [this, connect = connOptions.m_specified_outgoing] {
2662 ThreadOpenConnections(connect, nullptr);
2663 });
2664 }
2665
2666 // Process messages
2667 threadMessageHandler = std::thread(&util::TraceThread, "msghand",
2668 [this] { ThreadMessageHandler(); });
2669
2670 if (m_i2p_sam_session) {
2672 std::thread(&util::TraceThread, "i2paccept",
2673 [this] { ThreadI2PAcceptIncoming(); });
2674 }
2675
2676 // Dump network addresses
2677 scheduler.scheduleEvery(
2678 [this]() {
2679 this->DumpAddresses();
2680 return true;
2681 },
2683
2684 return true;
2685}
2686
2688public:
2689 CNetCleanup() = default;
2690
2692#ifdef WIN32
2693 // Shutdown Windows Sockets
2694 WSACleanup();
2695#endif
2696 }
2697};
2699
2701 {
2703 flagInterruptMsgProc = true;
2704 }
2705 condMsgProc.notify_all();
2706
2707 interruptNet();
2708 InterruptSocks5(true);
2709
2710 if (semOutbound) {
2711 for (int i = 0; i < m_max_outbound; i++) {
2712 semOutbound->post();
2713 }
2714 }
2715
2716 if (semAddnode) {
2717 for (int i = 0; i < nMaxAddnode; i++) {
2718 semAddnode->post();
2719 }
2720 }
2721}
2722
2724 if (threadI2PAcceptIncoming.joinable()) {
2726 }
2727 if (threadMessageHandler.joinable()) {
2728 threadMessageHandler.join();
2729 }
2730 if (threadOpenConnections.joinable()) {
2731 threadOpenConnections.join();
2732 }
2733 if (threadOpenAddedConnections.joinable()) {
2735 }
2736 if (threadDNSAddressSeed.joinable()) {
2737 threadDNSAddressSeed.join();
2738 }
2739 if (threadSocketHandler.joinable()) {
2740 threadSocketHandler.join();
2741 }
2742}
2743
2746 DumpAddresses();
2747 fAddressesInitialized = false;
2748
2750 // Anchor connections are only dumped during clean shutdown.
2751 std::vector<CAddress> anchors_to_dump =
2753 if (anchors_to_dump.size() > MAX_BLOCK_RELAY_ONLY_ANCHORS) {
2754 anchors_to_dump.resize(MAX_BLOCK_RELAY_ONLY_ANCHORS);
2755 }
2758 anchors_to_dump);
2759 }
2760 }
2761
2762 // Delete peer connections.
2763 std::vector<CNode *> nodes;
2764 WITH_LOCK(m_nodes_mutex, nodes.swap(m_nodes));
2765 for (CNode *pnode : nodes) {
2766 pnode->CloseSocketDisconnect();
2767 DeleteNode(pnode);
2768 }
2769
2770 for (CNode *pnode : m_nodes_disconnected) {
2771 DeleteNode(pnode);
2772 }
2773 m_nodes_disconnected.clear();
2774 vhListenSocket.clear();
2775 semOutbound.reset();
2776 semAddnode.reset();
2777}
2778
2780 assert(pnode);
2781 for (auto interface : m_msgproc) {
2782 interface->FinalizeNode(*config, *pnode);
2783 }
2784 delete pnode;
2785}
2786
2788 Interrupt();
2789 Stop();
2790}
2791
2792std::vector<CAddress>
2793CConnman::GetAddresses(size_t max_addresses, size_t max_pct,
2794 std::optional<Network> network) const {
2795 std::vector<CAddress> addresses =
2796 addrman.GetAddr(max_addresses, max_pct, network);
2797 if (m_banman) {
2798 addresses.erase(std::remove_if(addresses.begin(), addresses.end(),
2799 [this](const CAddress &addr) {
2800 return m_banman->IsDiscouraged(
2801 addr) ||
2802 m_banman->IsBanned(addr);
2803 }),
2804 addresses.end());
2805 }
2806 return addresses;
2807}
2808
2809std::vector<CAddress>
2810CConnman::GetAddresses(CNode &requestor, size_t max_addresses, size_t max_pct) {
2811 auto local_socket_bytes = requestor.addrBind.GetAddrBytes();
2813 .Write(requestor.addr.GetNetwork())
2814 .Write(local_socket_bytes)
2815 .Finalize();
2816 const auto current_time = GetTime<std::chrono::microseconds>();
2817 auto r = m_addr_response_caches.emplace(cache_id, CachedAddrResponse{});
2818 CachedAddrResponse &cache_entry = r.first->second;
2819 // New CachedAddrResponse have expiration 0.
2820 if (cache_entry.m_cache_entry_expiration < current_time) {
2821 cache_entry.m_addrs_response_cache =
2822 GetAddresses(max_addresses, max_pct, /* network */ std::nullopt);
2823 // Choosing a proper cache lifetime is a trade-off between the privacy
2824 // leak minimization and the usefulness of ADDR responses to honest
2825 // users.
2826 //
2827 // Longer cache lifetime makes it more difficult for an attacker to
2828 // scrape enough AddrMan data to maliciously infer something useful. By
2829 // the time an attacker scraped enough AddrMan records, most of the
2830 // records should be old enough to not leak topology info by e.g.
2831 // analyzing real-time changes in timestamps.
2832 //
2833 // It takes only several hundred requests to scrape everything from an
2834 // AddrMan containing 100,000 nodes, so ~24 hours of cache lifetime
2835 // indeed makes the data less inferable by the time most of it could be
2836 // scraped (considering that timestamps are updated via ADDR
2837 // self-announcements and when nodes communicate). We also should be
2838 // robust to those attacks which may not require scraping *full*
2839 // victim's AddrMan (because even several timestamps of the same handful
2840 // of nodes may leak privacy).
2841 //
2842 // On the other hand, longer cache lifetime makes ADDR responses
2843 // outdated and less useful for an honest requestor, e.g. if most nodes
2844 // in the ADDR response are no longer active.
2845 //
2846 // However, the churn in the network is known to be rather low. Since we
2847 // consider nodes to be "terrible" (see IsTerrible()) if the timestamps
2848 // are older than 30 days, max. 24 hours of "penalty" due to cache
2849 // shouldn't make any meaningful difference in terms of the freshness of
2850 // the response.
2851 cache_entry.m_cache_entry_expiration =
2852 current_time + 21h +
2853 FastRandomContext().randrange<std::chrono::microseconds>(6h);
2854 }
2855 return cache_entry.m_addrs_response_cache;
2856}
2857
2858bool CConnman::AddNode(const std::string &strNode) {
2860 for (const std::string &it : m_added_nodes) {
2861 if (strNode == it) {
2862 return false;
2863 }
2864 }
2865
2866 m_added_nodes.push_back(strNode);
2867 return true;
2868}
2869
2870bool CConnman::RemoveAddedNode(const std::string &strNode) {
2872 for (std::vector<std::string>::iterator it = m_added_nodes.begin();
2873 it != m_added_nodes.end(); ++it) {
2874 if (strNode == *it) {
2875 m_added_nodes.erase(it);
2876 return true;
2877 }
2878 }
2879 return false;
2880}
2881
2884 // Shortcut if we want total
2886 return m_nodes.size();
2887 }
2888
2889 int nNum = 0;
2890 for (const auto &pnode : m_nodes) {
2891 if (flags & (pnode->IsInboundConn() ? ConnectionDirection::In
2893 nNum++;
2894 }
2895 }
2896
2897 return nNum;
2898}
2899
2900void CConnman::GetNodeStats(std::vector<CNodeStats> &vstats) const {
2901 vstats.clear();
2903 vstats.reserve(m_nodes.size());
2904 for (CNode *pnode : m_nodes) {
2905 vstats.emplace_back();
2906 pnode->copyStats(vstats.back());
2907 vstats.back().m_mapped_as = pnode->addr.GetMappedAS(addrman.GetAsmap());
2908 }
2909}
2910
2913
2914 for (auto &&pnode : m_nodes) {
2915 if (pnode->GetId() == id) {
2916 pnode->copyStats(stats);
2917 stats.m_mapped_as = pnode->addr.GetMappedAS(addrman.GetAsmap());
2918 return true;
2919 }
2920 }
2921
2922 return false;
2923}
2924
2925bool CConnman::DisconnectNode(const std::string &strNode) {
2927 if (CNode *pnode = FindNode(strNode)) {
2929 "disconnect by address%s matched peer=%d; disconnecting\n",
2930 (fLogIPs ? strprintf("=%s", strNode) : ""), pnode->GetId());
2931 pnode->fDisconnect = true;
2932 return true;
2933 }
2934 return false;
2935}
2936
2938 bool disconnected = false;
2940 for (CNode *pnode : m_nodes) {
2941 if (subnet.Match(pnode->addr)) {
2943 "disconnect by subnet%s matched peer=%d; disconnecting\n",
2944 (fLogIPs ? strprintf("=%s", subnet.ToString()) : ""),
2945 pnode->GetId());
2946 pnode->fDisconnect = true;
2947 disconnected = true;
2948 }
2949 }
2950 return disconnected;
2951}
2952
2954 return DisconnectNode(CSubNet(addr));
2955}
2956
2959 for (CNode *pnode : m_nodes) {
2960 if (id == pnode->GetId()) {
2961 LogDebug(BCLog::NET, "disconnect by id peer=%d; disconnecting\n",
2962 pnode->GetId());
2963 pnode->fDisconnect = true;
2964 return true;
2965 }
2966 }
2967 return false;
2968}
2969
2970void CConnman::RecordBytesRecv(uint64_t bytes) {
2971 nTotalBytesRecv += bytes;
2972}
2973
2974void CConnman::RecordBytesSent(uint64_t bytes) {
2976 nTotalBytesSent += bytes;
2977
2978 const auto now = GetTime<std::chrono::seconds>();
2979 if (nMaxOutboundCycleStartTime + MAX_UPLOAD_TIMEFRAME < now) {
2980 // timeframe expired, reset cycle
2981 nMaxOutboundCycleStartTime = now;
2982 nMaxOutboundTotalBytesSentInCycle = 0;
2983 }
2984
2985 // TODO, exclude peers with download permission
2986 nMaxOutboundTotalBytesSentInCycle += bytes;
2987}
2988
2991 return nMaxOutboundLimit;
2992}
2993
2994std::chrono::seconds CConnman::GetMaxOutboundTimeframe() const {
2995 return MAX_UPLOAD_TIMEFRAME;
2996}
2997
2998std::chrono::seconds CConnman::GetMaxOutboundTimeLeftInCycle() const {
3000 if (nMaxOutboundLimit == 0) {
3001 return 0s;
3002 }
3003
3004 if (nMaxOutboundCycleStartTime.count() == 0) {
3005 return MAX_UPLOAD_TIMEFRAME;
3006 }
3007
3008 const std::chrono::seconds cycleEndTime =
3009 nMaxOutboundCycleStartTime + MAX_UPLOAD_TIMEFRAME;
3010 const auto now = GetTime<std::chrono::seconds>();
3011 return (cycleEndTime < now) ? 0s : cycleEndTime - now;
3012}
3013
3014bool CConnman::OutboundTargetReached(bool historicalBlockServingLimit) const {
3016 if (nMaxOutboundLimit == 0) {
3017 return false;
3018 }
3019
3020 if (historicalBlockServingLimit) {
3021 // keep a large enough buffer to at least relay each block once.
3022 const std::chrono::seconds timeLeftInCycle =
3024 const uint64_t buffer =
3025 timeLeftInCycle / std::chrono::minutes{10} * ONE_MEGABYTE;
3026 if (buffer >= nMaxOutboundLimit ||
3027 nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit - buffer) {
3028 return true;
3029 }
3030 } else if (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit) {
3031 return true;
3032 }
3033
3034 return false;
3035}
3036
3039 if (nMaxOutboundLimit == 0) {
3040 return 0;
3041 }
3042
3043 return (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit)
3044 ? 0
3045 : nMaxOutboundLimit - nMaxOutboundTotalBytesSentInCycle;
3046}
3047
3049 return nTotalBytesRecv;
3050}
3051
3054 return nTotalBytesSent;
3055}
3056
3060
3061void CNode::invsPolled(uint32_t count) {
3062 invCounters += count;
3063}
3064
3065void CNode::invsVoted(uint32_t count) {
3066 invCounters += uint64_t(count) << 32;
3067}
3068
3069void CNode::updateAvailabilityScore(double decayFactor) {
3070 if (!m_avalanche_enabled) {
3071 return;
3072 }
3073
3074 uint64_t windowInvCounters = invCounters.exchange(0);
3075 double previousScore = availabilityScore;
3076
3077 int64_t polls = windowInvCounters & std::numeric_limits<uint32_t>::max();
3078 int64_t votes = windowInvCounters >> 32;
3079
3081 decayFactor * (2 * votes - polls) + (1. - decayFactor) * previousScore;
3082}
3083
3085 // The score is set atomically so there is no need to lock the statistics
3086 // when reading.
3087 return availabilityScore;
3088}
3089
3090CNode::CNode(NodeId idIn, std::shared_ptr<Sock> sock, const CAddress &addrIn,
3091 uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn,
3092 uint64_t nLocalExtraEntropyIn, const CAddress &addrBindIn,
3093 const std::string &addrNameIn, ConnectionType conn_type_in,
3094 bool inbound_onion, CNodeOptions &&node_opts)
3095 : m_deserializer{std::make_unique<V1TransportDeserializer>(
3097 m_serializer{
3099 m_permission_flags{node_opts.permission_flags}, m_sock{sock},
3100 m_connected(GetTime<std::chrono::seconds>()), addr{addrIn},
3101 addrBind{addrBindIn},
3102 m_addr_name{addrNameIn.empty() ? addr.ToStringAddrPort() : addrNameIn},
3103 m_inbound_onion{inbound_onion}, m_prefer_evict{node_opts.prefer_evict},
3104 nKeyedNetGroup{nKeyedNetGroupIn}, m_conn_type{conn_type_in}, id{idIn},
3105 nLocalHostNonce{nLocalHostNonceIn},
3106 nLocalExtraEntropy{nLocalExtraEntropyIn},
3107 m_recv_flood_size{node_opts.recv_flood_size},
3108 m_i2p_sam_session{std::move(node_opts.i2p_sam_session)} {
3109 if (inbound_onion) {
3110 assert(conn_type_in == ConnectionType::INBOUND);
3111 }
3112
3113 for (const std::string &msg : getAllNetMessageTypes()) {
3114 mapRecvBytesPerMsgType[msg] = 0;
3115 }
3116 mapRecvBytesPerMsgType[NET_MESSAGE_TYPE_OTHER] = 0;
3117
3118 if (fLogIPs) {
3119 LogDebug(BCLog::NET, "Added connection to %s peer=%d\n", m_addr_name,
3120 id);
3121 } else {
3122 LogDebug(BCLog::NET, "Added connection peer=%d\n", id);
3123 }
3124}
3125
3128
3129 size_t nSizeAdded = 0;
3130 for (const auto &msg : vRecvMsg) {
3131 // vRecvMsg contains only completed CNetMessage
3132 // the single possible partially deserialized message are held by
3133 // TransportDeserializer
3134 nSizeAdded += msg.m_raw_message_size;
3135 }
3136
3138 m_msg_process_queue.splice(m_msg_process_queue.end(), vRecvMsg);
3139 m_msg_process_queue_size += nSizeAdded;
3140 pauseRecv(m_msg_process_queue_size > m_recv_flood_size);
3141}
3142
3143std::optional<std::pair<CNetMessage, bool>> CNode::PollMessage() {
3145 if (m_msg_process_queue.empty()) {
3146 return std::nullopt;
3147 }
3148
3149 std::list<CNetMessage> msgs;
3150 // Just take one message
3151 msgs.splice(msgs.begin(), m_msg_process_queue, m_msg_process_queue.begin());
3152 m_msg_process_queue_size -= msgs.front().m_raw_message_size;
3153 pauseRecv(m_msg_process_queue_size > m_recv_flood_size);
3154
3155 return std::make_pair(std::move(msgs.front()),
3156 !m_msg_process_queue.empty());
3157}
3158
3160 return pnode && pnode->fSuccessfullyConnected && !pnode->fDisconnect;
3161}
3162
3164 size_t nMessageSize = msg.data.size();
3165 LogDebug(BCLog::NETDEBUG, "sending %s (%d bytes) peer=%d\n", msg.m_type,
3166 nMessageSize, pnode->GetId());
3167 if (gArgs.GetBoolArg("-capturemessages", false)) {
3168 CaptureMessage(pnode->addr, msg.m_type, msg.data,
3169 /*is_incoming=*/false);
3170 }
3171
3172 TRACE6(net, outbound_message, pnode->GetId(), pnode->m_addr_name.c_str(),
3173 pnode->ConnectionTypeAsString().c_str(), msg.m_type.c_str(),
3174 msg.data.size(), msg.data.data());
3175
3176 // make sure we use the appropriate network transport format
3177 std::vector<uint8_t> serializedHeader;
3178 pnode->m_serializer->prepareForTransport(*config, msg, serializedHeader);
3179 size_t nTotalSize = nMessageSize + serializedHeader.size();
3180
3181 size_t nBytesSent = 0;
3182 {
3183 LOCK(pnode->cs_vSend);
3184 bool optimisticSend(pnode->vSendMsg.empty());
3185
3186 // log total amount of bytes per message type
3187 pnode->AccountForSentBytes(msg.m_type, nTotalSize);
3188 pnode->nSendSize += nTotalSize;
3189
3190 if (pnode->nSendSize > nSendBufferMaxSize) {
3191 pnode->fPauseSend = true;
3192 }
3193 pnode->vSendMsg.push_back(std::move(serializedHeader));
3194 if (nMessageSize) {
3195 pnode->vSendMsg.push_back(std::move(msg.data));
3196 }
3197
3198 // If write queue empty, attempt "optimistic write"
3199 bool data_left;
3200 if (optimisticSend) {
3201 std::tie(nBytesSent, data_left) = SocketSendData(*pnode);
3202 }
3203 }
3204 if (nBytesSent) {
3205 RecordBytesSent(nBytesSent);
3206 }
3207}
3208
3209bool CConnman::ForNode(NodeId id, std::function<bool(CNode *pnode)> func) {
3210 CNode *found = nullptr;
3212 for (auto &&pnode : m_nodes) {
3213 if (pnode->GetId() == id) {
3214 found = pnode;
3215 break;
3216 }
3217 }
3218 return found != nullptr && NodeFullyConnected(found) && func(found);
3219}
3220
3222 return CSipHasher(nSeed0, nSeed1).Write(id);
3223}
3224
3226 std::vector<uint8_t> vchNetGroup(ad.GetGroup(addrman.GetAsmap()));
3227
3229 .Write(vchNetGroup)
3230 .Finalize();
3231}
3232
3247std::string getSubVersionEB(uint64_t MaxBlockSize) {
3248 // Prepare EB string we are going to add to SubVer:
3249 // 1) translate from byte to MB and convert to string
3250 // 2) limit the EB string to the first decimal digit (floored)
3251 std::stringstream ebMBs;
3252 ebMBs << (MaxBlockSize / (ONE_MEGABYTE / 10));
3253 std::string eb = ebMBs.str();
3254 eb.insert(eb.size() - 1, ".", 1);
3255 if (eb.substr(0, 1) == ".") {
3256 eb = "0" + eb;
3257 }
3258 return eb;
3259}
3260
3261std::string userAgent(const Config &config) {
3262 // format excessive blocksize value
3263 std::string eb = getSubVersionEB(config.GetMaxBlockSize());
3264 std::vector<std::string> uacomments;
3265 uacomments.push_back("EB" + eb);
3266
3267 // Comments are checked for char compliance at startup, it is safe to add
3268 // them to the user agent string
3269 for (const std::string &cmt : gArgs.GetArgs("-uacomment")) {
3270 uacomments.push_back(cmt);
3271 }
3272
3273 const std::string client_name = gArgs.GetArg("-uaclientname", CLIENT_NAME);
3274 const std::string client_version =
3275 gArgs.GetArg("-uaclientversion", FormatVersion(CLIENT_VERSION));
3276
3277 // Size compliance is checked at startup, it is safe to not check it again
3278 return FormatUserAgent(client_name, client_version, uacomments);
3279}
3280
3281void CaptureMessageToFile(const CAddress &addr, const std::string &msg_type,
3282 Span<const uint8_t> data, bool is_incoming) {
3283 // Note: This function captures the message at the time of processing,
3284 // not at socket receive/send time.
3285 // This ensures that the messages are always in order from an application
3286 // layer (processing) perspective.
3287 auto now = GetTime<std::chrono::microseconds>();
3288
3289 // Windows folder names can not include a colon
3290 std::string clean_addr = addr.ToStringAddrPort();
3291 std::replace(clean_addr.begin(), clean_addr.end(), ':', '_');
3292
3293 fs::path base_path = gArgs.GetDataDirNet() / "message_capture" / clean_addr;
3294 fs::create_directories(base_path);
3295
3296 fs::path path =
3297 base_path / (is_incoming ? "msgs_recv.dat" : "msgs_sent.dat");
3298 AutoFile f{fsbridge::fopen(path, "ab")};
3299
3300 ser_writedata64(f, now.count());
3301 f << Span{msg_type};
3302 for (auto i = msg_type.length(); i < CMessageHeader::MESSAGE_TYPE_SIZE;
3303 ++i) {
3304 f << uint8_t{'\0'};
3305 }
3306 uint32_t size = data.size();
3307 ser_writedata32(f, size);
3308 f << data;
3309}
3310
3311std::function<void(const CAddress &addr, const std::string &msg_type,
3312 Span<const uint8_t> data, bool is_incoming)>
std::vector< CAddress > ReadAnchors(const CChainParams &chainParams, const fs::path &anchors_db_path)
Read the anchor IP address database (anchors.dat)
Definition addrdb.cpp:334
bool DumpPeerAddresses(const CChainParams &chainParams, const ArgsManager &args, const AddrMan &addr)
Definition addrdb.cpp:259
void DumpAnchors(const CChainParams &chainParams, const fs::path &anchors_db_path, const std::vector< CAddress > &anchors)
Dump the anchor IP address database (anchors.dat)
Definition addrdb.cpp:324
ArgsManager gArgs
Definition args.cpp:39
int flags
const CChainParams & Params()
Return the currently selected parameters.
Stochastic address manager.
Definition addrman.h:68
std::vector< CAddress > GetAddr(size_t max_addresses, size_t max_pct, std::optional< Network > network) const
Return all or many randomly selected addresses, optionally by network.
Definition addrman.cpp:1317
const std::vector< bool > & GetAsmap() const
Definition addrman.cpp:1330
void Attempt(const CService &addr, bool fCountFailure, NodeSeconds time=Now< NodeSeconds >())
Mark an entry as connection attempted to.
Definition addrman.cpp:1300
std::pair< CAddress, NodeSeconds > Select(bool newOnly=false) const
Choose an address to connect to.
Definition addrman.cpp:1313
void ResolveCollisions()
See if any to-be-evicted tried table entries have been tested and if so resolve the collisions.
Definition addrman.cpp:1305
size_t size() const
Return the number of (unique) addresses in all tables.
Definition addrman.cpp:1286
void Good(const CService &addr, bool test_before_evict=true, NodeSeconds time=Now< NodeSeconds >())
Mark an entry as accessible, possibly moving it from "new" to "tried".
Definition addrman.cpp:1295
std::pair< CAddress, NodeSeconds > SelectTriedCollision()
Randomly select an address in the tried table that another address is attempting to evict.
Definition addrman.cpp:1309
bool Add(const std::vector< CAddress > &vAddr, const CNetAddr &source, std::chrono::seconds time_penalty=0s)
Attempt to add one or more addresses to addrman's new table.
Definition addrman.cpp:1290
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition args.cpp:361
fs::path GetDataDirNet() const
Get data directory path with appended network identifier.
Definition args.h:239
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition args.cpp:371
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition args.cpp:494
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition args.cpp:462
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition args.cpp:524
Non-refcounted RAII wrapper for FILE*.
Definition streams.h:433
bool IsBanned(const CNetAddr &net_addr)
Return whether net_addr is banned.
Definition banman.cpp:83
bool IsDiscouraged(const CNetAddr &net_addr)
Return whether net_addr is discouraged.
Definition banman.cpp:78
A CService with information about it as peer.
Definition protocol.h:441
ServiceFlags nServices
Serialized as uint64_t in V1, and as CompactSize in V2.
Definition protocol.h:553
NodeSeconds nTime
Always included in serialization, except in the network format on INIT_PROTO_VERSION.
Definition protocol.h:551
const CMessageHeader::MessageMagic & NetMagic() const
const std::vector< SeedSpec6 > & FixedSeeds() const
uint16_t GetDefaultPort() const
RAII helper to atomically create a copy of m_nodes and add a reference to each of the nodes.
Definition net.h:1424
bool whitelist_relay
flag for adding 'relay' permission to whitelisted inbound and manual peers with default permissions.
Definition net.h:1415
std::condition_variable condMsgProc
Definition net.h:1339
bool AddConnection(const std::string &address, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Attempts to open a connection.
Definition net.cpp:1180
std::thread threadMessageHandler
Definition net.h:1362
std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const
returns the time in second left in the current max outbound cycle in case of no limit,...
Definition net.cpp:2998
bool OutboundTargetReached(bool historicalBlockServingLimit) const
check if the outbound target is reached.
Definition net.cpp:3014
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition net.h:1239
CClientUIInterface * m_client_interface
Definition net.h:1318
void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition net.cpp:2277
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition net.cpp:3209
void DeleteNode(CNode *pnode)
Definition net.cpp:2779
bool RemoveAddedNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition net.cpp:2870
bool AttemptToEvictConnection()
Try to find a connection to evict when the node is full.
Definition net.cpp:986
bool AlreadyConnectedToAddress(const CAddress &addr)
Determine whether we're already connected to a given address, in order to avoid initiating duplicate ...
Definition net.cpp:394
int m_max_outbound
Definition net.h:1316
static constexpr size_t MAX_UNUSED_I2P_SESSIONS_SIZE
Cap on the size of m_unused_i2p_sessions, to ensure it does not unexpectedly use too much memory.
Definition net.h:1403
bool GetTryNewOutboundPeer() const
Definition net.cpp:1734
void Stop()
Definition net.h:924
int m_max_outbound_block_relay
Definition net.h:1309
std::thread threadI2PAcceptIncoming
Definition net.h:1363
void SetTryNewOutboundPeer(bool flag)
Definition net.cpp:1738
std::atomic< bool > flagInterruptMsgProc
Definition net.h:1341
void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition net.cpp:2700
void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition net.cpp:1571
Sock::EventsPerSock GenerateWaitSockets(Span< CNode *const > nodes)
Generate a collection of sockets to check for IO readiness.
Definition net.cpp:1366
void SocketHandlerConnected(const std::vector< CNode * > &nodes, const Sock::EventsPerSock &events_per_sock) EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Do the read/write for connected sockets that are ready for IO.
Definition net.cpp:1428
NodeId GetNewNodeId()
Definition net.cpp:2503
CThreadInterrupt interruptNet
This is signaled when network activity should cease.
Definition net.h:1349
std::unique_ptr< CSemaphore > semAddnode
Definition net.h:1301
bool Start(CScheduler &scheduler, const Options &options) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition net.cpp:2566
std::atomic< NodeId > nLastNodeId
Definition net.h:1257
void RecordBytesSent(uint64_t bytes)
Definition net.cpp:2974
int GetExtraBlockRelayCount() const
Definition net.cpp:1766
void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition net.cpp:1563
BanMan * m_banman
Pointer to this node's banman.
Definition net.h:1325
uint64_t GetOutboundTargetBytesLeft() const
response the bytes left in the current max outbound cycle in case of no limit, it will always respons...
Definition net.cpp:3037
std::thread threadDNSAddressSeed
Definition net.h:1358
std::atomic< ServiceFlags > nLocalServices
Services this node offers.
Definition net.h:1298
void ThreadI2PAcceptIncoming()
Definition net.cpp:2328
const uint64_t nSeed1
Definition net.h:1334
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
Definition net.h:1331
std::chrono::seconds GetMaxOutboundTimeframe() const
Definition net.cpp:2994
bool whitelist_forcerelay
flag for adding 'forcerelay' permission to whitelisted inbound and manual peers with default permissi...
Definition net.h:1409
unsigned int nPrevNodeCount
Definition net.h:1258
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, std::optional< CNetAddr > addr, const std::vector< NetWhitelistPermissions > &ranges) const
Definition net.cpp:604
void NotifyNumConnectionsChanged()
Definition net.cpp:1280
ServiceFlags GetLocalServices() const
Used to convey which local services we are offering peers during node connection.
Definition net.cpp:3057
bool DisconnectNode(const std::string &node)
Definition net.cpp:2925
std::chrono::seconds m_peer_connect_timeout
Definition net.h:1235
std::atomic_bool m_try_another_outbound_peer
flag for deciding to connect to an extra outbound peer, in excess of m_max_outbound_full_relay.
Definition net.h:1369
bool InitBinds(const Options &options)
Definition net.cpp:2529
void AddAddrFetch(const std::string &strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex)
Definition net.cpp:135
std::vector< ListenSocket > vhListenSocket
Definition net.h:1246
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *strDest, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Definition net.cpp:2227
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const
Return vector of current BLOCK_RELAY peers.
Definition net.cpp:2125
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition net.cpp:3221
uint64_t GetMaxOutboundTarget() const
Definition net.cpp:2989
std::unique_ptr< CSemaphore > semOutbound
Definition net.h:1300
void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition net.cpp:2194
RecursiveMutex cs_totalBytesSent
Definition net.h:1224
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
Definition net.cpp:2507
std::thread threadOpenConnections
Definition net.h:1361
size_t GetNodeCount(ConnectionDirection) const
Definition net.cpp:2882
void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition net.cpp:1715
Mutex m_addr_fetches_mutex
Definition net.h:1251
bool InactivityCheck(const CNode &node) const
Return true if the peer is inactive and should be disconnected.
Definition net.cpp:1299
CNode * FindNode(const CNetAddr &ip)
Definition net.cpp:354
void GetNodeStats(std::vector< CNodeStats > &vstats) const
Definition net.cpp:2900
std::vector< AddedNodeInfo > GetAddedNodeInfo() const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition net.cpp:2137
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition net.h:1334
unsigned int nReceiveFloodSize
Definition net.h:1244
int GetExtraFullOutboundCount() const
Definition net.cpp:1750
uint64_t GetTotalBytesRecv() const
Definition net.cpp:3048
std::pair< size_t, bool > SocketSendData(CNode &node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend)
(Try to) send data from node's vSendMsg.
Definition net.cpp:909
RecursiveMutex m_nodes_mutex
Definition net.h:1256
static bool NodeFullyConnected(const CNode *pnode)
Definition net.cpp:3159
int nMaxConnections
Definition net.h:1302
CConnman(const Config &configIn, uint64_t seed0, uint64_t seed1, AddrMan &addrmanIn, bool network_active=true)
Definition net.cpp:2492
std::vector< CAddress > GetAddresses(size_t max_addresses, size_t max_pct, std::optional< Network > network) const
Return all or many randomly selected addresses, optionally by network.
Definition net.cpp:2793
void SetNetworkActive(bool active)
Definition net.cpp:2478
std::list< CNode * > m_nodes_disconnected
Definition net.h:1255
AddrMan & addrman
Definition net.h:1249
std::atomic_bool inflight_throttle
Definition net.h:1417
void SocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Check connected and listening sockets for IO readiness and process them accordingly.
Definition net.cpp:1400
uint64_t CalculateKeyedNetGroup(const CAddress &ad) const
Definition net.cpp:3225
Mutex mutexMsgProc
Definition net.h:1340
bool fAddressesInitialized
Definition net.h:1248
virtual ~CConnman()
Definition net.cpp:2787
void StopThreads()
Definition net.cpp:2723
bool AddNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition net.cpp:2858
std::thread threadOpenAddedConnections
Definition net.h:1360
Mutex m_added_nodes_mutex
Definition net.h:1253
const Config * config
Definition net.h:1221
void Init(const Options &connOptions) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition net.h:872
bool CheckIncomingNonce(uint64_t nonce)
Definition net.cpp:399
int m_max_outbound_full_relay
Definition net.h:1305
Mutex m_unused_i2p_sessions_mutex
Mutex protecting m_i2p_sam_sessions.
Definition net.h:1387
int nMaxAddnode
Definition net.h:1314
void RecordBytesRecv(uint64_t bytes)
Definition net.cpp:2970
bool ShouldRunInactivityChecks(const CNode &node, std::chrono::seconds now) const
Return true if we should disconnect the peer for failing an inactivity check.
Definition net.cpp:1294
void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition net.cpp:1555
void CreateNodeFromAcceptedSocket(std::unique_ptr< Sock > &&sock, NetPermissionFlags permission_flags, const CAddress &addr_bind, const CAddress &addr)
Create a CNode object from a socket that has just been accepted and add the node to the m_nodes membe...
Definition net.cpp:1066
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
Definition net.cpp:3163
void StopNodes()
Definition net.cpp:2744
unsigned int nSendBufferMaxSize
Definition net.h:1243
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
Definition net.h:1356
bool m_use_addrman_outgoing
Definition net.h:1317
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition net.h:1241
std::map< uint64_t, CachedAddrResponse > m_addr_response_caches
Addr responses stored in different caches per (network, local socket) prevent cross-network node iden...
Definition net.h:1285
std::atomic< uint64_t > nTotalBytesRecv
Definition net.h:1225
std::atomic< bool > fNetworkActive
Definition net.h:1247
std::atomic_bool m_start_extra_block_relay_peers
flag for initiating extra block-relay-only peer connections.
Definition net.h:1376
void DisconnectNodes()
Definition net.cpp:1230
void SocketHandlerListening(const Sock::EventsPerSock &events_per_sock)
Accept incoming connections, one from each read-ready listening socket.
Definition net.cpp:1542
void DumpAddresses()
Definition net.cpp:1706
std::vector< CService > m_onion_binds
A vector of -bind=<address>:<port>=onion arguments each of which is an address and port that are desi...
Definition net.h:1382
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Definition net.cpp:426
std::vector< NetEventsInterface * > m_msgproc
Definition net.h:1320
std::thread threadSocketHandler
Definition net.h:1359
uint64_t GetTotalBytesSent() const
Definition net.cpp:3052
void ThreadOpenConnections(std::vector< std::string > connect, std::function< void(const CAddress &, ConnectionType)> mockOpenConnection) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition net.cpp:1780
void AcceptConnection(const ListenSocket &hListenSocket)
Definition net.cpp:1037
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
Definition net.cpp:2366
int m_max_avalanche_outbound
Definition net.h:1312
CHash256 & Write(Span< const uint8_t > input)
Definition hash.h:36
void Finalize(Span< uint8_t > output)
Definition hash.h:29
Message header.
Definition protocol.h:34
static constexpr size_t MESSAGE_TYPE_SIZE
Definition protocol.h:37
bool IsMessageTypeValid() const
Definition protocol.cpp:125
static constexpr size_t CHECKSUM_SIZE
Definition protocol.h:39
MessageMagic pchMessageStart
Definition protocol.h:69
std::string GetMessageType() const
Definition protocol.cpp:119
bool IsOversized(const Config &config) const
Definition protocol.cpp:144
static constexpr size_t HEADER_SIZE
Definition protocol.h:44
uint8_t pchChecksum[CHECKSUM_SIZE]
Definition protocol.h:72
static constexpr size_t MESSAGE_START_SIZE
Definition protocol.h:36
uint32_t nMessageSize
Definition protocol.h:71
Network address.
Definition netaddress.h:114
Network GetNetClass() const
std::string ToStringAddr() const
bool IsRoutable() const
bool IsValid() const
bool IsIPv4() const
bool IsIPv6() const
std::vector< uint8_t > GetGroup(const std::vector< bool > &asmap) const
Get the canonical identifier of our network group.
std::vector< uint8_t > GetAddrBytes() const
bool SetInternal(const std::string &name)
Create an "internal" address that represents a name or FQDN.
enum Network GetNetwork() const
~CNetCleanup()
Definition net.cpp:2691
CNetCleanup()=default
Transport protocol agnostic message container.
Definition net.h:262
Information about a peer.
Definition net.h:395
const CAddress addrBind
Definition net.h:437
const std::chrono::seconds m_connected
Unix epoch time at peer connection.
Definition net.h:432
std::atomic< int > nVersion
Definition net.h:442
std::atomic< double > availabilityScore
The last computed score.
Definition net.h:766
bool IsInboundConn() const
Definition net.h:527
std::atomic_bool fPauseRecv
Definition net.h:466
void pauseRecv(bool pause)
Definition net.cpp:698
NodeId GetId() const
Definition net.h:687
std::atomic< int64_t > nTimeOffset
Definition net.h:433
const std::string m_addr_name
Definition net.h:438
std::string ConnectionTypeAsString() const
Definition net.h:733
std::atomic< bool > m_bip152_highbandwidth_to
Definition net.h:565
std::list< CNetMessage > vRecvMsg
Definition net.h:747
std::atomic< bool > m_bip152_highbandwidth_from
Definition net.h:567
std::atomic_bool fSuccessfullyConnected
Definition net.h:458
CNode(NodeId id, std::shared_ptr< Sock > sock, const CAddress &addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, uint64_t nLocalExtraEntropyIn, const CAddress &addrBindIn, const std::string &addrNameIn, ConnectionType conn_type_in, bool inbound_onion, CNodeOptions &&node_opts={})
Definition net.cpp:3090
const CAddress addr
Definition net.h:435
void SetAddrLocal(const CService &addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
May not be called more than once.
Definition net.cpp:631
CSemaphoreGrant grantOutbound
Definition net.h:462
std::atomic< std::chrono::seconds > m_last_msg_start
Definition net.h:429
void MarkReceivedMsgsForProcessing() EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex)
Move all messages from the received queue to the processing queue.
Definition net.cpp:3126
Mutex m_subver_mutex
cleanSubVer is a sanitized string of the user agent byte array we read from the wire.
Definition net.h:451
const std::unique_ptr< const TransportSerializer > m_serializer
Definition net.h:399
Mutex cs_vSend
Definition net.h:420
CNode * AddRef()
Definition net.h:720
std::atomic_bool fPauseSend
Definition net.h:467
std::optional< std::pair< CNetMessage, bool > > PollMessage() EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex)
Poll the next message from the processing queue of this connection.
Definition net.cpp:3143
double getAvailabilityScore() const
Definition net.cpp:3084
Mutex m_msg_process_queue_mutex
Definition net.h:749
const ConnectionType m_conn_type
Definition net.h:469
Network ConnectedThroughNetwork() const
Get network the peer connected through.
Definition net.cpp:644
const size_t m_recv_flood_size
Definition net.h:745
void copyStats(CNodeStats &stats) EXCLUSIVE_LOCKS_REQUIRED(!m_subver_mutex
Definition net.cpp:648
std::atomic< std::chrono::microseconds > m_last_ping_time
Last measured round-trip time.
Definition net.h:661
void updateAvailabilityScore(double decayFactor)
The availability score is calculated using an exponentially weighted average.
Definition net.cpp:3069
const NetPermissionFlags m_permission_flags
Definition net.h:401
bool ReceiveMsgBytes(const Config &config, Span< const uint8_t > msg_bytes, bool &complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv)
Receive bytes from the buffer and deserialize them into messages.
Definition net.cpp:710
void invsPolled(uint32_t count)
The node was polled for count invs.
Definition net.cpp:3061
Mutex m_addr_local_mutex
Definition net.h:755
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e.
Definition net.h:441
std::atomic< std::chrono::microseconds > m_min_ping_time
Lowest measured round-trip time.
Definition net.h:667
void AccountForSentBytes(const std::string &msg_type, size_t sent_bytes) EXCLUSIVE_LOCKS_REQUIRED(cs_vSend)
Account for the total size of a sent message in the per msg type connection stats.
Definition net.h:489
std::atomic< std::chrono::seconds > m_last_proof_time
UNIX epoch time of the last proof received from this peer that we had not yet seen (e....
Definition net.h:658
Mutex cs_vRecv
Definition net.h:422
std::atomic< bool > m_avalanche_enabled
Definition net.h:588
std::atomic< std::chrono::seconds > m_last_block_time
UNIX epoch time of the last block received from this peer that we had not yet seen (e....
Definition net.h:642
const std::unique_ptr< TransportDeserializer > m_deserializer
Definition net.h:398
std::atomic< uint64_t > invCounters
The inventories polled and voted counters since last score computation, stored as a pair of uint32_t ...
Definition net.h:763
Mutex m_sock_mutex
Definition net.h:421
std::atomic_bool fDisconnect
Definition net.h:461
std::atomic< std::chrono::seconds > m_last_recv
Definition net.h:428
std::atomic< std::chrono::seconds > m_last_tx_time
UNIX epoch time of the last transaction received from this peer that we had not yet seen (e....
Definition net.h:650
CService GetAddrLocal() const EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
Definition net.cpp:625
void invsVoted(uint32_t count)
The node voted for count invs.
Definition net.cpp:3065
void CloseSocketDisconnect() EXCLUSIVE_LOCKS_REQUIRED(!m_sock_mutex)
Definition net.cpp:594
std::atomic< std::chrono::seconds > m_last_send
Definition net.h:427
std::atomic< uint64_t > nInflightBytes
Definition net.h:425
Simple class for background tasks that should be run periodically or once "after a while".
Definition scheduler.h:42
void scheduleEvery(Predicate p, std::chrono::milliseconds delta) EXCLUSIVE_LOCKS_REQUIRED(!newTaskMutex)
Repeat p until it return false.
RAII-style semaphore lock.
Definition sync.h:383
bool TryAcquire()
Definition sync.h:405
void MoveTo(CSemaphoreGrant &grant)
Definition sync.h:412
A combination of a network address (CNetAddr) and a (TCP) port.
Definition netaddress.h:573
bool SetSockAddr(const struct sockaddr *paddr, socklen_t addrlen)
Set CService from a network sockaddr.
uint16_t GetPort() const
sa_family_t GetSAFamily() const
Get the address family.
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Obtain the IPv4/6 socket address this represents.
std::string ToStringAddrPort() const
SipHash-2-4.
Definition siphash.h:14
uint64_t Finalize() const
Compute the 64-bit SipHash-2-4 of the data written so far.
Definition siphash.cpp:83
CSipHasher & Write(uint64_t data)
Hash a 64-bit integer worth of data.
Definition siphash.cpp:36
std::string ToString() const
bool Match(const CNetAddr &addr) const
std::chrono::steady_clock Clock
bool sleep_for(Clock::duration rel_time) EXCLUSIVE_LOCKS_REQUIRED(!mut)
virtual uint64_t GetMaxBlockSize() const =0
virtual const CChainParams & GetChainParams() const =0
size_type size() const
Definition streams.h:151
void resize(size_type n, value_type c=value_type{})
Definition streams.h:153
Fast randomness source.
Definition random.h:411
Different type to mark Mutex at global scope.
Definition sync.h:144
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition net.h:792
NetPermissionFlags m_flags
static void AddFlag(NetPermissionFlags &flags, NetPermissionFlags f)
static void ClearFlag(NetPermissionFlags &flags, NetPermissionFlags f)
ClearFlag is only called with f == NetPermissionFlags::Implicit.
static bool HasFlag(NetPermissionFlags flags, NetPermissionFlags f)
static bool TryParse(const std::string &str, NetWhitebindPermissions &output, bilingual_str &error)
std::string ToString() const
Definition netbase.h:96
Tp rand_uniform_delay(const Tp &time, typename Tp::duration range) noexcept
Return the time point advanced by a uniform random duration.
Definition random.h:339
Chrono::duration rand_uniform_duration(typename Chrono::duration range) noexcept
Generate a uniform random duration in the range from 0 (inclusive) to range (exclusive).
Definition random.h:351
I randrange(I range) noexcept
Generate a random integer in the range [0..range), with range > 0.
Definition random.h:266
std::chrono::microseconds rand_exp_duration(std::chrono::microseconds mean) noexcept
Return a duration sampled from an exponential distribution (https://en.wikipedia.org/wiki/Exponential...
Definition random.h:389
uint64_t randbits(int bits) noexcept
Generate a random (bits)-bit integer.
Definition random.h:216
RAII helper class that manages a socket and closes it automatically when it goes out of scope.
Definition sock.h:27
static constexpr Event SEND
If passed to Wait(), then it will wait for readiness to send to the socket.
Definition sock.h:165
uint8_t Event
Definition sock.h:153
virtual int GetSockName(sockaddr *name, socklen_t *name_len) const
getsockname(2) wrapper.
Definition sock.cpp:106
static constexpr Event ERR
Ignored if passed to Wait(), but could be set in the occurred events if an exceptional condition has ...
Definition sock.h:172
static constexpr Event RECV
If passed to Wait(), then it will wait for readiness to read from the socket.
Definition sock.h:159
std::unordered_map< std::shared_ptr< const Sock >, Events, HashSharedPtrSock, EqualSharedPtrSock > EventsPerSock
On which socket to wait for what events in WaitMany().
Definition sock.h:229
A Span is an object that can refer to a contiguous sequence of objects.
Definition span.h:94
constexpr std::size_t size() const noexcept
Definition span.h:210
CONSTEXPR_IF_NOT_DEBUG Span< C > first(std::size_t count) const noexcept
Definition span.h:228
constexpr C * data() const noexcept
Definition span.h:199
CMessageHeader hdr
Definition net.h:317
CNetMessage GetMessage(std::chrono::microseconds time, bool &reject_message) override
Definition net.cpp:849
const uint256 & GetMessageHash() const
Definition net.cpp:840
const NodeId m_node_id
Definition net.h:308
const Config & m_config
Definition net.h:306
uint32_t nDataPos
Definition net.h:321
int readData(Span< const uint8_t > msg_bytes)
Definition net.cpp:823
bool Complete() const override
Definition net.h:344
int readHeader(const Config &config, Span< const uint8_t > msg_bytes)
Definition net.cpp:775
DataStream hdrbuf
Definition net.h:315
DataStream vRecv
Definition net.h:319
void prepareForTransport(const Config &config, CSerializedNetMsg &msg, std::vector< uint8_t > &header) const override
Definition net.cpp:893
Minimal stream for overwriting and/or appending to an existing byte vector.
Definition streams.h:31
constexpr bool IsNull() const
Definition uint256.h:44
constexpr uint8_t * begin()
Definition uint256.h:122
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition fs.h:30
256-bit opaque blob.
Definition uint256.h:199
std::string FormatVersion(int nVersion)
std::string FormatUserAgent(const std::string &name, const std::string &version, const std::vector< std::string > &comments)
Format the subversion field according to BIP 14 spec.
static constexpr int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
const std::string CLIENT_NAME
#define WSAEWOULDBLOCK
Definition compat.h:59
#define SOCKET_ERROR
Definition compat.h:66
#define WSAGetLastError()
Definition compat.h:57
#define WSAEMSGSIZE
Definition compat.h:61
#define MSG_NOSIGNAL
Definition compat.h:122
#define MSG_DONTWAIT
Definition compat.h:128
void * sockopt_arg_type
Definition compat.h:104
#define WSAEINPROGRESS
Definition compat.h:63
#define WSAEADDRINUSE
Definition compat.h:64
#define WSAEINTR
Definition compat.h:62
const Config & GetConfig()
Definition config.cpp:40
ConnectionType
Different types of connections to a peer.
@ BLOCK_RELAY
We use block-relay-only connections to help prevent against partition attacks.
@ MANUAL
We open manual connections to addresses that users explicitly inputted via the addnode RPC,...
@ OUTBOUND_FULL_RELAY
These are the default connections that we use to connect with the network.
@ FEELER
Feeler connections are short-lived connections made to check that a node is alive.
@ INBOUND
Inbound connections are those initiated by a peer.
@ AVALANCHE_OUTBOUND
Special case of connection to a full relay outbound with avalanche service enabled.
@ ADDR_FETCH
AddrFetch connections are short lived connections used to solicit addresses from peers.
static const uint64_t ONE_MEGABYTE
1MB
Definition consensus.h:12
static uint32_t ReadLE32(const uint8_t *ptr)
Definition common.h:19
std::vector< std::string > GetRandomizedDNSSeeds(const CChainParams &params)
Return the list of hostnames to look up for DNS seeds.
Definition dnsseeds.cpp:10
std::optional< NodeId > SelectNodeToEvict(std::vector< NodeEvictionCandidate > &&vEvictionCandidates)
Select an inbound peer to evict after filtering out (protecting) peers having distinct,...
Definition eviction.cpp:261
int64_t NodeId
Definition eviction.h:16
uint256 Hash(const T &in1)
Compute the 256-bit hash of an object.
Definition hash.h:74
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition hex_base.cpp:30
bool fLogIPs
Definition logging.cpp:24
#define LogPrintLevel(category, level,...)
Definition logging.h:437
#define LogError(...)
Definition logging.h:419
#define LogDebug(category,...)
Definition logging.h:446
#define LogPrintf(...)
Definition logging.h:424
@ NETDEBUG
Definition logging.h:98
@ PROXY
Definition logging.h:84
@ NET
Definition logging.h:69
static bool create_directories(const std::filesystem::path &p)
Create directory (and if necessary its parents), unless the leaf directory already exists or is a sym...
Definition fs.h:185
FILE * fopen(const fs::path &p, const char *mode)
Definition fs.cpp:30
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition rcu.h:259
void TraceThread(std::string_view thread_name, std::function< void()> thread_func)
A wrapper for do-something-once thread functions.
Definition thread.cpp:14
bool IsPeerAddrLocalGood(CNode *pnode)
Definition net.cpp:240
uint16_t GetListenPort()
Definition net.cpp:140
static constexpr int DNSSEEDS_TO_QUERY_AT_ONCE
Number of DNS seeds to query when the number of connections is low.
Definition net.cpp:75
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition net.cpp:349
static const uint64_t RANDOMIZER_ID_NETGROUP
Definition net.cpp:118
CService GetLocalAddress(const CNetAddr &addrPeer)
Definition net.cpp:224
static const uint64_t SELECT_TIMEOUT_MILLISECONDS
Definition net.cpp:113
void RemoveLocal(const CService &addr)
Definition net.cpp:314
BindFlags
Used to pass flags to the Bind() function.
Definition net.cpp:100
@ BF_REPORT_ERROR
Definition net.cpp:103
@ BF_NONE
Definition net.cpp:101
@ BF_EXPLICIT
Definition net.cpp:102
@ BF_DONT_ADVERTISE
Do not call AddLocal() for our special addresses, e.g., for incoming Tor connections,...
Definition net.cpp:108
bool fDiscover
Definition net.cpp:128
static const uint64_t RANDOMIZER_ID_LOCALHOSTNONCE
Definition net.cpp:120
static constexpr std::chrono::minutes DUMP_PEERS_INTERVAL
Definition net.cpp:70
static CAddress GetBindAddress(const Sock &sock)
Get the bind address for a socket as CAddress.
Definition net.cpp:411
static constexpr auto FEELER_SLEEP_WINDOW
Definition net.cpp:97
static constexpr int DNSSEEDS_DELAY_PEER_THRESHOLD
Definition net.cpp:90
bool fListen
Definition net.cpp:129
static constexpr size_t MAX_BLOCK_RELAY_ONLY_ANCHORS
Maximum number of block-relay-only anchor connections.
Definition net.cpp:61
bool GetLocal(CService &addr, const CNetAddr *paddrPeer)
Definition net.cpp:175
static constexpr std::chrono::seconds DNSSEEDS_DELAY_FEW_PEERS
How long to delay before querying DNS seeds.
Definition net.cpp:87
static const uint64_t RANDOMIZER_ID_ADDRCACHE
Definition net.cpp:124
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
Definition net.cpp:246
const std::string NET_MESSAGE_TYPE_OTHER
Definition net.cpp:115
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition net.cpp:320
std::function< void(const CAddress &addr, const std::string &msg_type, Span< const uint8_t > data, bool is_incoming)> CaptureMessage
Defaults to CaptureMessageToFile(), but can be overridden by unit tests.
Definition net.cpp:3313
const char *const ANCHORS_DATABASE_FILENAME
Anchor IP address database file name.
Definition net.cpp:67
std::string getSubVersionEB(uint64_t MaxBlockSize)
This function convert MaxBlockSize from byte to MB with a decimal precision one digit rounded down E....
Definition net.cpp:3247
GlobalMutex g_maplocalhost_mutex
Definition net.cpp:130
bool AddLocal(const CService &addr, int nScore)
Definition net.cpp:281
void CaptureMessageToFile(const CAddress &addr, const std::string &msg_type, Span< const uint8_t > data, bool is_incoming)
Dump binary message to file, with timestamp.
Definition net.cpp:3281
static constexpr std::chrono::minutes DNSSEEDS_DELAY_MANY_PEERS
Definition net.cpp:88
static int GetnScore(const CService &addr)
Definition net.cpp:233
static const uint64_t RANDOMIZER_ID_EXTRAENTROPY
Definition net.cpp:122
static std::vector< CAddress > convertSeed6(const std::vector< SeedSpec6 > &vSeedsIn)
Convert the pnSeed6 array into usable address objects.
Definition net.cpp:200
static CNetCleanup instance_of_cnetcleanup
Definition net.cpp:2698
std::string userAgent(const Config &config)
Definition net.cpp:3261
static constexpr std::chrono::seconds MAX_UPLOAD_TIMEFRAME
The default timeframe for -maxuploadtarget.
Definition net.cpp:93
void Discover()
Look up IP addresses from all interfaces on the machine and add them to the list of local addresses t...
Definition net.cpp:2466
bool IsReachable(enum Network net)
Definition net.cpp:328
bool SeenLocal(const CService &addr)
vote for a local address
Definition net.cpp:338
uint16_t GetListenPort()
Definition net.cpp:140
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition net.cpp:349
void RemoveLocal(const CService &addr)
Definition net.cpp:314
static constexpr std::chrono::minutes TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition net.h:65
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
Definition net.cpp:281
bool fDiscover
Definition net.cpp:128
static const size_t DEFAULT_MAXINFLIGHTBUFFER
Definition net.h:110
static const bool DEFAULT_FORCEDNSSEED
Definition net.h:105
bool fListen
Definition net.cpp:129
static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL
Run the extra block-relay-only connection loop once every 5 minutes.
Definition net.h:69
const std::string NET_MESSAGE_TYPE_OTHER
Definition net.cpp:115
static const bool DEFAULT_FIXEDSEEDS
Definition net.h:107
std::function< void(const CAddress &addr, const std::string &msg_type, Span< const uint8_t > data, bool is_incoming)> CaptureMessage
Defaults to CaptureMessageToFile(), but can be overridden by unit tests.
Definition net.cpp:3313
static constexpr auto FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes.
Definition net.h:67
static const bool DEFAULT_DNSSEED
Definition net.h:106
@ LOCAL_MANUAL
Definition net.h:169
@ LOCAL_BIND
Definition net.h:165
@ LOCAL_IF
Definition net.h:163
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition net.h:80
bool IsReachable(enum Network net)
Definition net.cpp:328
NetPermissionFlags
Network
A network type.
Definition netaddress.h:37
@ NET_I2P
I2P.
Definition netaddress.h:52
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
Definition netaddress.h:62
@ NET_ONION
TOR (v2 or v3)
Definition netaddress.h:49
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
Definition netaddress.h:40
@ NET_INTERNAL
A set of addresses that represent the hash of a string or FQDN.
Definition netaddress.h:59
std::unique_ptr< Sock > ConnectDirectly(const CService &dest, bool manual_connection)
Create a socket and try to connect to the specified service.
Definition netbase.cpp:745
std::vector< CNetAddr > LookupHost(const std::string &name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
Resolve a host string to its corresponding network addresses.
Definition netbase.cpp:211
bool HaveNameProxy()
Definition netbase.cpp:850
void InterruptSocks5(bool interrupt)
Definition netbase.cpp:928
std::vector< CService > Lookup(const std::string &name, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
Resolve a service string to its corresponding service.
Definition netbase.cpp:237
bool fNameLookup
Definition netbase.cpp:48
bool GetProxy(enum Network net, Proxy &proxyInfoOut)
Definition netbase.cpp:822
std::unique_ptr< Sock > ConnectThroughProxy(const Proxy &proxy, const std::string &dest, uint16_t port, bool &proxy_connection_failed)
Connect to a specified destination service through a SOCKS5 proxy by first connecting to the SOCKS5 p...
Definition netbase.cpp:865
std::function< std::unique_ptr< Sock >(int, int, int)> CreateSock
Socket factory.
Definition netbase.cpp:673
bool GetNameProxy(Proxy &nameProxyOut)
Definition netbase.cpp:841
CService LookupNumeric(const std::string &name, uint16_t portDefault, DNSLookupFn dns_lookup_function)
Resolve a service string with a numeric IP to its first corresponding service.
Definition netbase.cpp:270
bool IsBadPort(uint16_t port)
Determine if a port is "bad" from the perspective of attempting to connect to a node on that port.
Definition netbase.cpp:932
ConnectionDirection
Definition netbase.h:37
std::vector< CNetAddr > GetLocalAddresses()
Return all local non-loopback IPv4 and IPv6 network addresses.
Definition netif.cpp:386
const std::vector< std::string > & getAllNetMessageTypes()
Get a vector of all valid message types (see above)
Definition protocol.cpp:199
ServiceFlags GetDesirableServiceFlags(ServiceFlags services)
Gets the set of service flags which are "desirable" for a given peer.
Definition protocol.cpp:156
static bool HasAllDesirableServiceFlags(ServiceFlags services)
A shortcut for (services & GetDesirableServiceFlags(services)) == GetDesirableServiceFlags(services),...
Definition protocol.h:426
ServiceFlags
nServices flags.
Definition protocol.h:335
@ NODE_NONE
Definition protocol.h:338
@ NODE_AVALANCHE
Definition protocol.h:379
static bool MayHaveUsefulAddressDB(ServiceFlags services)
Checks if a peer with the given service flags may be capable of having a robust address-storage DB.
Definition protocol.h:434
void RandAddEvent(const uint32_t event_info) noexcept
Gathers entropy from the low bits of the time at which events occur.
Definition random.cpp:704
static uint16_t GetDefaultPort()
Definition bitcoin.h:18
void ser_writedata32(Stream &s, uint32_t obj)
Definition serialize.h:72
void ser_writedata64(Stream &s, uint64_t obj)
Definition serialize.h:82
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
Definition sock.cpp:440
Cache responses to addr requests to minimize privacy leak.
Definition net.h:1266
std::chrono::microseconds m_cache_entry_expiration
Definition net.h:1268
std::vector< CAddress > m_addrs_response_cache
Definition net.h:1267
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition net.h:1088
std::shared_ptr< Sock > sock
Definition net.h:1087
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition net.h:858
std::vector< CService > onion_binds
Definition net.h:860
std::vector< std::string > m_specified_outgoing
Definition net.h:865
std::vector< CService > vBinds
Definition net.h:859
bool m_i2p_accept_incoming
Definition net.h:867
std::vector< std::string > vSeedNodes
Definition net.h:855
bool m_use_addrman_outgoing
Definition net.h:864
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
Definition net.h:863
NetPermissionFlags permission_flags
Definition net.h:389
std::unique_ptr< i2p::sam::Session > i2p_sam_session
Definition net.h:388
POD that contains various stats about a node.
Definition net.h:217
std::string addrLocal
Definition net.h:245
CAddress addrBind
Definition net.h:249
uint64_t nRecvBytes
Definition net.h:238
std::chrono::microseconds m_last_ping_time
Definition net.h:242
uint32_t m_mapped_as
Definition net.h:252
mapMsgTypeSize mapRecvBytesPerMsgType
Definition net.h:239
bool fInbound
Definition net.h:230
uint64_t nSendBytes
Definition net.h:236
std::chrono::seconds m_last_recv
Definition net.h:220
std::optional< double > m_availabilityScore
Definition net.h:254
uint64_t nInflightBytes
Definition net.h:240
std::chrono::seconds m_last_proof_time
Definition net.h:223
ConnectionType m_conn_type
Definition net.h:253
std::chrono::seconds m_last_send
Definition net.h:219
std::chrono::seconds m_last_tx_time
Definition net.h:222
CAddress addr
Definition net.h:247
mapMsgTypeSize mapSendBytesPerMsgType
Definition net.h:237
std::chrono::microseconds m_min_ping_time
Definition net.h:243
int64_t nTimeOffset
Definition net.h:226
std::chrono::seconds m_connected
Definition net.h:225
bool m_bip152_highbandwidth_from
Definition net.h:234
bool m_bip152_highbandwidth_to
Definition net.h:232
std::string m_addr_name
Definition net.h:227
int nVersion
Definition net.h:228
std::chrono::seconds m_last_block_time
Definition net.h:224
Network m_network
Definition net.h:251
NodeId nodeid
Definition net.h:218
std::string cleanSubVer
Definition net.h:229
std::chrono::seconds m_last_msg_start
Definition net.h:221
NetPermissionFlags m_permission_flags
Definition net.h:241
uint16_t nPort
Definition net.h:201
static time_point now() noexcept
Return current system time or mocked time, if set.
Definition time.cpp:29
Auxiliary requested/occurred events to wait for in WaitMany().
Definition sock.h:194
Bilingual messages:
Definition translation.h:17
std::string original
Definition translation.h:18
An established connection with another peer.
Definition i2p.h:33
std::unique_ptr< Sock > sock
Connected socket.
Definition i2p.h:35
CService me
Our I2P address.
Definition i2p.h:38
#define WAIT_LOCK(cs, name)
Definition sync.h:304
#define AssertLockNotHeld(cs)
Definition sync.h:163
#define LOCK(cs)
Definition sync.h:295
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition sync.h:343
static int count
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#define GUARDED_BY(x)
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition time.cpp:76
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
Definition time.cpp:80
constexpr int64_t count_seconds(std::chrono::seconds t)
Definition time.h:85
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
Definition time.h:27
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
#define TRACE6(context, event, a, b, c, d, e, f)
Definition trace.h:45
bilingual_str _(const char *psz)
Translation function.
Definition translation.h:68
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition translation.h:36
bool SplitHostPort(std::string_view in, uint16_t &portOut, std::string &hostOut)
Splits socket address string into host string and port value.
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.
assert(!tx.IsCoinBase())