Bitcoin ABC 0.33.6
P2P Digital Currency
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 LogPrint(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 LogPrint(BCLog::NET, "disconnecting peer=%d\n", id);
599 m_sock.reset();
600 }
601 m_i2p_sam_session.reset();
602}
603
605 NetPermissionFlags &flags, const CNetAddr &addr,
606 const std::vector<NetWhitelistPermissions> &ranges) const {
607 for (const auto &subnet : ranges) {
608 if (subnet.m_subnet.Match(addr)) {
609 NetPermissions::AddFlag(flags, subnet.m_flags);
610 }
611 }
616 }
617 if (whitelist_relay) {
619 }
622 }
623}
624
628 return addrLocal;
629}
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
646}
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 LogPrint(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 LogPrint(
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 LogPrint(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 LogPrint(
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 AddWhitelistPermissionFlags(permission_flags, addr,
1075
1076 {
1078 for (const CNode *pnode : m_nodes) {
1079 if (pnode->IsInboundConn()) {
1080 nInbound++;
1081 }
1082 }
1083 }
1084
1085 if (!fNetworkActive) {
1087 "connection from %s dropped: not accepting new connections\n",
1088 addr.ToStringAddrPort());
1089 return;
1090 }
1091
1092 if (!sock->IsSelectable()) {
1093 LogPrintf("connection from %s dropped: non-selectable socket\n",
1094 addr.ToStringAddrPort());
1095 return;
1096 }
1097
1098 // According to the internet TCP_NODELAY is not carried into accepted
1099 // sockets on all platforms. Set it again here just to be sure.
1100 const int on{1};
1101 if (sock->SetSockOpt(IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) ==
1102 SOCKET_ERROR) {
1104 "connection from %s: unable to set TCP_NODELAY, continuing "
1105 "anyway\n",
1106 addr.ToStringAddrPort());
1107 }
1108
1109 // Don't accept connections from banned peers.
1110 bool banned = m_banman && m_banman->IsBanned(addr);
1111 if (!NetPermissions::HasFlag(permission_flags, NetPermissionFlags::NoBan) &&
1112 banned) {
1113 LogPrint(BCLog::NET, "connection from %s dropped (banned)\n",
1114 addr.ToStringAddrPort());
1115 return;
1116 }
1117
1118 // Only accept connections from discouraged peers if our inbound slots
1119 // aren't (almost) full.
1120 bool discouraged = m_banman && m_banman->IsDiscouraged(addr);
1121 if (!NetPermissions::HasFlag(permission_flags, NetPermissionFlags::NoBan) &&
1122 nInbound + 1 >= nMaxInbound && discouraged) {
1123 LogPrint(BCLog::NET, "connection from %s dropped (discouraged)\n",
1124 addr.ToStringAddrPort());
1125 return;
1126 }
1127
1128 if (nInbound >= nMaxInbound) {
1129 if (!AttemptToEvictConnection()) {
1130 // No connection to evict, disconnect the new connection
1131 LogPrint(BCLog::NET, "failed to find an eviction candidate - "
1132 "connection dropped (full)\n");
1133 return;
1134 }
1135 }
1136
1137 NodeId id = GetNewNodeId();
1139 .Write(id)
1140 .Finalize();
1141 uint64_t extra_entropy =
1143 .Write(id)
1144 .Finalize();
1145
1146 const bool inbound_onion =
1147 std::find(m_onion_binds.begin(), m_onion_binds.end(), addr_bind) !=
1148 m_onion_binds.end();
1149 CNode *pnode = new CNode(
1150 id, std::move(sock), addr, CalculateKeyedNetGroup(addr), nonce,
1151 extra_entropy, addr_bind, "", ConnectionType::INBOUND, inbound_onion,
1153 .permission_flags = permission_flags,
1154 .prefer_evict = discouraged,
1155 .recv_flood_size = nReceiveFloodSize,
1156 });
1157 pnode->AddRef();
1158 for (auto interface : m_msgproc) {
1159 interface->InitializeNode(*config, *pnode, GetLocalServices());
1160 }
1161
1162 LogPrint(BCLog::NET, "connection from %s accepted\n",
1163 addr.ToStringAddrPort());
1164
1165 {
1167 m_nodes.push_back(pnode);
1168 }
1169
1170 // We received a new connection, harvest entropy from the time (and our peer
1171 // count)
1172 RandAddEvent(uint32_t(id));
1173}
1174
1175bool CConnman::AddConnection(const std::string &address,
1176 ConnectionType conn_type) {
1178 std::optional<int> max_connections;
1179 switch (conn_type) {
1182 return false;
1184 max_connections = m_max_outbound_full_relay;
1185 break;
1187 max_connections = m_max_outbound_block_relay;
1188 break;
1189 // no limit for ADDR_FETCH because -seednode has no limit either
1191 break;
1192 // no limit for FEELER connections since they're short-lived
1194 break;
1196 max_connections = m_max_avalanche_outbound;
1197 break;
1198 } // no default case, so the compiler can warn about missing cases
1199
1200 // Count existing connections
1201 int existing_connections =
1203 return std::count_if(
1204 m_nodes.begin(), m_nodes.end(), [conn_type](CNode *node) {
1205 return node->m_conn_type == conn_type;
1206 }););
1207
1208 // Max connections of specified type already exist
1209 if (max_connections != std::nullopt &&
1210 existing_connections >= max_connections) {
1211 return false;
1212 }
1213
1214 // Max total outbound connections already exist
1215 CSemaphoreGrant grant(*semOutbound, true);
1216 if (!grant) {
1217 return false;
1218 }
1219
1220 OpenNetworkConnection(CAddress(), false, &grant, address.c_str(),
1221 conn_type);
1222 return true;
1223}
1224
1226 {
1228
1229 if (!fNetworkActive) {
1230 // Disconnect any connected nodes
1231 for (CNode *pnode : m_nodes) {
1232 if (!pnode->fDisconnect) {
1234 "Network not active, dropping peer=%d\n",
1235 pnode->GetId());
1236 pnode->fDisconnect = true;
1237 }
1238 }
1239 }
1240
1241 // Disconnect unused nodes
1242 std::vector<CNode *> nodes_copy = m_nodes;
1243 for (CNode *pnode : nodes_copy) {
1244 if (pnode->fDisconnect) {
1245 // remove from m_nodes
1246 m_nodes.erase(remove(m_nodes.begin(), m_nodes.end(), pnode),
1247 m_nodes.end());
1248
1249 // release outbound grant (if any)
1250 pnode->grantOutbound.Release();
1251
1252 // close socket and cleanup
1253 pnode->CloseSocketDisconnect();
1254
1255 // hold in disconnected pool until all refs are released
1256 pnode->Release();
1257 m_nodes_disconnected.push_back(pnode);
1258 }
1259 }
1260 }
1261 {
1262 // Delete disconnected nodes
1263 std::list<CNode *> nodes_disconnected_copy = m_nodes_disconnected;
1264 for (CNode *pnode : nodes_disconnected_copy) {
1265 // Destroy the object only after other threads have stopped using
1266 // it.
1267 if (pnode->GetRefCount() <= 0) {
1268 m_nodes_disconnected.remove(pnode);
1269 DeleteNode(pnode);
1270 }
1271 }
1272 }
1273}
1274
1276 size_t nodes_size;
1277 {
1279 nodes_size = m_nodes.size();
1280 }
1281 if (nodes_size != nPrevNodeCount) {
1282 nPrevNodeCount = nodes_size;
1283 if (m_client_interface) {
1284 m_client_interface->NotifyNumConnectionsChanged(nodes_size);
1285 }
1286 }
1287}
1288
1290 std::chrono::seconds now) const {
1291 return node.m_connected + m_peer_connect_timeout < now;
1292}
1293
1295 // Tests that see disconnects after using mocktime can start nodes with a
1296 // large timeout. For example, -peertimeout=999999999.
1297 const auto now{GetTime<std::chrono::seconds>()};
1298 const auto last_send{node.m_last_send.load()};
1299 const auto last_recv{node.m_last_recv.load()};
1300 const auto last_msg_start{node.m_last_msg_start.load()};
1301
1302 if (!ShouldRunInactivityChecks(node, now)) {
1303 return false;
1304 }
1305
1306 if (last_recv.count() == 0 || last_send.count() == 0) {
1308 "socket no message in first %i seconds, %d %d peer=%d\n",
1309 count_seconds(m_peer_connect_timeout), last_recv.count() != 0,
1310 last_send.count() != 0, node.GetId());
1311 return true;
1312 }
1313
1314 if (now > last_send + TIMEOUT_INTERVAL) {
1315 LogPrint(BCLog::NET, "socket sending timeout: %is peer=%d\n",
1316 count_seconds(now - last_send), node.GetId());
1317 return true;
1318 }
1319
1320 if (now > last_recv + TIMEOUT_INTERVAL) {
1321 LogPrint(BCLog::NET, "socket receive timeout: %is peer=%d\n",
1322 count_seconds(now - last_recv), node.GetId());
1323 return true;
1324 }
1325
1326 uint64_t inflight_bytes = node.nInflightBytes.load();
1327 if (inflight_bytes > 0 && !node.fPauseRecv) {
1328 // First check if the peer started sending us a message, but then
1329 // stalled without finishing it.
1330 if (now > last_recv + m_peer_connect_timeout) {
1332 "socket receive timeout: stalled message, last data "
1333 "received %i seconds ago, bytes=%d peer=%d\n",
1334 count_seconds(now - last_recv), inflight_bytes,
1335 node.GetId());
1336 return true;
1337 }
1338
1339 // Second check if the peer sent us a message, but is too slow to
1340 // complete it in reasonable time (~2.13Mb/s for a 32MB block under
1341 // default settings).
1342 if (now > last_msg_start + 2 * m_peer_connect_timeout) {
1344 "socket receive timeout: stalled message started %i "
1345 "seconds ago, bytes=%d peer=%d\n",
1346 count_seconds(now - last_msg_start), inflight_bytes,
1347 node.GetId());
1348 return true;
1349 }
1350 }
1351
1352 if (!node.fSuccessfullyConnected) {
1353 LogPrint(BCLog::NET, "version handshake timeout peer=%d\n",
1354 node.GetId());
1355 return true;
1356 }
1357
1358 return false;
1359}
1360
1362 Sock::EventsPerSock events_per_sock;
1363
1364 for (const ListenSocket &hListenSocket : vhListenSocket) {
1365 events_per_sock.emplace(hListenSocket.sock, Sock::Events{Sock::RECV});
1366 }
1367
1368 int inbound_candidates{0};
1369 for (CNode *pnode : nodes) {
1370 inbound_candidates += pnode->IsInboundConn();
1371
1372 // Stop receiving if the peer is paused, or if we have enough inflight
1373 // data to process already in wich case we limit to outbounds and up to
1374 // 3 inbounds.
1375 bool select_recv = !pnode->fPauseRecv &&
1376 (!inflight_throttle || !pnode->IsInboundConn() ||
1377 inbound_candidates <= 3);
1378 bool select_send =
1379 WITH_LOCK(pnode->cs_vSend, return !pnode->vSendMsg.empty());
1380 if (!select_recv && !select_send) {
1381 continue;
1382 }
1383
1384 LOCK(pnode->m_sock_mutex);
1385 if (pnode->m_sock) {
1386 Sock::Event event =
1387 (select_send ? Sock::SEND : 0) | (select_recv ? Sock::RECV : 0);
1388 events_per_sock.emplace(pnode->m_sock, Sock::Events{event});
1389 }
1390 }
1391
1392 return events_per_sock;
1393}
1394
1396 Sock::EventsPerSock events_per_sock;
1397
1398 {
1399 const NodesSnapshot snap{*this, /*shuffle=*/false};
1400
1401 const auto timeout =
1402 std::chrono::milliseconds(SELECT_TIMEOUT_MILLISECONDS);
1403
1404 // Check for the readiness of the already connected sockets and the
1405 // listening sockets in one call ("readiness" as in poll(2) or
1406 // select(2)). If none are ready, wait for a short while and return
1407 // empty sets.
1408 events_per_sock = GenerateWaitSockets(snap.Nodes());
1409 if (events_per_sock.empty() ||
1410 !events_per_sock.begin()->first->WaitMany(timeout,
1411 events_per_sock)) {
1412 interruptNet.sleep_for(timeout);
1413 }
1414
1415 // Service (send/receive) each of the already connected nodes.
1416 SocketHandlerConnected(snap.Nodes(), events_per_sock);
1417 }
1418
1419 // Accept new connections from listening sockets.
1420 SocketHandlerListening(events_per_sock);
1421}
1422
1424 const std::vector<CNode *> &nodes,
1425 const Sock::EventsPerSock &events_per_sock) {
1426 uint64_t nTotalInflightBytes{0};
1427 for (CNode *pnode : nodes) {
1428 if (interruptNet) {
1429 return;
1430 }
1431
1432 // Always account for the node inflight bytes, even if the socket is
1433 // paused.
1434 nTotalInflightBytes += pnode->nInflightBytes;
1435
1436 //
1437 // Receive
1438 //
1439 bool recvSet = false;
1440 bool sendSet = false;
1441 bool errorSet = false;
1442 {
1443 LOCK(pnode->m_sock_mutex);
1444 if (!pnode->m_sock) {
1445 continue;
1446 }
1447 const auto it = events_per_sock.find(pnode->m_sock);
1448 if (it != events_per_sock.end()) {
1449 recvSet = it->second.occurred & Sock::RECV;
1450 sendSet = it->second.occurred & Sock::SEND;
1451 errorSet = it->second.occurred & Sock::ERR;
1452 }
1453 }
1454
1455 if (sendSet) {
1456 // Send data
1457 auto [bytes_sent, data_left] =
1458 WITH_LOCK(pnode->cs_vSend, return SocketSendData(*pnode));
1459 if (bytes_sent) {
1460 RecordBytesSent(bytes_sent);
1461
1462 // If both receiving and (non-optimistic) sending were possible,
1463 // we first attempt sending. If that succeeds, but does not
1464 // fully drain the send queue, do not attempt to receive. This
1465 // avoids needlessly queueing data if the remote peer is slow at
1466 // receiving data, by means of TCP flow control. We only do this
1467 // when sending actually succeeded to make sure progress is
1468 // always made; otherwise a deadlock would be possible when both
1469 // sides have data to send, but neither is receiving.
1470 if (data_left) {
1471 recvSet = false;
1472 }
1473 }
1474 }
1475
1476 if (recvSet || errorSet) {
1477 // typical socket buffer is 8K-64K
1478 uint8_t pchBuf[0x10000];
1479 int32_t nBytes = 0;
1480 {
1481 LOCK(pnode->m_sock_mutex);
1482 if (!pnode->m_sock) {
1483 continue;
1484 }
1485 nBytes =
1486 pnode->m_sock->Recv(pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
1487 }
1488 if (nBytes > 0) {
1489 bool notify = false;
1490 if (!pnode->ReceiveMsgBytes(*config, {pchBuf, (size_t)nBytes},
1491 notify)) {
1492 pnode->CloseSocketDisconnect();
1493 }
1494 RecordBytesRecv(nBytes);
1495 if (notify) {
1496 pnode->MarkReceivedMsgsForProcessing();
1498 }
1499 } else if (nBytes == 0) {
1500 // socket closed gracefully
1501 if (!pnode->fDisconnect) {
1502 LogPrint(BCLog::NET, "socket closed for peer=%d\n",
1503 pnode->GetId());
1504 }
1505 pnode->CloseSocketDisconnect();
1506 } else if (nBytes < 0) {
1507 // error
1508 int nErr = WSAGetLastError();
1509 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE &&
1510 nErr != WSAEINTR && nErr != WSAEINPROGRESS) {
1511 if (!pnode->fDisconnect) {
1513 "socket recv error for peer=%d: %s\n",
1514 pnode->GetId(), NetworkErrorString(nErr));
1515 }
1516 pnode->CloseSocketDisconnect();
1517 }
1518 }
1519 }
1520
1521 if (InactivityCheck(*pnode)) {
1522 pnode->fDisconnect = true;
1523 }
1524 }
1525
1526 const size_t max_inflight_bytes = DEFAULT_MAXINFLIGHTBUFFER * 1000;
1527
1528 bool prev_inflight_throttle = inflight_throttle;
1529 inflight_throttle = nTotalInflightBytes > max_inflight_bytes;
1530 if (prev_inflight_throttle != inflight_throttle) {
1531 LogPrintf("Inflight throttling %s (%d/%d)\n",
1532 inflight_throttle ? "enabled" : "disabled",
1533 nTotalInflightBytes, max_inflight_bytes);
1534 }
1535}
1536
1538 const Sock::EventsPerSock &events_per_sock) {
1539 for (const ListenSocket &listen_socket : vhListenSocket) {
1540 if (interruptNet) {
1541 return;
1542 }
1543 const auto it = events_per_sock.find(listen_socket.sock);
1544 if (it != events_per_sock.end() && it->second.occurred & Sock::RECV) {
1545 AcceptConnection(listen_socket);
1546 }
1547 }
1548}
1549
1551 while (!interruptNet) {
1554 SocketHandler();
1555 }
1556}
1557
1559 {
1561 fMsgProcWake = true;
1562 }
1563 condMsgProc.notify_one();
1564}
1565
1568 std::vector<std::string> seeds =
1570 // Number of seeds left before testing if we have enough connections
1571 int seeds_right_now = 0;
1572 int found = 0;
1573
1574 if (gArgs.GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED)) {
1575 // When -forcednsseed is provided, query all.
1576 seeds_right_now = seeds.size();
1577 } else if (addrman.size() == 0) {
1578 // If we have no known peers, query all.
1579 // This will occur on the first run, or if peers.dat has been
1580 // deleted.
1581 seeds_right_now = seeds.size();
1582 }
1583
1584 // goal: only query DNS seed if address need is acute
1585 // * If we have a reasonable number of peers in addrman, spend
1586 // some time trying them first. This improves user privacy by
1587 // creating fewer identifying DNS requests, reduces trust by
1588 // giving seeds less influence on the network topology, and
1589 // reduces traffic to the seeds.
1590 // * When querying DNS seeds query a few at once, this ensures
1591 // that we don't give DNS seeds the ability to eclipse nodes
1592 // that query them.
1593 // * If we continue having problems, eventually query all the
1594 // DNS seeds, and if that fails too, also try the fixed seeds.
1595 // (done in ThreadOpenConnections)
1596 const std::chrono::seconds seeds_wait_time =
1600
1601 for (const std::string &seed : seeds) {
1602 if (seeds_right_now == 0) {
1603 seeds_right_now += DNSSEEDS_TO_QUERY_AT_ONCE;
1604
1605 if (addrman.size() > 0) {
1606 LogPrintf("Waiting %d seconds before querying DNS seeds.\n",
1607 seeds_wait_time.count());
1608 std::chrono::seconds to_wait = seeds_wait_time;
1609 while (to_wait.count() > 0) {
1610 // if sleeping for the MANY_PEERS interval, wake up
1611 // early to see if we have enough peers and can stop
1612 // this thread entirely freeing up its resources
1613 std::chrono::seconds w =
1614 std::min(DNSSEEDS_DELAY_FEW_PEERS, to_wait);
1615 if (!interruptNet.sleep_for(w)) {
1616 return;
1617 }
1618 to_wait -= w;
1619
1620 int nRelevant = 0;
1621 {
1623 for (const CNode *pnode : m_nodes) {
1624 if (pnode->fSuccessfullyConnected &&
1625 pnode->IsFullOutboundConn()) {
1626 ++nRelevant;
1627 }
1628 }
1629 }
1630 if (nRelevant >= 2) {
1631 if (found > 0) {
1632 LogPrintf("%d addresses found from DNS seeds\n",
1633 found);
1634 LogPrintf(
1635 "P2P peers available. Finished DNS seeding.\n");
1636 } else {
1637 LogPrintf(
1638 "P2P peers available. Skipped DNS seeding.\n");
1639 }
1640 return;
1641 }
1642 }
1643 }
1644 }
1645
1646 if (interruptNet) {
1647 return;
1648 }
1649
1650 // hold off on querying seeds if P2P network deactivated
1651 if (!fNetworkActive) {
1652 LogPrintf("Waiting for network to be reactivated before querying "
1653 "DNS seeds.\n");
1654 do {
1655 if (!interruptNet.sleep_for(std::chrono::seconds{1})) {
1656 return;
1657 }
1658 } while (!fNetworkActive);
1659 }
1660
1661 LogPrintf("Loading addresses from DNS seed %s\n", seed);
1662 if (HaveNameProxy()) {
1663 AddAddrFetch(seed);
1664 } else {
1665 std::vector<CAddress> vAdd;
1666 ServiceFlags requiredServiceBits =
1668 std::string host = strprintf("x%x.%s", requiredServiceBits, seed);
1669 CNetAddr resolveSource;
1670 if (!resolveSource.SetInternal(host)) {
1671 continue;
1672 }
1673
1674 // Limits number of IPs learned from a DNS seed
1675 unsigned int nMaxIPs = 256;
1676 const auto addresses{LookupHost(host, nMaxIPs, true)};
1677 if (!addresses.empty()) {
1678 for (const CNetAddr &ip : addresses) {
1679 CAddress addr = CAddress(
1681 requiredServiceBits);
1682 // Use a random age between 3 and 7 days old.
1683 addr.nTime = rng.rand_uniform_delay(
1684 Now<NodeSeconds>() - 3 * 24h, -4 * 24h);
1685 vAdd.push_back(addr);
1686 found++;
1687 }
1688 addrman.Add(vAdd, resolveSource);
1689 } else {
1690 // We now avoid directly using results from DNS Seeds which do
1691 // not support service bit filtering, instead using them as a
1692 // addrfetch to get nodes with our desired service bits.
1693 AddAddrFetch(seed);
1694 }
1695 }
1696 --seeds_right_now;
1697 }
1698 LogPrintf("%d addresses found from DNS seeds\n", found);
1699}
1700
1702 int64_t nStart = GetTimeMillis();
1703
1705
1706 LogPrint(BCLog::NET, "Flushed %d addresses to peers.dat %dms\n",
1707 addrman.size(), GetTimeMillis() - nStart);
1708}
1709
1712 std::string strDest;
1713 {
1715 if (m_addr_fetches.empty()) {
1716 return;
1717 }
1718 strDest = m_addr_fetches.front();
1719 m_addr_fetches.pop_front();
1720 }
1721 CAddress addr;
1722 CSemaphoreGrant grant(*semOutbound, true);
1723 if (grant) {
1724 OpenNetworkConnection(addr, false, &grant, strDest.c_str(),
1726 }
1727}
1728
1731}
1732
1735 LogPrint(BCLog::NET, "net: setting try another outbound peer=%s\n",
1736 flag ? "true" : "false");
1737}
1738
1739// Return the number of peers we have over our outbound connection limit.
1740// Exclude peers that are marked for disconnect, or are going to be disconnected
1741// soon (eg ADDR_FETCH and FEELER).
1742// Also exclude peers that haven't finished initial connection handshake yet (so
1743// that we don't decide we're over our desired connection limit, and then evict
1744// some peer that has finished the handshake).
1746 int full_outbound_peers = 0;
1747 {
1749 for (const CNode *pnode : m_nodes) {
1750 if (pnode->fSuccessfullyConnected && !pnode->fDisconnect &&
1751 pnode->IsFullOutboundConn()) {
1752 ++full_outbound_peers;
1753 }
1754 }
1755 }
1756 return std::max(full_outbound_peers - m_max_outbound_full_relay -
1758 0);
1759}
1760
1762 int block_relay_peers = 0;
1763 {
1765 for (const CNode *pnode : m_nodes) {
1766 if (pnode->fSuccessfullyConnected && !pnode->fDisconnect &&
1767 pnode->IsBlockOnlyConn()) {
1768 ++block_relay_peers;
1769 }
1770 }
1771 }
1772 return std::max(block_relay_peers - m_max_outbound_block_relay, 0);
1773}
1774
1776 const std::vector<std::string> connect,
1777 std::function<void(const CAddress &, ConnectionType)> mockOpenConnection) {
1780 // Connect to specific addresses
1781 if (!connect.empty()) {
1782 for (int64_t nLoop = 0;; nLoop++) {
1784 for (const std::string &strAddr : connect) {
1785 CAddress addr(CService(), NODE_NONE);
1786 OpenNetworkConnection(addr, false, nullptr, strAddr.c_str(),
1788 for (int i = 0; i < 10 && i < nLoop; i++) {
1790 std::chrono::milliseconds(500))) {
1791 return;
1792 }
1793 }
1794 }
1795 if (!interruptNet.sleep_for(std::chrono::milliseconds(500))) {
1796 return;
1797 }
1798 }
1799 }
1800
1801 // Initiate network connections
1802 auto start = GetTime<std::chrono::microseconds>();
1803
1804 // Minimum time before next feeler connection (in microseconds
1805 auto next_feeler = start + rng.rand_exp_duration(FEELER_INTERVAL);
1806 auto next_extra_block_relay =
1808 const bool dnsseed = gArgs.GetBoolArg("-dnsseed", DEFAULT_DNSSEED);
1809 bool add_fixed_seeds = gArgs.GetBoolArg("-fixedseeds", DEFAULT_FIXEDSEEDS);
1810 const bool use_seednodes{gArgs.IsArgSet("-seednode")};
1811
1812 if (!add_fixed_seeds) {
1813 LogPrintf("Fixed seeds are disabled\n");
1814 }
1815
1816 while (!interruptNet) {
1818
1819 // No need to sleep the thread if we are mocking the network connection
1820 if (!mockOpenConnection &&
1821 !interruptNet.sleep_for(std::chrono::milliseconds(500))) {
1822 return;
1823 }
1824
1826 if (interruptNet) {
1827 return;
1828 }
1829
1830 if (add_fixed_seeds && addrman.size() == 0) {
1831 // When the node starts with an empty peers.dat, there are a few
1832 // other sources of peers before we fallback on to fixed seeds:
1833 // -dnsseed, -seednode, -addnode If none of those are available, we
1834 // fallback on to fixed seeds immediately, else we allow 60 seconds
1835 // for any of those sources to populate addrman.
1836 bool add_fixed_seeds_now = false;
1837 // It is cheapest to check if enough time has passed first.
1838 if (GetTime<std::chrono::seconds>() >
1839 start + std::chrono::minutes{1}) {
1840 add_fixed_seeds_now = true;
1841 LogPrintf("Adding fixed seeds as 60 seconds have passed and "
1842 "addrman is empty\n");
1843 } else if (!dnsseed && !use_seednodes) {
1844 // Lock the mutex after performing the above cheap checks.
1846 if (m_added_nodes.empty()) {
1847 add_fixed_seeds_now = true;
1848 LogPrintf("Adding fixed seeds as -dnsseed=0 and neither "
1849 "-addnode nor -seednode are provided\n");
1850 }
1851 }
1852
1853 if (add_fixed_seeds_now) {
1854 CNetAddr local;
1855 local.SetInternal("fixedseeds");
1857 local);
1858 add_fixed_seeds = false;
1859 }
1860 }
1861
1862 //
1863 // Choose an address to connect to based on most recently seen
1864 //
1865 CAddress addrConnect;
1866
1867 // Only connect out to one peer per network group (/16 for IPv4).
1868 int nOutboundFullRelay = 0;
1869 int nOutboundBlockRelay = 0;
1870 int nOutboundAvalanche = 0;
1871 std::set<std::vector<uint8_t>> setConnected;
1872
1873 {
1875 for (const CNode *pnode : m_nodes) {
1876 if (pnode->IsAvalancheOutboundConnection()) {
1877 nOutboundAvalanche++;
1878 } else if (pnode->IsFullOutboundConn()) {
1879 nOutboundFullRelay++;
1880 } else if (pnode->IsBlockOnlyConn()) {
1881 nOutboundBlockRelay++;
1882 }
1883
1884 // Netgroups for inbound and manual peers are not excluded
1885 // because our goal here is to not use multiple of our
1886 // limited outbound slots on a single netgroup but inbound
1887 // and manual peers do not use our outbound slots. Inbound
1888 // peers also have the added issue that they could be attacker
1889 // controlled and could be used to prevent us from connecting
1890 // to particular hosts if we used them here.
1891 switch (pnode->m_conn_type) {
1894 break;
1900 setConnected.insert(
1901 pnode->addr.GetGroup(addrman.GetAsmap()));
1902 } // no default case, so the compiler can warn about missing
1903 // cases
1904 }
1905 }
1906
1908 auto now = GetTime<std::chrono::microseconds>();
1909 bool anchor = false;
1910 bool fFeeler = false;
1911
1912 // Determine what type of connection to open. Opening
1913 // BLOCK_RELAY connections to addresses from anchors.dat gets the
1914 // highest priority. Then we open AVALANCHE_OUTBOUND connection until we
1915 // hit our avalanche outbound peer limit, which is 0 if avalanche is not
1916 // enabled. We fallback after 50 retries to OUTBOUND_FULL_RELAY if the
1917 // peer is not avalanche capable until we meet our full-relay capacity.
1918 // Then we open BLOCK_RELAY connection until we hit our block-relay-only
1919 // peer limit.
1920 // GetTryNewOutboundPeer() gets set when a stale tip is detected, so we
1921 // try opening an additional OUTBOUND_FULL_RELAY connection. If none of
1922 // these conditions are met, check to see if it's time to try an extra
1923 // block-relay-only peer (to confirm our tip is current, see below) or
1924 // the next_feeler timer to decide if we should open a FEELER.
1925
1926 if (!m_anchors.empty() &&
1927 (nOutboundBlockRelay < m_max_outbound_block_relay)) {
1928 conn_type = ConnectionType::BLOCK_RELAY;
1929 anchor = true;
1930 } else if (nOutboundAvalanche < m_max_avalanche_outbound) {
1932 } else if (nOutboundFullRelay < m_max_outbound_full_relay) {
1933 // OUTBOUND_FULL_RELAY
1934 } else if (nOutboundBlockRelay < m_max_outbound_block_relay) {
1935 conn_type = ConnectionType::BLOCK_RELAY;
1936 } else if (GetTryNewOutboundPeer()) {
1937 // OUTBOUND_FULL_RELAY
1938 } else if (now > next_extra_block_relay &&
1940 // Periodically connect to a peer (using regular outbound selection
1941 // methodology from addrman) and stay connected long enough to sync
1942 // headers, but not much else.
1943 //
1944 // Then disconnect the peer, if we haven't learned anything new.
1945 //
1946 // The idea is to make eclipse attacks very difficult to pull off,
1947 // because every few minutes we're finding a new peer to learn
1948 // headers from.
1949 //
1950 // This is similar to the logic for trying extra outbound
1951 // (full-relay) peers, except:
1952 // - we do this all the time on an exponential timer, rather than
1953 // just when our tip is stale
1954 // - we potentially disconnect our next-youngest block-relay-only
1955 // peer, if our newest block-relay-only peer delivers a block more
1956 // recently.
1957 // See the eviction logic in net_processing.cpp.
1958 //
1959 // Because we can promote these connections to block-relay-only
1960 // connections, they do not get their own ConnectionType enum
1961 // (similar to how we deal with extra outbound peers).
1962 next_extra_block_relay =
1963 now +
1965 conn_type = ConnectionType::BLOCK_RELAY;
1966 } else if (now > next_feeler) {
1967 next_feeler = now + rng.rand_exp_duration(FEELER_INTERVAL);
1968 conn_type = ConnectionType::FEELER;
1969 fFeeler = true;
1970 } else {
1971 // skip to next iteration of while loop
1972 continue;
1973 }
1974
1976
1977 const auto current_time{NodeClock::now()};
1978 int nTries = 0;
1979 while (!interruptNet) {
1980 if (anchor && !m_anchors.empty()) {
1981 const CAddress addr = m_anchors.back();
1982 m_anchors.pop_back();
1983 if (!addr.IsValid() || IsLocal(addr) || !IsReachable(addr) ||
1985 setConnected.count(addr.GetGroup(addrman.GetAsmap()))) {
1986 continue;
1987 }
1988 addrConnect = addr;
1990 "Trying to make an anchor connection to %s\n",
1991 addrConnect.ToStringAddrPort());
1992 break;
1993 }
1994 // If we didn't find an appropriate destination after trying 100
1995 // addresses fetched from addrman, stop this loop, and let the outer
1996 // loop run again (which sleeps, adds seed nodes, recalculates
1997 // already-connected network ranges, ...) before trying new addrman
1998 // addresses.
1999 nTries++;
2000 if (nTries > 100) {
2001 break;
2002 }
2003
2004 CAddress addr;
2005 NodeSeconds addr_last_try{0s};
2006
2007 if (fFeeler) {
2008 // First, try to get a tried table collision address. This
2009 // returns an empty (invalid) address if there are no collisions
2010 // to try.
2011 std::tie(addr, addr_last_try) = addrman.SelectTriedCollision();
2012
2013 if (!addr.IsValid()) {
2014 // No tried table collisions. Select a new table address
2015 // for our feeler.
2016 std::tie(addr, addr_last_try) = addrman.Select(true);
2017 } else if (AlreadyConnectedToAddress(addr)) {
2018 // If test-before-evict logic would have us connect to a
2019 // peer that we're already connected to, just mark that
2020 // address as Good(). We won't be able to initiate the
2021 // connection anyway, so this avoids inadvertently evicting
2022 // a currently-connected peer.
2023 addrman.Good(addr);
2024 // Select a new table address for our feeler instead.
2025 std::tie(addr, addr_last_try) = addrman.Select(true);
2026 }
2027 } else {
2028 // Not a feeler
2029 std::tie(addr, addr_last_try) = addrman.Select();
2030 }
2031
2032 // Require outbound connections, other than feelers and avalanche,
2033 // to be to distinct network groups
2034 if (!fFeeler && conn_type != ConnectionType::AVALANCHE_OUTBOUND &&
2035 setConnected.count(addr.GetGroup(addrman.GetAsmap()))) {
2036 break;
2037 }
2038
2039 // if we selected an invalid or local address, restart
2040 if (!addr.IsValid() || IsLocal(addr)) {
2041 break;
2042 }
2043
2044 if (!IsReachable(addr)) {
2045 continue;
2046 }
2047
2048 // only consider very recently tried nodes after 30 failed attempts
2049 if (current_time - addr_last_try < 10min && nTries < 30) {
2050 continue;
2051 }
2052
2053 // for non-feelers, require all the services we'll want,
2054 // for feelers, only require they be a full node (only because most
2055 // SPV clients don't have a good address DB available)
2056 if (!fFeeler && !HasAllDesirableServiceFlags(addr.nServices)) {
2057 continue;
2058 }
2059
2060 if (fFeeler && !MayHaveUsefulAddressDB(addr.nServices)) {
2061 continue;
2062 }
2063
2064 // Do not connect to bad ports, unless 50 invalid addresses have
2065 // been selected already.
2066 if (nTries < 50 && (addr.IsIPv4() || addr.IsIPv6()) &&
2067 IsBadPort(addr.GetPort())) {
2068 continue;
2069 }
2070
2071 // For avalanche peers, check they have the avalanche service bit
2072 // set.
2073 if (conn_type == ConnectionType::AVALANCHE_OUTBOUND &&
2074 !(addr.nServices & NODE_AVALANCHE)) {
2075 // If this peer is not suitable as an avalanche one and we tried
2076 // over 20 addresses already, see if we can fallback to a non
2077 // avalanche full outbound.
2078 if (nTries < 20 ||
2079 nOutboundFullRelay >= m_max_outbound_full_relay ||
2080 setConnected.count(addr.GetGroup(addrman.GetAsmap()))) {
2081 // Fallback is not desirable or possible, try another one
2082 continue;
2083 }
2084
2085 // Fallback is possible, update the connection type accordingly
2087 }
2088
2089 addrConnect = addr;
2090 break;
2091 }
2092
2093 if (addrConnect.IsValid()) {
2094 if (fFeeler) {
2095 // Add small amount of random noise before connection to avoid
2096 // synchronization.
2100 return;
2101 }
2102 LogPrint(BCLog::NET, "Making feeler connection to %s\n",
2103 addrConnect.ToStringAddrPort());
2104 }
2105
2106 // This mock is for testing purpose only. It prevents the thread
2107 // from attempting the connection which is useful for testing.
2108 if (mockOpenConnection) {
2109 mockOpenConnection(addrConnect, conn_type);
2110 } else {
2111 OpenNetworkConnection(addrConnect,
2112 int(setConnected.size()) >=
2113 std::min(nMaxConnections - 1, 2),
2114 &grant, nullptr, conn_type);
2115 }
2116 }
2117 }
2118}
2119
2120std::vector<CAddress> CConnman::GetCurrentBlockRelayOnlyConns() const {
2121 std::vector<CAddress> ret;
2123 for (const CNode *pnode : m_nodes) {
2124 if (pnode->IsBlockOnlyConn()) {
2125 ret.push_back(pnode->addr);
2126 }
2127 }
2128
2129 return ret;
2130}
2131
2132std::vector<AddedNodeInfo> CConnman::GetAddedNodeInfo() const {
2133 std::vector<AddedNodeInfo> ret;
2134
2135 std::list<std::string> lAddresses(0);
2136 {
2138 ret.reserve(m_added_nodes.size());
2139 std::copy(m_added_nodes.cbegin(), m_added_nodes.cend(),
2140 std::back_inserter(lAddresses));
2141 }
2142
2143 // Build a map of all already connected addresses (by IP:port and by name)
2144 // to inbound/outbound and resolved CService
2145 std::map<CService, bool> mapConnected;
2146 std::map<std::string, std::pair<bool, CService>> mapConnectedByName;
2147 {
2149 for (const CNode *pnode : m_nodes) {
2150 if (pnode->addr.IsValid()) {
2151 mapConnected[pnode->addr] = pnode->IsInboundConn();
2152 }
2153 std::string addrName{pnode->m_addr_name};
2154 if (!addrName.empty()) {
2155 mapConnectedByName[std::move(addrName)] =
2156 std::make_pair(pnode->IsInboundConn(),
2157 static_cast<const CService &>(pnode->addr));
2158 }
2159 }
2160 }
2161
2162 for (const std::string &strAddNode : lAddresses) {
2163 CService service(
2164 LookupNumeric(strAddNode, Params().GetDefaultPort(strAddNode)));
2165 AddedNodeInfo addedNode{strAddNode, CService(), false, false};
2166 if (service.IsValid()) {
2167 // strAddNode is an IP:port
2168 auto it = mapConnected.find(service);
2169 if (it != mapConnected.end()) {
2170 addedNode.resolvedAddress = service;
2171 addedNode.fConnected = true;
2172 addedNode.fInbound = it->second;
2173 }
2174 } else {
2175 // strAddNode is a name
2176 auto it = mapConnectedByName.find(strAddNode);
2177 if (it != mapConnectedByName.end()) {
2178 addedNode.resolvedAddress = it->second.second;
2179 addedNode.fConnected = true;
2180 addedNode.fInbound = it->second.first;
2181 }
2182 }
2183 ret.emplace_back(std::move(addedNode));
2184 }
2185
2186 return ret;
2187}
2188
2191 while (true) {
2193 std::vector<AddedNodeInfo> vInfo = GetAddedNodeInfo();
2194 bool tried = false;
2195 for (const AddedNodeInfo &info : vInfo) {
2196 if (!info.fConnected) {
2197 if (!grant.TryAcquire()) {
2198 // If we've used up our semaphore and need a new one, let's
2199 // not wait here since while we are waiting the
2200 // addednodeinfo state might change.
2201 break;
2202 }
2203 tried = true;
2204 CAddress addr(CService(), NODE_NONE);
2205 OpenNetworkConnection(addr, false, &grant,
2206 info.strAddedNode.c_str(),
2208 if (!interruptNet.sleep_for(std::chrono::milliseconds(500))) {
2209 return;
2210 }
2211 }
2212 }
2213 // Retry every 60 seconds if a connection was attempted, otherwise two
2214 // seconds.
2215 if (!interruptNet.sleep_for(std::chrono::seconds(tried ? 60 : 2))) {
2216 return;
2217 }
2218 }
2219}
2220
2221// If successful, this moves the passed grant to the constructed node.
2223 bool fCountFailure,
2224 CSemaphoreGrant *grantOutbound,
2225 const char *pszDest,
2226 ConnectionType conn_type) {
2228 assert(conn_type != ConnectionType::INBOUND);
2229
2230 //
2231 // Initiate outbound network connection
2232 //
2233 if (interruptNet) {
2234 return;
2235 }
2236 if (!fNetworkActive) {
2237 return;
2238 }
2239 if (!pszDest) {
2240 bool banned_or_discouraged =
2241 m_banman && (m_banman->IsDiscouraged(addrConnect) ||
2242 m_banman->IsBanned(addrConnect));
2243 if (IsLocal(addrConnect) || banned_or_discouraged ||
2244 AlreadyConnectedToAddress(addrConnect)) {
2245 return;
2246 }
2247 } else if (FindNode(std::string(pszDest))) {
2248 return;
2249 }
2250
2251 CNode *pnode = ConnectNode(addrConnect, pszDest, fCountFailure, conn_type);
2252
2253 if (!pnode) {
2254 return;
2255 }
2256 if (grantOutbound) {
2257 grantOutbound->MoveTo(pnode->grantOutbound);
2258 }
2259
2260 for (auto interface : m_msgproc) {
2261 interface->InitializeNode(*config, *pnode, nLocalServices);
2262 }
2263
2264 {
2266 m_nodes.push_back(pnode);
2267 }
2268}
2269
2271
2274
2275 while (!flagInterruptMsgProc) {
2276 bool fMoreWork = false;
2277
2278 {
2279 // Randomize the order in which we process messages from/to our
2280 // peers. This prevents attacks in which an attacker exploits having
2281 // multiple consecutive connections in the vNodes list.
2282 const NodesSnapshot snap{*this, /*shuffle=*/true};
2283
2284 for (CNode *pnode : snap.Nodes()) {
2285 if (pnode->fDisconnect) {
2286 continue;
2287 }
2288
2289 bool fMoreNodeWork = false;
2290 // Receive messages
2291 for (auto interface : m_msgproc) {
2292 fMoreNodeWork |= interface->ProcessMessages(
2293 *config, pnode, flagInterruptMsgProc);
2294 }
2295 fMoreWork |= (fMoreNodeWork && !pnode->fPauseSend);
2297 return;
2298 }
2299
2300 // Send messages
2301 for (auto interface : m_msgproc) {
2302 interface->SendMessages(*config, pnode);
2303 }
2304
2306 return;
2307 }
2308 }
2309 }
2310
2311 WAIT_LOCK(mutexMsgProc, lock);
2312 if (!fMoreWork) {
2313 condMsgProc.wait_until(lock,
2314 std::chrono::steady_clock::now() +
2315 std::chrono::milliseconds(100),
2316 [this]() EXCLUSIVE_LOCKS_REQUIRED(
2317 mutexMsgProc) { return fMsgProcWake; });
2318 }
2319 fMsgProcWake = false;
2320 }
2321}
2322
2324 static constexpr auto err_wait_begin = 1s;
2325 static constexpr auto err_wait_cap = 5min;
2326 auto err_wait = err_wait_begin;
2327
2328 bool advertising_listen_addr = false;
2329 i2p::Connection conn;
2330
2331 while (!interruptNet) {
2332 if (!m_i2p_sam_session->Listen(conn)) {
2333 if (advertising_listen_addr && conn.me.IsValid()) {
2334 RemoveLocal(conn.me);
2335 advertising_listen_addr = false;
2336 }
2337
2338 interruptNet.sleep_for(err_wait);
2339 if (err_wait < err_wait_cap) {
2340 err_wait *= 2;
2341 }
2342
2343 continue;
2344 }
2345
2346 if (!advertising_listen_addr) {
2347 AddLocal(conn.me, LOCAL_MANUAL);
2348 advertising_listen_addr = true;
2349 }
2350
2351 if (!m_i2p_sam_session->Accept(conn)) {
2352 continue;
2353 }
2354
2356 std::move(conn.sock), NetPermissionFlags::None,
2357 CAddress{conn.me, NODE_NONE}, CAddress{conn.peer, NODE_NONE});
2358 }
2359}
2360
2361bool CConnman::BindListenPort(const CService &addrBind, bilingual_str &strError,
2362 NetPermissionFlags permissions) {
2363 int nOne = 1;
2364
2365 // Create socket for listening for incoming connections
2366 struct sockaddr_storage sockaddr;
2367 socklen_t len = sizeof(sockaddr);
2368 if (!addrBind.GetSockAddr((struct sockaddr *)&sockaddr, &len)) {
2369 strError =
2370 strprintf(Untranslated("Bind address family for %s not supported"),
2371 addrBind.ToStringAddrPort());
2373 strError.original);
2374 return false;
2375 }
2376
2377 std::unique_ptr<Sock> sock =
2378 CreateSock(addrBind.GetSAFamily(), SOCK_STREAM, IPPROTO_TCP);
2379 if (!sock) {
2380 strError =
2381 strprintf(Untranslated("Couldn't open socket for incoming "
2382 "connections (socket returned error %s)"),
2385 strError.original);
2386 return false;
2387 }
2388
2389 // Allow binding if the port is still in TIME_WAIT state after
2390 // the program was closed and restarted.
2391 if (sock->SetSockOpt(SOL_SOCKET, SO_REUSEADDR, (sockopt_arg_type)&nOne,
2392 sizeof(int)) == SOCKET_ERROR) {
2393 strError = strprintf(
2395 "Error setting SO_REUSEADDR on socket: %s, continuing anyway"),
2397 LogPrintf("%s\n", strError.original);
2398 }
2399
2400 // Some systems don't have IPV6_V6ONLY but are always v6only; others do have
2401 // the option and enable it by default or not. Try to enable it, if
2402 // possible.
2403 if (addrBind.IsIPv6()) {
2404#ifdef IPV6_V6ONLY
2405 if (sock->SetSockOpt(IPPROTO_IPV6, IPV6_V6ONLY, (sockopt_arg_type)&nOne,
2406 sizeof(int)) == SOCKET_ERROR) {
2407 strError = strprintf(Untranslated("Error setting IPV6_V6ONLY on "
2408 "socket: %s, continuing anyway"),
2410 LogPrintf("%s\n", strError.original);
2411 }
2412#endif
2413#ifdef WIN32
2414 int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED;
2415 if (sock->SetSockOpt(IPPROTO_IPV6, IPV6_PROTECTION_LEVEL,
2416 (sockopt_arg_type)&nProtLevel,
2417 sizeof(int)) == SOCKET_ERROR) {
2418 strError =
2419 strprintf(Untranslated("Error setting IPV6_PROTECTION_LEVEL on "
2420 "socket: %s, continuing anyway"),
2422 LogPrintf("%s\n", strError.original);
2423 }
2424#endif
2425 }
2426
2427 if (sock->Bind(reinterpret_cast<struct sockaddr *>(&sockaddr), len) ==
2428 SOCKET_ERROR) {
2429 int nErr = WSAGetLastError();
2430 if (nErr == WSAEADDRINUSE) {
2431 strError = strprintf(_("Unable to bind to %s on this computer. %s "
2432 "is probably already running."),
2433 addrBind.ToStringAddrPort(), PACKAGE_NAME);
2434 } else {
2435 strError = strprintf(_("Unable to bind to %s on this computer "
2436 "(bind returned error %s)"),
2437 addrBind.ToStringAddrPort(),
2438 NetworkErrorString(nErr));
2439 }
2440
2442 strError.original);
2443 return false;
2444 }
2445 LogPrintf("Bound to %s\n", addrBind.ToStringAddrPort());
2446
2447 // Listen for incoming connections
2448 if (sock->Listen(SOMAXCONN) == SOCKET_ERROR) {
2449 strError = strprintf(_("Listening for incoming connections "
2450 "failed (listen returned error %s)"),
2453 strError.original);
2454 return false;
2455 }
2456
2457 vhListenSocket.emplace_back(std::move(sock), permissions);
2458 return true;
2459}
2460
2461void Discover() {
2462 if (!fDiscover) {
2463 return;
2464 }
2465
2466 for (const CNetAddr &addr : GetLocalAddresses()) {
2467 if (AddLocal(addr, LOCAL_IF)) {
2468 LogPrintf("%s: %s\n", __func__, addr.ToStringAddr());
2469 }
2470 }
2471}
2472
2474 LogPrintf("%s: %s\n", __func__, active);
2475
2476 if (fNetworkActive == active) {
2477 return;
2478 }
2479
2480 fNetworkActive = active;
2481
2482 if (m_client_interface) {
2483 m_client_interface->NotifyNetworkActiveChanged(fNetworkActive);
2484 }
2485}
2486
2487CConnman::CConnman(const Config &configIn, uint64_t nSeed0In, uint64_t nSeed1In,
2488 AddrMan &addrmanIn, bool network_active)
2489 : config(&configIn), addrman(addrmanIn), nSeed0(nSeed0In),
2490 nSeed1(nSeed1In) {
2491 SetTryNewOutboundPeer(false);
2492
2493 Options connOptions;
2494 Init(connOptions);
2495 SetNetworkActive(network_active);
2496}
2497
2499 return nLastNodeId.fetch_add(1);
2500}
2501
2502bool CConnman::Bind(const CService &addr, unsigned int flags,
2503 NetPermissionFlags permissions) {
2504 if (!(flags & BF_EXPLICIT) && !IsReachable(addr)) {
2505 return false;
2506 }
2507 bilingual_str strError;
2508 if (!BindListenPort(addr, strError, permissions)) {
2510 m_client_interface->ThreadSafeMessageBox(
2511 strError, "", CClientUIInterface::MSG_ERROR);
2512 }
2513 return false;
2514 }
2515
2516 if (addr.IsRoutable() && fDiscover && !(flags & BF_DONT_ADVERTISE) &&
2518 AddLocal(addr, LOCAL_BIND);
2519 }
2520
2521 return true;
2522}
2523
2524bool CConnman::InitBinds(const Options &options) {
2525 for (const auto &addrBind : options.vBinds) {
2526 if (!Bind(addrBind, BF_EXPLICIT | BF_REPORT_ERROR,
2528 return false;
2529 }
2530 }
2531 for (const auto &addrBind : options.vWhiteBinds) {
2532 if (!Bind(addrBind.m_service, BF_EXPLICIT | BF_REPORT_ERROR,
2533 addrBind.m_flags)) {
2534 return false;
2535 }
2536 }
2537 for (const auto &addr_bind : options.onion_binds) {
2540 return false;
2541 }
2542 }
2543 if (options.bind_on_any) {
2544 // Don't consider errors to bind on IPv6 "::" fatal because the host OS
2545 // may not have IPv6 support and the user did not explicitly ask us to
2546 // bind on that.
2547 const CService ipv6_any{in6_addr(IN6ADDR_ANY_INIT),
2548 GetListenPort()}; // ::
2550
2551 struct in_addr inaddr_any;
2552 inaddr_any.s_addr = htonl(INADDR_ANY);
2553 const CService ipv4_any{inaddr_any, GetListenPort()}; // 0.0.0.0
2555 return false;
2556 }
2557 }
2558 return true;
2559}
2560
2561bool CConnman::Start(CScheduler &scheduler, const Options &connOptions) {
2562 Init(connOptions);
2563
2564 if (fListen && !InitBinds(connOptions)) {
2565 if (m_client_interface) {
2566 m_client_interface->ThreadSafeMessageBox(
2567 _("Failed to listen on any port. Use -listen=0 if you want "
2568 "this."),
2570 }
2571 return false;
2572 }
2573
2574 Proxy i2p_sam;
2575 if (GetProxy(NET_I2P, i2p_sam) && connOptions.m_i2p_accept_incoming) {
2576 m_i2p_sam_session = std::make_unique<i2p::sam::Session>(
2577 gArgs.GetDataDirNet() / "i2p_private_key", i2p_sam, &interruptNet);
2578 }
2579
2580 for (const auto &strDest : connOptions.vSeedNodes) {
2581 AddAddrFetch(strDest);
2582 }
2583
2585 // Load addresses from anchors.dat
2586 m_anchors =
2591 }
2592 LogPrintf(
2593 "%i block-relay-only anchors will be tried for connections.\n",
2594 m_anchors.size());
2595 }
2596
2597 if (m_client_interface) {
2598 m_client_interface->InitMessage(
2599 _("Starting network threads...").translated);
2600 }
2601
2602 fAddressesInitialized = true;
2603
2604 if (semOutbound == nullptr) {
2605 // initialize semaphore
2606 semOutbound = std::make_unique<CSemaphore>(
2607 std::min(m_max_outbound, nMaxConnections));
2608 }
2609 if (semAddnode == nullptr) {
2610 // initialize semaphore
2611 semAddnode = std::make_unique<CSemaphore>(nMaxAddnode);
2612 }
2613
2614 //
2615 // Start threads
2616 //
2617 assert(m_msgproc.size() > 0);
2618 InterruptSocks5(false);
2620 flagInterruptMsgProc = false;
2621
2622 {
2624 fMsgProcWake = false;
2625 }
2626
2627 // Send and receive from sockets, accept connections
2628 threadSocketHandler = std::thread(&util::TraceThread, "net",
2629 [this] { ThreadSocketHandler(); });
2630
2631 if (!gArgs.GetBoolArg("-dnsseed", DEFAULT_DNSSEED)) {
2632 LogPrintf("DNS seeding disabled\n");
2633 } else {
2634 threadDNSAddressSeed = std::thread(&util::TraceThread, "dnsseed",
2635 [this] { ThreadDNSAddressSeed(); });
2636 }
2637
2638 // Initiate manual connections
2639 threadOpenAddedConnections = std::thread(
2640 &util::TraceThread, "addcon", [this] { ThreadOpenAddedConnections(); });
2641
2642 if (connOptions.m_use_addrman_outgoing &&
2643 !connOptions.m_specified_outgoing.empty()) {
2644 if (m_client_interface) {
2645 m_client_interface->ThreadSafeMessageBox(
2646 _("Cannot provide specific connections and have addrman find "
2647 "outgoing connections at the same."),
2649 }
2650 return false;
2651 }
2652 if (connOptions.m_use_addrman_outgoing ||
2653 !connOptions.m_specified_outgoing.empty()) {
2655 std::thread(&util::TraceThread, "opencon",
2656 [this, connect = connOptions.m_specified_outgoing] {
2657 ThreadOpenConnections(connect, nullptr);
2658 });
2659 }
2660
2661 // Process messages
2662 threadMessageHandler = std::thread(&util::TraceThread, "msghand",
2663 [this] { ThreadMessageHandler(); });
2664
2665 if (m_i2p_sam_session) {
2667 std::thread(&util::TraceThread, "i2paccept",
2668 [this] { ThreadI2PAcceptIncoming(); });
2669 }
2670
2671 // Dump network addresses
2672 scheduler.scheduleEvery(
2673 [this]() {
2674 this->DumpAddresses();
2675 return true;
2676 },
2678
2679 return true;
2680}
2681
2683public:
2684 CNetCleanup() = default;
2685
2687#ifdef WIN32
2688 // Shutdown Windows Sockets
2689 WSACleanup();
2690#endif
2691 }
2692};
2694
2696 {
2698 flagInterruptMsgProc = true;
2699 }
2700 condMsgProc.notify_all();
2701
2702 interruptNet();
2703 InterruptSocks5(true);
2704
2705 if (semOutbound) {
2706 for (int i = 0; i < m_max_outbound; i++) {
2707 semOutbound->post();
2708 }
2709 }
2710
2711 if (semAddnode) {
2712 for (int i = 0; i < nMaxAddnode; i++) {
2713 semAddnode->post();
2714 }
2715 }
2716}
2717
2719 if (threadI2PAcceptIncoming.joinable()) {
2721 }
2722 if (threadMessageHandler.joinable()) {
2723 threadMessageHandler.join();
2724 }
2725 if (threadOpenConnections.joinable()) {
2726 threadOpenConnections.join();
2727 }
2728 if (threadOpenAddedConnections.joinable()) {
2730 }
2731 if (threadDNSAddressSeed.joinable()) {
2732 threadDNSAddressSeed.join();
2733 }
2734 if (threadSocketHandler.joinable()) {
2735 threadSocketHandler.join();
2736 }
2737}
2738
2741 DumpAddresses();
2742 fAddressesInitialized = false;
2743
2745 // Anchor connections are only dumped during clean shutdown.
2746 std::vector<CAddress> anchors_to_dump =
2748 if (anchors_to_dump.size() > MAX_BLOCK_RELAY_ONLY_ANCHORS) {
2749 anchors_to_dump.resize(MAX_BLOCK_RELAY_ONLY_ANCHORS);
2750 }
2753 anchors_to_dump);
2754 }
2755 }
2756
2757 // Delete peer connections.
2758 std::vector<CNode *> nodes;
2759 WITH_LOCK(m_nodes_mutex, nodes.swap(m_nodes));
2760 for (CNode *pnode : nodes) {
2761 pnode->CloseSocketDisconnect();
2762 DeleteNode(pnode);
2763 }
2764
2765 for (CNode *pnode : m_nodes_disconnected) {
2766 DeleteNode(pnode);
2767 }
2768 m_nodes_disconnected.clear();
2769 vhListenSocket.clear();
2770 semOutbound.reset();
2771 semAddnode.reset();
2772}
2773
2775 assert(pnode);
2776 for (auto interface : m_msgproc) {
2777 interface->FinalizeNode(*config, *pnode);
2778 }
2779 delete pnode;
2780}
2781
2783 Interrupt();
2784 Stop();
2785}
2786
2787std::vector<CAddress>
2788CConnman::GetAddresses(size_t max_addresses, size_t max_pct,
2789 std::optional<Network> network) const {
2790 std::vector<CAddress> addresses =
2791 addrman.GetAddr(max_addresses, max_pct, network);
2792 if (m_banman) {
2793 addresses.erase(std::remove_if(addresses.begin(), addresses.end(),
2794 [this](const CAddress &addr) {
2795 return m_banman->IsDiscouraged(
2796 addr) ||
2797 m_banman->IsBanned(addr);
2798 }),
2799 addresses.end());
2800 }
2801 return addresses;
2802}
2803
2804std::vector<CAddress>
2805CConnman::GetAddresses(CNode &requestor, size_t max_addresses, size_t max_pct) {
2806 auto local_socket_bytes = requestor.addrBind.GetAddrBytes();
2808 .Write(requestor.addr.GetNetwork())
2809 .Write(local_socket_bytes)
2810 .Finalize();
2811 const auto current_time = GetTime<std::chrono::microseconds>();
2812 auto r = m_addr_response_caches.emplace(cache_id, CachedAddrResponse{});
2813 CachedAddrResponse &cache_entry = r.first->second;
2814 // New CachedAddrResponse have expiration 0.
2815 if (cache_entry.m_cache_entry_expiration < current_time) {
2816 cache_entry.m_addrs_response_cache =
2817 GetAddresses(max_addresses, max_pct, /* network */ std::nullopt);
2818 // Choosing a proper cache lifetime is a trade-off between the privacy
2819 // leak minimization and the usefulness of ADDR responses to honest
2820 // users.
2821 //
2822 // Longer cache lifetime makes it more difficult for an attacker to
2823 // scrape enough AddrMan data to maliciously infer something useful. By
2824 // the time an attacker scraped enough AddrMan records, most of the
2825 // records should be old enough to not leak topology info by e.g.
2826 // analyzing real-time changes in timestamps.
2827 //
2828 // It takes only several hundred requests to scrape everything from an
2829 // AddrMan containing 100,000 nodes, so ~24 hours of cache lifetime
2830 // indeed makes the data less inferable by the time most of it could be
2831 // scraped (considering that timestamps are updated via ADDR
2832 // self-announcements and when nodes communicate). We also should be
2833 // robust to those attacks which may not require scraping *full*
2834 // victim's AddrMan (because even several timestamps of the same handful
2835 // of nodes may leak privacy).
2836 //
2837 // On the other hand, longer cache lifetime makes ADDR responses
2838 // outdated and less useful for an honest requestor, e.g. if most nodes
2839 // in the ADDR response are no longer active.
2840 //
2841 // However, the churn in the network is known to be rather low. Since we
2842 // consider nodes to be "terrible" (see IsTerrible()) if the timestamps
2843 // are older than 30 days, max. 24 hours of "penalty" due to cache
2844 // shouldn't make any meaningful difference in terms of the freshness of
2845 // the response.
2846 cache_entry.m_cache_entry_expiration =
2847 current_time + 21h +
2848 FastRandomContext().randrange<std::chrono::microseconds>(6h);
2849 }
2850 return cache_entry.m_addrs_response_cache;
2851}
2852
2853bool CConnman::AddNode(const std::string &strNode) {
2855 for (const std::string &it : m_added_nodes) {
2856 if (strNode == it) {
2857 return false;
2858 }
2859 }
2860
2861 m_added_nodes.push_back(strNode);
2862 return true;
2863}
2864
2865bool CConnman::RemoveAddedNode(const std::string &strNode) {
2867 for (std::vector<std::string>::iterator it = m_added_nodes.begin();
2868 it != m_added_nodes.end(); ++it) {
2869 if (strNode == *it) {
2870 m_added_nodes.erase(it);
2871 return true;
2872 }
2873 }
2874 return false;
2875}
2876
2879 // Shortcut if we want total
2881 return m_nodes.size();
2882 }
2883
2884 int nNum = 0;
2885 for (const auto &pnode : m_nodes) {
2886 if (flags & (pnode->IsInboundConn() ? ConnectionDirection::In
2888 nNum++;
2889 }
2890 }
2891
2892 return nNum;
2893}
2894
2895void CConnman::GetNodeStats(std::vector<CNodeStats> &vstats) const {
2896 vstats.clear();
2898 vstats.reserve(m_nodes.size());
2899 for (CNode *pnode : m_nodes) {
2900 vstats.emplace_back();
2901 pnode->copyStats(vstats.back());
2902 vstats.back().m_mapped_as = pnode->addr.GetMappedAS(addrman.GetAsmap());
2903 }
2904}
2905
2908
2909 for (auto &&pnode : m_nodes) {
2910 if (pnode->GetId() == id) {
2911 pnode->copyStats(stats);
2912 stats.m_mapped_as = pnode->addr.GetMappedAS(addrman.GetAsmap());
2913 return true;
2914 }
2915 }
2916
2917 return false;
2918}
2919
2920bool CConnman::DisconnectNode(const std::string &strNode) {
2922 if (CNode *pnode = FindNode(strNode)) {
2924 "disconnect by address%s matched peer=%d; disconnecting\n",
2925 (fLogIPs ? strprintf("=%s", strNode) : ""), pnode->GetId());
2926 pnode->fDisconnect = true;
2927 return true;
2928 }
2929 return false;
2930}
2931
2933 bool disconnected = false;
2935 for (CNode *pnode : m_nodes) {
2936 if (subnet.Match(pnode->addr)) {
2938 "disconnect by subnet%s matched peer=%d; disconnecting\n",
2939 (fLogIPs ? strprintf("=%s", subnet.ToString()) : ""),
2940 pnode->GetId());
2941 pnode->fDisconnect = true;
2942 disconnected = true;
2943 }
2944 }
2945 return disconnected;
2946}
2947
2949 return DisconnectNode(CSubNet(addr));
2950}
2951
2954 for (CNode *pnode : m_nodes) {
2955 if (id == pnode->GetId()) {
2956 LogPrint(BCLog::NET, "disconnect by id peer=%d; disconnecting\n",
2957 pnode->GetId());
2958 pnode->fDisconnect = true;
2959 return true;
2960 }
2961 }
2962 return false;
2963}
2964
2965void CConnman::RecordBytesRecv(uint64_t bytes) {
2966 nTotalBytesRecv += bytes;
2967}
2968
2969void CConnman::RecordBytesSent(uint64_t bytes) {
2971 nTotalBytesSent += bytes;
2972
2973 const auto now = GetTime<std::chrono::seconds>();
2974 if (nMaxOutboundCycleStartTime + MAX_UPLOAD_TIMEFRAME < now) {
2975 // timeframe expired, reset cycle
2976 nMaxOutboundCycleStartTime = now;
2977 nMaxOutboundTotalBytesSentInCycle = 0;
2978 }
2979
2980 // TODO, exclude peers with download permission
2981 nMaxOutboundTotalBytesSentInCycle += bytes;
2982}
2983
2986 return nMaxOutboundLimit;
2987}
2988
2989std::chrono::seconds CConnman::GetMaxOutboundTimeframe() const {
2990 return MAX_UPLOAD_TIMEFRAME;
2991}
2992
2993std::chrono::seconds CConnman::GetMaxOutboundTimeLeftInCycle() const {
2995 if (nMaxOutboundLimit == 0) {
2996 return 0s;
2997 }
2998
2999 if (nMaxOutboundCycleStartTime.count() == 0) {
3000 return MAX_UPLOAD_TIMEFRAME;
3001 }
3002
3003 const std::chrono::seconds cycleEndTime =
3004 nMaxOutboundCycleStartTime + MAX_UPLOAD_TIMEFRAME;
3005 const auto now = GetTime<std::chrono::seconds>();
3006 return (cycleEndTime < now) ? 0s : cycleEndTime - now;
3007}
3008
3009bool CConnman::OutboundTargetReached(bool historicalBlockServingLimit) const {
3011 if (nMaxOutboundLimit == 0) {
3012 return false;
3013 }
3014
3015 if (historicalBlockServingLimit) {
3016 // keep a large enough buffer to at least relay each block once.
3017 const std::chrono::seconds timeLeftInCycle =
3019 const uint64_t buffer =
3020 timeLeftInCycle / std::chrono::minutes{10} * ONE_MEGABYTE;
3021 if (buffer >= nMaxOutboundLimit ||
3022 nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit - buffer) {
3023 return true;
3024 }
3025 } else if (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit) {
3026 return true;
3027 }
3028
3029 return false;
3030}
3031
3034 if (nMaxOutboundLimit == 0) {
3035 return 0;
3036 }
3037
3038 return (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit)
3039 ? 0
3040 : nMaxOutboundLimit - nMaxOutboundTotalBytesSentInCycle;
3041}
3042
3044 return nTotalBytesRecv;
3045}
3046
3049 return nTotalBytesSent;
3050}
3051
3053 return nLocalServices;
3054}
3055
3056void CNode::invsPolled(uint32_t count) {
3057 invCounters += count;
3058}
3059
3060void CNode::invsVoted(uint32_t count) {
3061 invCounters += uint64_t(count) << 32;
3062}
3063
3064void CNode::updateAvailabilityScore(double decayFactor) {
3065 if (!m_avalanche_enabled) {
3066 return;
3067 }
3068
3069 uint64_t windowInvCounters = invCounters.exchange(0);
3070 double previousScore = availabilityScore;
3071
3072 int64_t polls = windowInvCounters & std::numeric_limits<uint32_t>::max();
3073 int64_t votes = windowInvCounters >> 32;
3074
3076 decayFactor * (2 * votes - polls) + (1. - decayFactor) * previousScore;
3077}
3078
3080 // The score is set atomically so there is no need to lock the statistics
3081 // when reading.
3082 return availabilityScore;
3083}
3084
3085CNode::CNode(NodeId idIn, std::shared_ptr<Sock> sock, const CAddress &addrIn,
3086 uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn,
3087 uint64_t nLocalExtraEntropyIn, const CAddress &addrBindIn,
3088 const std::string &addrNameIn, ConnectionType conn_type_in,
3089 bool inbound_onion, CNodeOptions &&node_opts)
3090 : m_deserializer{std::make_unique<V1TransportDeserializer>(
3092 m_serializer{
3094 m_permission_flags{node_opts.permission_flags}, m_sock{sock},
3095 m_connected(GetTime<std::chrono::seconds>()), addr{addrIn},
3096 addrBind{addrBindIn},
3097 m_addr_name{addrNameIn.empty() ? addr.ToStringAddrPort() : addrNameIn},
3098 m_inbound_onion{inbound_onion}, m_prefer_evict{node_opts.prefer_evict},
3099 nKeyedNetGroup{nKeyedNetGroupIn}, m_conn_type{conn_type_in}, id{idIn},
3100 nLocalHostNonce{nLocalHostNonceIn},
3101 nLocalExtraEntropy{nLocalExtraEntropyIn},
3102 m_recv_flood_size{node_opts.recv_flood_size},
3103 m_i2p_sam_session{std::move(node_opts.i2p_sam_session)} {
3104 if (inbound_onion) {
3105 assert(conn_type_in == ConnectionType::INBOUND);
3106 }
3107
3108 for (const std::string &msg : getAllNetMessageTypes()) {
3109 mapRecvBytesPerMsgType[msg] = 0;
3110 }
3111 mapRecvBytesPerMsgType[NET_MESSAGE_TYPE_OTHER] = 0;
3112
3113 if (fLogIPs) {
3114 LogPrint(BCLog::NET, "Added connection to %s peer=%d\n", m_addr_name,
3115 id);
3116 } else {
3117 LogPrint(BCLog::NET, "Added connection peer=%d\n", id);
3118 }
3119}
3120
3123
3124 size_t nSizeAdded = 0;
3125 for (const auto &msg : vRecvMsg) {
3126 // vRecvMsg contains only completed CNetMessage
3127 // the single possible partially deserialized message are held by
3128 // TransportDeserializer
3129 nSizeAdded += msg.m_raw_message_size;
3130 }
3131
3133 m_msg_process_queue.splice(m_msg_process_queue.end(), vRecvMsg);
3134 m_msg_process_queue_size += nSizeAdded;
3135 pauseRecv(m_msg_process_queue_size > m_recv_flood_size);
3136}
3137
3138std::optional<std::pair<CNetMessage, bool>> CNode::PollMessage() {
3140 if (m_msg_process_queue.empty()) {
3141 return std::nullopt;
3142 }
3143
3144 std::list<CNetMessage> msgs;
3145 // Just take one message
3146 msgs.splice(msgs.begin(), m_msg_process_queue, m_msg_process_queue.begin());
3147 m_msg_process_queue_size -= msgs.front().m_raw_message_size;
3148 pauseRecv(m_msg_process_queue_size > m_recv_flood_size);
3149
3150 return std::make_pair(std::move(msgs.front()),
3151 !m_msg_process_queue.empty());
3152}
3153
3155 return pnode && pnode->fSuccessfullyConnected && !pnode->fDisconnect;
3156}
3157
3159 size_t nMessageSize = msg.data.size();
3160 LogPrint(BCLog::NETDEBUG, "sending %s (%d bytes) peer=%d\n", msg.m_type,
3161 nMessageSize, pnode->GetId());
3162 if (gArgs.GetBoolArg("-capturemessages", false)) {
3163 CaptureMessage(pnode->addr, msg.m_type, msg.data,
3164 /*is_incoming=*/false);
3165 }
3166
3167 TRACE6(net, outbound_message, pnode->GetId(), pnode->m_addr_name.c_str(),
3168 pnode->ConnectionTypeAsString().c_str(), msg.m_type.c_str(),
3169 msg.data.size(), msg.data.data());
3170
3171 // make sure we use the appropriate network transport format
3172 std::vector<uint8_t> serializedHeader;
3173 pnode->m_serializer->prepareForTransport(*config, msg, serializedHeader);
3174 size_t nTotalSize = nMessageSize + serializedHeader.size();
3175
3176 size_t nBytesSent = 0;
3177 {
3178 LOCK(pnode->cs_vSend);
3179 bool optimisticSend(pnode->vSendMsg.empty());
3180
3181 // log total amount of bytes per message type
3182 pnode->AccountForSentBytes(msg.m_type, nTotalSize);
3183 pnode->nSendSize += nTotalSize;
3184
3185 if (pnode->nSendSize > nSendBufferMaxSize) {
3186 pnode->fPauseSend = true;
3187 }
3188 pnode->vSendMsg.push_back(std::move(serializedHeader));
3189 if (nMessageSize) {
3190 pnode->vSendMsg.push_back(std::move(msg.data));
3191 }
3192
3193 // If write queue empty, attempt "optimistic write"
3194 bool data_left;
3195 if (optimisticSend) {
3196 std::tie(nBytesSent, data_left) = SocketSendData(*pnode);
3197 }
3198 }
3199 if (nBytesSent) {
3200 RecordBytesSent(nBytesSent);
3201 }
3202}
3203
3204bool CConnman::ForNode(NodeId id, std::function<bool(CNode *pnode)> func) {
3205 CNode *found = nullptr;
3207 for (auto &&pnode : m_nodes) {
3208 if (pnode->GetId() == id) {
3209 found = pnode;
3210 break;
3211 }
3212 }
3213 return found != nullptr && NodeFullyConnected(found) && func(found);
3214}
3215
3217 return CSipHasher(nSeed0, nSeed1).Write(id);
3218}
3219
3221 std::vector<uint8_t> vchNetGroup(ad.GetGroup(addrman.GetAsmap()));
3222
3224 .Write(vchNetGroup)
3225 .Finalize();
3226}
3227
3242std::string getSubVersionEB(uint64_t MaxBlockSize) {
3243 // Prepare EB string we are going to add to SubVer:
3244 // 1) translate from byte to MB and convert to string
3245 // 2) limit the EB string to the first decimal digit (floored)
3246 std::stringstream ebMBs;
3247 ebMBs << (MaxBlockSize / (ONE_MEGABYTE / 10));
3248 std::string eb = ebMBs.str();
3249 eb.insert(eb.size() - 1, ".", 1);
3250 if (eb.substr(0, 1) == ".") {
3251 eb = "0" + eb;
3252 }
3253 return eb;
3254}
3255
3256std::string userAgent(const Config &config) {
3257 // format excessive blocksize value
3258 std::string eb = getSubVersionEB(config.GetMaxBlockSize());
3259 std::vector<std::string> uacomments;
3260 uacomments.push_back("EB" + eb);
3261
3262 // Comments are checked for char compliance at startup, it is safe to add
3263 // them to the user agent string
3264 for (const std::string &cmt : gArgs.GetArgs("-uacomment")) {
3265 uacomments.push_back(cmt);
3266 }
3267
3268 const std::string client_name = gArgs.GetArg("-uaclientname", CLIENT_NAME);
3269 const std::string client_version =
3270 gArgs.GetArg("-uaclientversion", FormatVersion(CLIENT_VERSION));
3271
3272 // Size compliance is checked at startup, it is safe to not check it again
3273 return FormatUserAgent(client_name, client_version, uacomments);
3274}
3275
3276void CaptureMessageToFile(const CAddress &addr, const std::string &msg_type,
3277 Span<const uint8_t> data, bool is_incoming) {
3278 // Note: This function captures the message at the time of processing,
3279 // not at socket receive/send time.
3280 // This ensures that the messages are always in order from an application
3281 // layer (processing) perspective.
3282 auto now = GetTime<std::chrono::microseconds>();
3283
3284 // Windows folder names can not include a colon
3285 std::string clean_addr = addr.ToStringAddrPort();
3286 std::replace(clean_addr.begin(), clean_addr.end(), ':', '_');
3287
3288 fs::path base_path = gArgs.GetDataDirNet() / "message_capture" / clean_addr;
3289 fs::create_directories(base_path);
3290
3291 fs::path path =
3292 base_path / (is_incoming ? "msgs_recv.dat" : "msgs_sent.dat");
3293 AutoFile f{fsbridge::fopen(path, "ab")};
3294
3295 ser_writedata64(f, now.count());
3296 f << Span{msg_type};
3297 for (auto i = msg_type.length(); i < CMessageHeader::MESSAGE_TYPE_SIZE;
3298 ++i) {
3299 f << uint8_t{'\0'};
3300 }
3301 uint32_t size = data.size();
3302 ser_writedata32(f, size);
3303 f << data;
3304}
3305
3306std::function<void(const CAddress &addr, const std::string &msg_type,
3307 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
Definition: bitcoin-tx.cpp:546
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:21
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:1316
const std::vector< bool > & GetAsmap() const
Definition: addrman.cpp:1329
void Attempt(const CService &addr, bool fCountFailure, NodeSeconds time=Now< NodeSeconds >())
Mark an entry as connection attempted to.
Definition: addrman.cpp:1299
std::pair< CAddress, NodeSeconds > Select(bool newOnly=false) const
Choose an address to connect to.
Definition: addrman.cpp:1312
void ResolveCollisions()
See if any to-be-evicted tried table entries have been tested and if so resolve the collisions.
Definition: addrman.cpp:1304
size_t size() const
Return the number of (unique) addresses in all tables.
Definition: addrman.cpp:1285
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:1294
std::pair< CAddress, NodeSeconds > SelectTriedCollision()
Randomly select an address in the tried table that another address is attempting to evict.
Definition: addrman.cpp:1308
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:1289
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:430
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:442
ServiceFlags nServices
Serialized as uint64_t in V1, and as CompactSize in V2.
Definition: protocol.h:554
NodeSeconds nTime
Always included in serialization, except in the network format on INIT_PROTO_VERSION.
Definition: protocol.h:552
const CMessageHeader::MessageMagic & NetMagic() const
Definition: chainparams.h:100
const std::vector< SeedSpec6 > & FixedSeeds() const
Definition: chainparams.h:144
uint16_t GetDefaultPort() const
Definition: chainparams.h:101
RAII helper to atomically create a copy of m_nodes and add a reference to each of the nodes.
Definition: net.h:1427
bool whitelist_relay
flag for adding 'relay' permission to whitelisted inbound and manual peers with default permissions.
Definition: net.h:1418
std::condition_variable condMsgProc
Definition: net.h:1342
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:1175
std::thread threadMessageHandler
Definition: net.h:1365
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:2993
bool OutboundTargetReached(bool historicalBlockServingLimit) const
check if the outbound target is reached.
Definition: net.cpp:3009
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition: net.h:1242
CClientUIInterface * m_client_interface
Definition: net.h:1321
void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:2272
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:3204
void DeleteNode(CNode *pnode)
Definition: net.cpp:2774
bool RemoveAddedNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2865
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:1319
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:1406
bool GetTryNewOutboundPeer() const
Definition: net.cpp:1729
void Stop()
Definition: net.h:927
int m_max_outbound_block_relay
Definition: net.h:1312
std::thread threadI2PAcceptIncoming
Definition: net.h:1366
void SetTryNewOutboundPeer(bool flag)
Definition: net.cpp:1733
std::atomic< bool > flagInterruptMsgProc
Definition: net.h:1344
void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:2695
void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:1566
Sock::EventsPerSock GenerateWaitSockets(Span< CNode *const > nodes)
Generate a collection of sockets to check for IO readiness.
Definition: net.cpp:1361
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:1423
NodeId GetNewNodeId()
Definition: net.cpp:2498
CThreadInterrupt interruptNet
This is signaled when network activity should cease.
Definition: net.h:1352
std::unique_ptr< CSemaphore > semAddnode
Definition: net.h:1304
bool Start(CScheduler &scheduler, const Options &options) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition: net.cpp:2561
std::atomic< NodeId > nLastNodeId
Definition: net.h:1260
void RecordBytesSent(uint64_t bytes)
Definition: net.cpp:2969
int GetExtraBlockRelayCount() const
Definition: net.cpp:1761
void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:1558
BanMan * m_banman
Pointer to this node's banman.
Definition: net.h:1328
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:3032
std::thread threadDNSAddressSeed
Definition: net.h:1361
std::atomic< ServiceFlags > nLocalServices
Services this node offers.
Definition: net.h:1301
void ThreadI2PAcceptIncoming()
Definition: net.cpp:2323
const uint64_t nSeed1
Definition: net.h:1337
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
Definition: net.h:1334
std::chrono::seconds GetMaxOutboundTimeframe() const
Definition: net.cpp:2989
bool whitelist_forcerelay
flag for adding 'forcerelay' permission to whitelisted inbound and manual peers with default permissi...
Definition: net.h:1412
unsigned int nPrevNodeCount
Definition: net.h:1261
void NotifyNumConnectionsChanged()
Definition: net.cpp:1275
ServiceFlags GetLocalServices() const
Used to convey which local services we are offering peers during node connection.
Definition: net.cpp:3052
bool DisconnectNode(const std::string &node)
Definition: net.cpp:2920
std::chrono::seconds m_peer_connect_timeout
Definition: net.h:1238
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:1372
bool InitBinds(const Options &options)
Definition: net.cpp:2524
void AddAddrFetch(const std::string &strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex)
Definition: net.cpp:135
std::vector< ListenSocket > vhListenSocket
Definition: net.h:1249
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:2222
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const
Return vector of current BLOCK_RELAY peers.
Definition: net.cpp:2120
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition: net.cpp:3216
uint64_t GetMaxOutboundTarget() const
Definition: net.cpp:2984
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:1303
void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition: net.cpp:2189
RecursiveMutex cs_totalBytesSent
Definition: net.h:1227
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
Definition: net.cpp:2502
std::thread threadOpenConnections
Definition: net.h:1364
size_t GetNodeCount(ConnectionDirection) const
Definition: net.cpp:2877
void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:1710
Mutex m_addr_fetches_mutex
Definition: net.h:1254
bool InactivityCheck(const CNode &node) const
Return true if the peer is inactive and should be disconnected.
Definition: net.cpp:1294
CNode * FindNode(const CNetAddr &ip)
Definition: net.cpp:354
void GetNodeStats(std::vector< CNodeStats > &vstats) const
Definition: net.cpp:2895
std::vector< AddedNodeInfo > GetAddedNodeInfo() const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2132
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition: net.h:1337
unsigned int nReceiveFloodSize
Definition: net.h:1247
int GetExtraFullOutboundCount() const
Definition: net.cpp:1745
uint64_t GetTotalBytesRecv() const
Definition: net.cpp:3043
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:1259
static bool NodeFullyConnected(const CNode *pnode)
Definition: net.cpp:3154
int nMaxConnections
Definition: net.h:1305
CConnman(const Config &configIn, uint64_t seed0, uint64_t seed1, AddrMan &addrmanIn, bool network_active=true)
Definition: net.cpp:2487
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:2788
void SetNetworkActive(bool active)
Definition: net.cpp:2473
std::list< CNode * > m_nodes_disconnected
Definition: net.h:1258
AddrMan & addrman
Definition: net.h:1252
std::atomic_bool inflight_throttle
Definition: net.h:1420
void SocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Check connected and listening sockets for IO readiness and process them accordingly.
Definition: net.cpp:1395
uint64_t CalculateKeyedNetGroup(const CAddress &ad) const
Definition: net.cpp:3220
Mutex mutexMsgProc
Definition: net.h:1343
bool fAddressesInitialized
Definition: net.h:1251
virtual ~CConnman()
Definition: net.cpp:2782
void StopThreads()
Definition: net.cpp:2718
bool AddNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2853
std::thread threadOpenAddedConnections
Definition: net.h:1363
Mutex m_added_nodes_mutex
Definition: net.h:1256
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, const CNetAddr &addr, const std::vector< NetWhitelistPermissions > &ranges) const
Definition: net.cpp:604
const Config * config
Definition: net.h:1224
void Init(const Options &connOptions) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.h:875
bool CheckIncomingNonce(uint64_t nonce)
Definition: net.cpp:399
int m_max_outbound_full_relay
Definition: net.h:1308
Mutex m_unused_i2p_sessions_mutex
Mutex protecting m_i2p_sam_sessions.
Definition: net.h:1390
int nMaxAddnode
Definition: net.h:1317
void RecordBytesRecv(uint64_t bytes)
Definition: net.cpp:2965
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:1289
void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:1550
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:3158
void StopNodes()
Definition: net.cpp:2739
unsigned int nSendBufferMaxSize
Definition: net.h:1246
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
Definition: net.h:1359
bool m_use_addrman_outgoing
Definition: net.h:1320
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition: net.h:1244
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:1288
std::atomic< uint64_t > nTotalBytesRecv
Definition: net.h:1228
std::atomic< bool > fNetworkActive
Definition: net.h:1250
std::atomic_bool m_start_extra_block_relay_peers
flag for initiating extra block-relay-only peer connections.
Definition: net.h:1379
void DisconnectNodes()
Definition: net.cpp:1225
void SocketHandlerListening(const Sock::EventsPerSock &events_per_sock)
Accept incoming connections, one from each read-ready listening socket.
Definition: net.cpp:1537
void DumpAddresses()
Definition: net.cpp:1701
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:1385
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:1323
std::thread threadSocketHandler
Definition: net.h:1362
uint64_t GetTotalBytesSent() const
Definition: net.cpp:3047
void ThreadOpenConnections(std::vector< std::string > connect, std::function< void(const CAddress &, ConnectionType)> mockOpenConnection) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:1775
void AcceptConnection(const ListenSocket &hListenSocket)
Definition: net.cpp:1037
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
Definition: net.cpp:2361
int m_max_avalanche_outbound
Definition: net.h:1315
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
Definition: netaddress.cpp:744
std::string ToStringAddr() const
Definition: netaddress.cpp:630
bool IsRoutable() const
Definition: netaddress.cpp:516
bool IsValid() const
Definition: netaddress.cpp:477
bool IsIPv4() const
Definition: netaddress.cpp:340
bool IsIPv6() const
Definition: netaddress.cpp:344
std::vector< uint8_t > GetGroup(const std::vector< bool > &asmap) const
Get the canonical identifier of our network group.
Definition: netaddress.cpp:806
std::vector< uint8_t > GetAddrBytes() const
Definition: netaddress.cpp:861
bool SetInternal(const std::string &name)
Create an "internal" address that represents a name or FQDN.
Definition: netaddress.cpp:188
enum Network GetNetwork() const
Definition: netaddress.cpp:553
~CNetCleanup()
Definition: net.cpp:2686
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:769
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:690
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:736
std::atomic< bool > m_bip152_highbandwidth_to
Definition: net.h:565
std::list< CNetMessage > vRecvMsg
Definition: net.h:750
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:3085
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:3121
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:723
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:3138
double getAvailabilityScore() const
Definition: net.cpp:3079
Mutex m_msg_process_queue_mutex
Definition: net.h:752
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:748
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:664
void updateAvailabilityScore(double decayFactor)
The availability score is calculated using an exponentially weighted average.
Definition: net.cpp:3064
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:3056
Mutex m_addr_local_mutex
Definition: net.h:758
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:670
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:661
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:645
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:766
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:653
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:3060
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:41
void scheduleEvery(Predicate p, std::chrono::milliseconds delta) EXCLUSIVE_LOCKS_REQUIRED(!newTaskMutex)
Repeat p until it return false.
Definition: scheduler.cpp:115
RAII-style semaphore lock.
Definition: sync.h:397
bool TryAcquire()
Definition: sync.h:419
void MoveTo(CSemaphoreGrant &grant)
Definition: sync.h:426
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.
Definition: netaddress.cpp:993
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)
Definition: config.h:19
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:795
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)
Definition: netbase.h:67
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
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
uint32_t nHdrPos
Definition: net.h:320
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
CHash256 hasher
Definition: net.h:309
DataStream hdrbuf
Definition: net.h:315
uint256 data_hash
Definition: net.h:310
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
uint8_t * begin()
Definition: uint256.h:85
bool IsNull() const
Definition: uint256.h:32
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:129
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.
Definition: clientversion.h:38
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 LogPrint(category,...)
Definition: logging.h:452
#define LogError(...)
Definition: logging.h:419
#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
Definition: messages.h:12
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:3308
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:3242
GlobalMutex g_maplocalhost_mutex
Definition: net.cpp:130
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(g_maplocalhost_mutex)
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:3276
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:2693
std::string userAgent(const Config &config)
Definition: net.cpp:3256
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:2461
bool IsReachable(enum Network net)
Definition: net.cpp:328
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:338
static constexpr std::chrono::minutes TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:65
static const size_t DEFAULT_MAXINFLIGHTBUFFER
Definition: net.h:110
static const bool DEFAULT_FORCEDNSSEED
Definition: net.h:105
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
static const bool DEFAULT_FIXEDSEEDS
Definition: net.h:107
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
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:732
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:198
bool HaveNameProxy()
Definition: netbase.cpp:837
void InterruptSocks5(bool interrupt)
Definition: netbase.cpp:915
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:224
bool fNameLookup
Definition: netbase.cpp:48
bool GetProxy(enum Network net, Proxy &proxyInfoOut)
Definition: netbase.cpp:809
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:852
std::function< std::unique_ptr< Sock >(int, int, int)> CreateSock
Socket factory.
Definition: netbase.cpp:660
bool GetNameProxy(Proxy &nameProxyOut)
Definition: netbase.cpp:828
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:257
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:919
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:427
ServiceFlags
nServices flags.
Definition: protocol.h:335
@ NODE_NONE
Definition: protocol.h:338
@ NODE_AVALANCHE
Definition: protocol.h:380
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:435
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:438
Cache responses to addr requests to minimize privacy leak.
Definition: net.h:1269
std::chrono::microseconds m_cache_entry_expiration
Definition: net.h:1271
std::vector< CAddress > m_addrs_response_cache
Definition: net.h:1270
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition: net.h:1091
std::shared_ptr< Sock > sock
Definition: net.h:1090
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:861
std::vector< CService > onion_binds
Definition: net.h:863
std::vector< std::string > m_specified_outgoing
Definition: net.h:868
std::vector< CService > vBinds
Definition: net.h:862
bool m_i2p_accept_incoming
Definition: net.h:870
std::vector< std::string > vSeedNodes
Definition: net.h:858
bool m_use_addrman_outgoing
Definition: net.h:867
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
Definition: net.h:866
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
int nScore
Definition: net.h:200
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:317
#define AssertLockNotHeld(cs)
Definition: sync.h:163
#define LOCK(cs)
Definition: sync.h:306
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:357
static int count
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
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...
Definition: tinyformat.h:1202
#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())