Bitcoin ABC 0.33.5
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 //
1433 // Receive
1434 //
1435 bool recvSet = false;
1436 bool sendSet = false;
1437 bool errorSet = false;
1438 {
1439 LOCK(pnode->m_sock_mutex);
1440 if (!pnode->m_sock) {
1441 continue;
1442 }
1443 const auto it = events_per_sock.find(pnode->m_sock);
1444 if (it != events_per_sock.end()) {
1445 recvSet = it->second.occurred & Sock::RECV;
1446 sendSet = it->second.occurred & Sock::SEND;
1447 errorSet = it->second.occurred & Sock::ERR;
1448 }
1449 }
1450
1451 if (sendSet) {
1452 // Send data
1453 auto [bytes_sent, data_left] =
1454 WITH_LOCK(pnode->cs_vSend, return SocketSendData(*pnode));
1455 if (bytes_sent) {
1456 RecordBytesSent(bytes_sent);
1457
1458 // If both receiving and (non-optimistic) sending were possible,
1459 // we first attempt sending. If that succeeds, but does not
1460 // fully drain the send queue, do not attempt to receive. This
1461 // avoids needlessly queueing data if the remote peer is slow at
1462 // receiving data, by means of TCP flow control. We only do this
1463 // when sending actually succeeded to make sure progress is
1464 // always made; otherwise a deadlock would be possible when both
1465 // sides have data to send, but neither is receiving.
1466 if (data_left) {
1467 recvSet = false;
1468 }
1469 }
1470 }
1471
1472 if (recvSet || errorSet) {
1473 // typical socket buffer is 8K-64K
1474 uint8_t pchBuf[0x10000];
1475 int32_t nBytes = 0;
1476 {
1477 LOCK(pnode->m_sock_mutex);
1478 if (!pnode->m_sock) {
1479 continue;
1480 }
1481 nBytes =
1482 pnode->m_sock->Recv(pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
1483 }
1484 if (nBytes > 0) {
1485 bool notify = false;
1486 if (!pnode->ReceiveMsgBytes(*config, {pchBuf, (size_t)nBytes},
1487 notify)) {
1488 pnode->CloseSocketDisconnect();
1489 }
1490 RecordBytesRecv(nBytes);
1491 nTotalInflightBytes += pnode->nInflightBytes;
1492 if (notify) {
1493 pnode->MarkReceivedMsgsForProcessing();
1495 }
1496 } else if (nBytes == 0) {
1497 // socket closed gracefully
1498 if (!pnode->fDisconnect) {
1499 LogPrint(BCLog::NET, "socket closed for peer=%d\n",
1500 pnode->GetId());
1501 }
1502 pnode->CloseSocketDisconnect();
1503 } else if (nBytes < 0) {
1504 // error
1505 int nErr = WSAGetLastError();
1506 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE &&
1507 nErr != WSAEINTR && nErr != WSAEINPROGRESS) {
1508 if (!pnode->fDisconnect) {
1510 "socket recv error for peer=%d: %s\n",
1511 pnode->GetId(), NetworkErrorString(nErr));
1512 }
1513 pnode->CloseSocketDisconnect();
1514 }
1515 }
1516 }
1517
1518 if (InactivityCheck(*pnode)) {
1519 pnode->fDisconnect = true;
1520 }
1521 }
1522
1523 const size_t max_inflight_bytes = DEFAULT_MAXINFLIGHTBUFFER * 1000;
1524
1525 bool prev_inflight_throttle = inflight_throttle;
1526 inflight_throttle = nTotalInflightBytes > max_inflight_bytes;
1527 if (prev_inflight_throttle != inflight_throttle) {
1528 LogPrintf("Inflight throttling %s (%d/%d)\n",
1529 inflight_throttle ? "enabled" : "disabled",
1530 nTotalInflightBytes, max_inflight_bytes);
1531 }
1532}
1533
1535 const Sock::EventsPerSock &events_per_sock) {
1536 for (const ListenSocket &listen_socket : vhListenSocket) {
1537 if (interruptNet) {
1538 return;
1539 }
1540 const auto it = events_per_sock.find(listen_socket.sock);
1541 if (it != events_per_sock.end() && it->second.occurred & Sock::RECV) {
1542 AcceptConnection(listen_socket);
1543 }
1544 }
1545}
1546
1548 while (!interruptNet) {
1551 SocketHandler();
1552 }
1553}
1554
1556 {
1558 fMsgProcWake = true;
1559 }
1560 condMsgProc.notify_one();
1561}
1562
1565 std::vector<std::string> seeds =
1567 // Number of seeds left before testing if we have enough connections
1568 int seeds_right_now = 0;
1569 int found = 0;
1570
1571 if (gArgs.GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED)) {
1572 // When -forcednsseed is provided, query all.
1573 seeds_right_now = seeds.size();
1574 } else if (addrman.size() == 0) {
1575 // If we have no known peers, query all.
1576 // This will occur on the first run, or if peers.dat has been
1577 // deleted.
1578 seeds_right_now = seeds.size();
1579 }
1580
1581 // goal: only query DNS seed if address need is acute
1582 // * If we have a reasonable number of peers in addrman, spend
1583 // some time trying them first. This improves user privacy by
1584 // creating fewer identifying DNS requests, reduces trust by
1585 // giving seeds less influence on the network topology, and
1586 // reduces traffic to the seeds.
1587 // * When querying DNS seeds query a few at once, this ensures
1588 // that we don't give DNS seeds the ability to eclipse nodes
1589 // that query them.
1590 // * If we continue having problems, eventually query all the
1591 // DNS seeds, and if that fails too, also try the fixed seeds.
1592 // (done in ThreadOpenConnections)
1593 const std::chrono::seconds seeds_wait_time =
1597
1598 for (const std::string &seed : seeds) {
1599 if (seeds_right_now == 0) {
1600 seeds_right_now += DNSSEEDS_TO_QUERY_AT_ONCE;
1601
1602 if (addrman.size() > 0) {
1603 LogPrintf("Waiting %d seconds before querying DNS seeds.\n",
1604 seeds_wait_time.count());
1605 std::chrono::seconds to_wait = seeds_wait_time;
1606 while (to_wait.count() > 0) {
1607 // if sleeping for the MANY_PEERS interval, wake up
1608 // early to see if we have enough peers and can stop
1609 // this thread entirely freeing up its resources
1610 std::chrono::seconds w =
1611 std::min(DNSSEEDS_DELAY_FEW_PEERS, to_wait);
1612 if (!interruptNet.sleep_for(w)) {
1613 return;
1614 }
1615 to_wait -= w;
1616
1617 int nRelevant = 0;
1618 {
1620 for (const CNode *pnode : m_nodes) {
1621 if (pnode->fSuccessfullyConnected &&
1622 pnode->IsFullOutboundConn()) {
1623 ++nRelevant;
1624 }
1625 }
1626 }
1627 if (nRelevant >= 2) {
1628 if (found > 0) {
1629 LogPrintf("%d addresses found from DNS seeds\n",
1630 found);
1631 LogPrintf(
1632 "P2P peers available. Finished DNS seeding.\n");
1633 } else {
1634 LogPrintf(
1635 "P2P peers available. Skipped DNS seeding.\n");
1636 }
1637 return;
1638 }
1639 }
1640 }
1641 }
1642
1643 if (interruptNet) {
1644 return;
1645 }
1646
1647 // hold off on querying seeds if P2P network deactivated
1648 if (!fNetworkActive) {
1649 LogPrintf("Waiting for network to be reactivated before querying "
1650 "DNS seeds.\n");
1651 do {
1652 if (!interruptNet.sleep_for(std::chrono::seconds{1})) {
1653 return;
1654 }
1655 } while (!fNetworkActive);
1656 }
1657
1658 LogPrintf("Loading addresses from DNS seed %s\n", seed);
1659 if (HaveNameProxy()) {
1660 AddAddrFetch(seed);
1661 } else {
1662 std::vector<CAddress> vAdd;
1663 ServiceFlags requiredServiceBits =
1665 std::string host = strprintf("x%x.%s", requiredServiceBits, seed);
1666 CNetAddr resolveSource;
1667 if (!resolveSource.SetInternal(host)) {
1668 continue;
1669 }
1670
1671 // Limits number of IPs learned from a DNS seed
1672 unsigned int nMaxIPs = 256;
1673 const auto addresses{LookupHost(host, nMaxIPs, true)};
1674 if (!addresses.empty()) {
1675 for (const CNetAddr &ip : addresses) {
1676 CAddress addr = CAddress(
1678 requiredServiceBits);
1679 // Use a random age between 3 and 7 days old.
1680 addr.nTime = rng.rand_uniform_delay(
1681 Now<NodeSeconds>() - 3 * 24h, -4 * 24h);
1682 vAdd.push_back(addr);
1683 found++;
1684 }
1685 addrman.Add(vAdd, resolveSource);
1686 } else {
1687 // We now avoid directly using results from DNS Seeds which do
1688 // not support service bit filtering, instead using them as a
1689 // addrfetch to get nodes with our desired service bits.
1690 AddAddrFetch(seed);
1691 }
1692 }
1693 --seeds_right_now;
1694 }
1695 LogPrintf("%d addresses found from DNS seeds\n", found);
1696}
1697
1699 int64_t nStart = GetTimeMillis();
1700
1702
1703 LogPrint(BCLog::NET, "Flushed %d addresses to peers.dat %dms\n",
1704 addrman.size(), GetTimeMillis() - nStart);
1705}
1706
1709 std::string strDest;
1710 {
1712 if (m_addr_fetches.empty()) {
1713 return;
1714 }
1715 strDest = m_addr_fetches.front();
1716 m_addr_fetches.pop_front();
1717 }
1718 CAddress addr;
1719 CSemaphoreGrant grant(*semOutbound, true);
1720 if (grant) {
1721 OpenNetworkConnection(addr, false, &grant, strDest.c_str(),
1723 }
1724}
1725
1728}
1729
1732 LogPrint(BCLog::NET, "net: setting try another outbound peer=%s\n",
1733 flag ? "true" : "false");
1734}
1735
1736// Return the number of peers we have over our outbound connection limit.
1737// Exclude peers that are marked for disconnect, or are going to be disconnected
1738// soon (eg ADDR_FETCH and FEELER).
1739// Also exclude peers that haven't finished initial connection handshake yet (so
1740// that we don't decide we're over our desired connection limit, and then evict
1741// some peer that has finished the handshake).
1743 int full_outbound_peers = 0;
1744 {
1746 for (const CNode *pnode : m_nodes) {
1747 if (pnode->fSuccessfullyConnected && !pnode->fDisconnect &&
1748 pnode->IsFullOutboundConn()) {
1749 ++full_outbound_peers;
1750 }
1751 }
1752 }
1753 return std::max(full_outbound_peers - m_max_outbound_full_relay -
1755 0);
1756}
1757
1759 int block_relay_peers = 0;
1760 {
1762 for (const CNode *pnode : m_nodes) {
1763 if (pnode->fSuccessfullyConnected && !pnode->fDisconnect &&
1764 pnode->IsBlockOnlyConn()) {
1765 ++block_relay_peers;
1766 }
1767 }
1768 }
1769 return std::max(block_relay_peers - m_max_outbound_block_relay, 0);
1770}
1771
1773 const std::vector<std::string> connect,
1774 std::function<void(const CAddress &, ConnectionType)> mockOpenConnection) {
1777 // Connect to specific addresses
1778 if (!connect.empty()) {
1779 for (int64_t nLoop = 0;; nLoop++) {
1781 for (const std::string &strAddr : connect) {
1782 CAddress addr(CService(), NODE_NONE);
1783 OpenNetworkConnection(addr, false, nullptr, strAddr.c_str(),
1785 for (int i = 0; i < 10 && i < nLoop; i++) {
1787 std::chrono::milliseconds(500))) {
1788 return;
1789 }
1790 }
1791 }
1792 if (!interruptNet.sleep_for(std::chrono::milliseconds(500))) {
1793 return;
1794 }
1795 }
1796 }
1797
1798 // Initiate network connections
1799 auto start = GetTime<std::chrono::microseconds>();
1800
1801 // Minimum time before next feeler connection (in microseconds
1802 auto next_feeler = start + rng.rand_exp_duration(FEELER_INTERVAL);
1803 auto next_extra_block_relay =
1805 const bool dnsseed = gArgs.GetBoolArg("-dnsseed", DEFAULT_DNSSEED);
1806 bool add_fixed_seeds = gArgs.GetBoolArg("-fixedseeds", DEFAULT_FIXEDSEEDS);
1807 const bool use_seednodes{gArgs.IsArgSet("-seednode")};
1808
1809 if (!add_fixed_seeds) {
1810 LogPrintf("Fixed seeds are disabled\n");
1811 }
1812
1813 while (!interruptNet) {
1815
1816 // No need to sleep the thread if we are mocking the network connection
1817 if (!mockOpenConnection &&
1818 !interruptNet.sleep_for(std::chrono::milliseconds(500))) {
1819 return;
1820 }
1821
1823 if (interruptNet) {
1824 return;
1825 }
1826
1827 if (add_fixed_seeds && addrman.size() == 0) {
1828 // When the node starts with an empty peers.dat, there are a few
1829 // other sources of peers before we fallback on to fixed seeds:
1830 // -dnsseed, -seednode, -addnode If none of those are available, we
1831 // fallback on to fixed seeds immediately, else we allow 60 seconds
1832 // for any of those sources to populate addrman.
1833 bool add_fixed_seeds_now = false;
1834 // It is cheapest to check if enough time has passed first.
1835 if (GetTime<std::chrono::seconds>() >
1836 start + std::chrono::minutes{1}) {
1837 add_fixed_seeds_now = true;
1838 LogPrintf("Adding fixed seeds as 60 seconds have passed and "
1839 "addrman is empty\n");
1840 } else if (!dnsseed && !use_seednodes) {
1841 // Lock the mutex after performing the above cheap checks.
1843 if (m_added_nodes.empty()) {
1844 add_fixed_seeds_now = true;
1845 LogPrintf("Adding fixed seeds as -dnsseed=0 and neither "
1846 "-addnode nor -seednode are provided\n");
1847 }
1848 }
1849
1850 if (add_fixed_seeds_now) {
1851 CNetAddr local;
1852 local.SetInternal("fixedseeds");
1854 local);
1855 add_fixed_seeds = false;
1856 }
1857 }
1858
1859 //
1860 // Choose an address to connect to based on most recently seen
1861 //
1862 CAddress addrConnect;
1863
1864 // Only connect out to one peer per network group (/16 for IPv4).
1865 int nOutboundFullRelay = 0;
1866 int nOutboundBlockRelay = 0;
1867 int nOutboundAvalanche = 0;
1868 std::set<std::vector<uint8_t>> setConnected;
1869
1870 {
1872 for (const CNode *pnode : m_nodes) {
1873 if (pnode->IsAvalancheOutboundConnection()) {
1874 nOutboundAvalanche++;
1875 } else if (pnode->IsFullOutboundConn()) {
1876 nOutboundFullRelay++;
1877 } else if (pnode->IsBlockOnlyConn()) {
1878 nOutboundBlockRelay++;
1879 }
1880
1881 // Netgroups for inbound and manual peers are not excluded
1882 // because our goal here is to not use multiple of our
1883 // limited outbound slots on a single netgroup but inbound
1884 // and manual peers do not use our outbound slots. Inbound
1885 // peers also have the added issue that they could be attacker
1886 // controlled and could be used to prevent us from connecting
1887 // to particular hosts if we used them here.
1888 switch (pnode->m_conn_type) {
1891 break;
1897 setConnected.insert(
1898 pnode->addr.GetGroup(addrman.GetAsmap()));
1899 } // no default case, so the compiler can warn about missing
1900 // cases
1901 }
1902 }
1903
1905 auto now = GetTime<std::chrono::microseconds>();
1906 bool anchor = false;
1907 bool fFeeler = false;
1908
1909 // Determine what type of connection to open. Opening
1910 // BLOCK_RELAY connections to addresses from anchors.dat gets the
1911 // highest priority. Then we open AVALANCHE_OUTBOUND connection until we
1912 // hit our avalanche outbound peer limit, which is 0 if avalanche is not
1913 // enabled. We fallback after 50 retries to OUTBOUND_FULL_RELAY if the
1914 // peer is not avalanche capable until we meet our full-relay capacity.
1915 // Then we open BLOCK_RELAY connection until we hit our block-relay-only
1916 // peer limit.
1917 // GetTryNewOutboundPeer() gets set when a stale tip is detected, so we
1918 // try opening an additional OUTBOUND_FULL_RELAY connection. If none of
1919 // these conditions are met, check to see if it's time to try an extra
1920 // block-relay-only peer (to confirm our tip is current, see below) or
1921 // the next_feeler timer to decide if we should open a FEELER.
1922
1923 if (!m_anchors.empty() &&
1924 (nOutboundBlockRelay < m_max_outbound_block_relay)) {
1925 conn_type = ConnectionType::BLOCK_RELAY;
1926 anchor = true;
1927 } else if (nOutboundAvalanche < m_max_avalanche_outbound) {
1929 } else if (nOutboundFullRelay < m_max_outbound_full_relay) {
1930 // OUTBOUND_FULL_RELAY
1931 } else if (nOutboundBlockRelay < m_max_outbound_block_relay) {
1932 conn_type = ConnectionType::BLOCK_RELAY;
1933 } else if (GetTryNewOutboundPeer()) {
1934 // OUTBOUND_FULL_RELAY
1935 } else if (now > next_extra_block_relay &&
1937 // Periodically connect to a peer (using regular outbound selection
1938 // methodology from addrman) and stay connected long enough to sync
1939 // headers, but not much else.
1940 //
1941 // Then disconnect the peer, if we haven't learned anything new.
1942 //
1943 // The idea is to make eclipse attacks very difficult to pull off,
1944 // because every few minutes we're finding a new peer to learn
1945 // headers from.
1946 //
1947 // This is similar to the logic for trying extra outbound
1948 // (full-relay) peers, except:
1949 // - we do this all the time on an exponential timer, rather than
1950 // just when our tip is stale
1951 // - we potentially disconnect our next-youngest block-relay-only
1952 // peer, if our newest block-relay-only peer delivers a block more
1953 // recently.
1954 // See the eviction logic in net_processing.cpp.
1955 //
1956 // Because we can promote these connections to block-relay-only
1957 // connections, they do not get their own ConnectionType enum
1958 // (similar to how we deal with extra outbound peers).
1959 next_extra_block_relay =
1960 now +
1962 conn_type = ConnectionType::BLOCK_RELAY;
1963 } else if (now > next_feeler) {
1964 next_feeler = now + rng.rand_exp_duration(FEELER_INTERVAL);
1965 conn_type = ConnectionType::FEELER;
1966 fFeeler = true;
1967 } else {
1968 // skip to next iteration of while loop
1969 continue;
1970 }
1971
1973
1974 const auto current_time{NodeClock::now()};
1975 int nTries = 0;
1976 while (!interruptNet) {
1977 if (anchor && !m_anchors.empty()) {
1978 const CAddress addr = m_anchors.back();
1979 m_anchors.pop_back();
1980 if (!addr.IsValid() || IsLocal(addr) || !IsReachable(addr) ||
1982 setConnected.count(addr.GetGroup(addrman.GetAsmap()))) {
1983 continue;
1984 }
1985 addrConnect = addr;
1987 "Trying to make an anchor connection to %s\n",
1988 addrConnect.ToStringAddrPort());
1989 break;
1990 }
1991 // If we didn't find an appropriate destination after trying 100
1992 // addresses fetched from addrman, stop this loop, and let the outer
1993 // loop run again (which sleeps, adds seed nodes, recalculates
1994 // already-connected network ranges, ...) before trying new addrman
1995 // addresses.
1996 nTries++;
1997 if (nTries > 100) {
1998 break;
1999 }
2000
2001 CAddress addr;
2002 NodeSeconds addr_last_try{0s};
2003
2004 if (fFeeler) {
2005 // First, try to get a tried table collision address. This
2006 // returns an empty (invalid) address if there are no collisions
2007 // to try.
2008 std::tie(addr, addr_last_try) = addrman.SelectTriedCollision();
2009
2010 if (!addr.IsValid()) {
2011 // No tried table collisions. Select a new table address
2012 // for our feeler.
2013 std::tie(addr, addr_last_try) = addrman.Select(true);
2014 } else if (AlreadyConnectedToAddress(addr)) {
2015 // If test-before-evict logic would have us connect to a
2016 // peer that we're already connected to, just mark that
2017 // address as Good(). We won't be able to initiate the
2018 // connection anyway, so this avoids inadvertently evicting
2019 // a currently-connected peer.
2020 addrman.Good(addr);
2021 // Select a new table address for our feeler instead.
2022 std::tie(addr, addr_last_try) = addrman.Select(true);
2023 }
2024 } else {
2025 // Not a feeler
2026 std::tie(addr, addr_last_try) = addrman.Select();
2027 }
2028
2029 // Require outbound connections, other than feelers and avalanche,
2030 // to be to distinct network groups
2031 if (!fFeeler && conn_type != ConnectionType::AVALANCHE_OUTBOUND &&
2032 setConnected.count(addr.GetGroup(addrman.GetAsmap()))) {
2033 break;
2034 }
2035
2036 // if we selected an invalid or local address, restart
2037 if (!addr.IsValid() || IsLocal(addr)) {
2038 break;
2039 }
2040
2041 if (!IsReachable(addr)) {
2042 continue;
2043 }
2044
2045 // only consider very recently tried nodes after 30 failed attempts
2046 if (current_time - addr_last_try < 10min && nTries < 30) {
2047 continue;
2048 }
2049
2050 // for non-feelers, require all the services we'll want,
2051 // for feelers, only require they be a full node (only because most
2052 // SPV clients don't have a good address DB available)
2053 if (!fFeeler && !HasAllDesirableServiceFlags(addr.nServices)) {
2054 continue;
2055 }
2056
2057 if (fFeeler && !MayHaveUsefulAddressDB(addr.nServices)) {
2058 continue;
2059 }
2060
2061 // Do not connect to bad ports, unless 50 invalid addresses have
2062 // been selected already.
2063 if (nTries < 50 && (addr.IsIPv4() || addr.IsIPv6()) &&
2064 IsBadPort(addr.GetPort())) {
2065 continue;
2066 }
2067
2068 // For avalanche peers, check they have the avalanche service bit
2069 // set.
2070 if (conn_type == ConnectionType::AVALANCHE_OUTBOUND &&
2071 !(addr.nServices & NODE_AVALANCHE)) {
2072 // If this peer is not suitable as an avalanche one and we tried
2073 // over 20 addresses already, see if we can fallback to a non
2074 // avalanche full outbound.
2075 if (nTries < 20 ||
2076 nOutboundFullRelay >= m_max_outbound_full_relay ||
2077 setConnected.count(addr.GetGroup(addrman.GetAsmap()))) {
2078 // Fallback is not desirable or possible, try another one
2079 continue;
2080 }
2081
2082 // Fallback is possible, update the connection type accordingly
2084 }
2085
2086 addrConnect = addr;
2087 break;
2088 }
2089
2090 if (addrConnect.IsValid()) {
2091 if (fFeeler) {
2092 // Add small amount of random noise before connection to avoid
2093 // synchronization.
2097 return;
2098 }
2099 LogPrint(BCLog::NET, "Making feeler connection to %s\n",
2100 addrConnect.ToStringAddrPort());
2101 }
2102
2103 // This mock is for testing purpose only. It prevents the thread
2104 // from attempting the connection which is useful for testing.
2105 if (mockOpenConnection) {
2106 mockOpenConnection(addrConnect, conn_type);
2107 } else {
2108 OpenNetworkConnection(addrConnect,
2109 int(setConnected.size()) >=
2110 std::min(nMaxConnections - 1, 2),
2111 &grant, nullptr, conn_type);
2112 }
2113 }
2114 }
2115}
2116
2117std::vector<CAddress> CConnman::GetCurrentBlockRelayOnlyConns() const {
2118 std::vector<CAddress> ret;
2120 for (const CNode *pnode : m_nodes) {
2121 if (pnode->IsBlockOnlyConn()) {
2122 ret.push_back(pnode->addr);
2123 }
2124 }
2125
2126 return ret;
2127}
2128
2129std::vector<AddedNodeInfo> CConnman::GetAddedNodeInfo() const {
2130 std::vector<AddedNodeInfo> ret;
2131
2132 std::list<std::string> lAddresses(0);
2133 {
2135 ret.reserve(m_added_nodes.size());
2136 std::copy(m_added_nodes.cbegin(), m_added_nodes.cend(),
2137 std::back_inserter(lAddresses));
2138 }
2139
2140 // Build a map of all already connected addresses (by IP:port and by name)
2141 // to inbound/outbound and resolved CService
2142 std::map<CService, bool> mapConnected;
2143 std::map<std::string, std::pair<bool, CService>> mapConnectedByName;
2144 {
2146 for (const CNode *pnode : m_nodes) {
2147 if (pnode->addr.IsValid()) {
2148 mapConnected[pnode->addr] = pnode->IsInboundConn();
2149 }
2150 std::string addrName{pnode->m_addr_name};
2151 if (!addrName.empty()) {
2152 mapConnectedByName[std::move(addrName)] =
2153 std::make_pair(pnode->IsInboundConn(),
2154 static_cast<const CService &>(pnode->addr));
2155 }
2156 }
2157 }
2158
2159 for (const std::string &strAddNode : lAddresses) {
2160 CService service(
2161 LookupNumeric(strAddNode, Params().GetDefaultPort(strAddNode)));
2162 AddedNodeInfo addedNode{strAddNode, CService(), false, false};
2163 if (service.IsValid()) {
2164 // strAddNode is an IP:port
2165 auto it = mapConnected.find(service);
2166 if (it != mapConnected.end()) {
2167 addedNode.resolvedAddress = service;
2168 addedNode.fConnected = true;
2169 addedNode.fInbound = it->second;
2170 }
2171 } else {
2172 // strAddNode is a name
2173 auto it = mapConnectedByName.find(strAddNode);
2174 if (it != mapConnectedByName.end()) {
2175 addedNode.resolvedAddress = it->second.second;
2176 addedNode.fConnected = true;
2177 addedNode.fInbound = it->second.first;
2178 }
2179 }
2180 ret.emplace_back(std::move(addedNode));
2181 }
2182
2183 return ret;
2184}
2185
2188 while (true) {
2190 std::vector<AddedNodeInfo> vInfo = GetAddedNodeInfo();
2191 bool tried = false;
2192 for (const AddedNodeInfo &info : vInfo) {
2193 if (!info.fConnected) {
2194 if (!grant.TryAcquire()) {
2195 // If we've used up our semaphore and need a new one, let's
2196 // not wait here since while we are waiting the
2197 // addednodeinfo state might change.
2198 break;
2199 }
2200 tried = true;
2201 CAddress addr(CService(), NODE_NONE);
2202 OpenNetworkConnection(addr, false, &grant,
2203 info.strAddedNode.c_str(),
2205 if (!interruptNet.sleep_for(std::chrono::milliseconds(500))) {
2206 return;
2207 }
2208 }
2209 }
2210 // Retry every 60 seconds if a connection was attempted, otherwise two
2211 // seconds.
2212 if (!interruptNet.sleep_for(std::chrono::seconds(tried ? 60 : 2))) {
2213 return;
2214 }
2215 }
2216}
2217
2218// If successful, this moves the passed grant to the constructed node.
2220 bool fCountFailure,
2221 CSemaphoreGrant *grantOutbound,
2222 const char *pszDest,
2223 ConnectionType conn_type) {
2225 assert(conn_type != ConnectionType::INBOUND);
2226
2227 //
2228 // Initiate outbound network connection
2229 //
2230 if (interruptNet) {
2231 return;
2232 }
2233 if (!fNetworkActive) {
2234 return;
2235 }
2236 if (!pszDest) {
2237 bool banned_or_discouraged =
2238 m_banman && (m_banman->IsDiscouraged(addrConnect) ||
2239 m_banman->IsBanned(addrConnect));
2240 if (IsLocal(addrConnect) || banned_or_discouraged ||
2241 AlreadyConnectedToAddress(addrConnect)) {
2242 return;
2243 }
2244 } else if (FindNode(std::string(pszDest))) {
2245 return;
2246 }
2247
2248 CNode *pnode = ConnectNode(addrConnect, pszDest, fCountFailure, conn_type);
2249
2250 if (!pnode) {
2251 return;
2252 }
2253 if (grantOutbound) {
2254 grantOutbound->MoveTo(pnode->grantOutbound);
2255 }
2256
2257 for (auto interface : m_msgproc) {
2258 interface->InitializeNode(*config, *pnode, nLocalServices);
2259 }
2260
2261 {
2263 m_nodes.push_back(pnode);
2264 }
2265}
2266
2268
2271
2272 while (!flagInterruptMsgProc) {
2273 bool fMoreWork = false;
2274
2275 {
2276 // Randomize the order in which we process messages from/to our
2277 // peers. This prevents attacks in which an attacker exploits having
2278 // multiple consecutive connections in the vNodes list.
2279 const NodesSnapshot snap{*this, /*shuffle=*/true};
2280
2281 for (CNode *pnode : snap.Nodes()) {
2282 if (pnode->fDisconnect) {
2283 continue;
2284 }
2285
2286 bool fMoreNodeWork = false;
2287 // Receive messages
2288 for (auto interface : m_msgproc) {
2289 fMoreNodeWork |= interface->ProcessMessages(
2290 *config, pnode, flagInterruptMsgProc);
2291 }
2292 fMoreWork |= (fMoreNodeWork && !pnode->fPauseSend);
2294 return;
2295 }
2296
2297 // Send messages
2298 for (auto interface : m_msgproc) {
2299 interface->SendMessages(*config, pnode);
2300 }
2301
2303 return;
2304 }
2305 }
2306 }
2307
2308 WAIT_LOCK(mutexMsgProc, lock);
2309 if (!fMoreWork) {
2310 condMsgProc.wait_until(lock,
2311 std::chrono::steady_clock::now() +
2312 std::chrono::milliseconds(100),
2313 [this]() EXCLUSIVE_LOCKS_REQUIRED(
2314 mutexMsgProc) { return fMsgProcWake; });
2315 }
2316 fMsgProcWake = false;
2317 }
2318}
2319
2321 static constexpr auto err_wait_begin = 1s;
2322 static constexpr auto err_wait_cap = 5min;
2323 auto err_wait = err_wait_begin;
2324
2325 bool advertising_listen_addr = false;
2326 i2p::Connection conn;
2327
2328 while (!interruptNet) {
2329 if (!m_i2p_sam_session->Listen(conn)) {
2330 if (advertising_listen_addr && conn.me.IsValid()) {
2331 RemoveLocal(conn.me);
2332 advertising_listen_addr = false;
2333 }
2334
2335 interruptNet.sleep_for(err_wait);
2336 if (err_wait < err_wait_cap) {
2337 err_wait *= 2;
2338 }
2339
2340 continue;
2341 }
2342
2343 if (!advertising_listen_addr) {
2344 AddLocal(conn.me, LOCAL_MANUAL);
2345 advertising_listen_addr = true;
2346 }
2347
2348 if (!m_i2p_sam_session->Accept(conn)) {
2349 continue;
2350 }
2351
2353 std::move(conn.sock), NetPermissionFlags::None,
2354 CAddress{conn.me, NODE_NONE}, CAddress{conn.peer, NODE_NONE});
2355 }
2356}
2357
2358bool CConnman::BindListenPort(const CService &addrBind, bilingual_str &strError,
2359 NetPermissionFlags permissions) {
2360 int nOne = 1;
2361
2362 // Create socket for listening for incoming connections
2363 struct sockaddr_storage sockaddr;
2364 socklen_t len = sizeof(sockaddr);
2365 if (!addrBind.GetSockAddr((struct sockaddr *)&sockaddr, &len)) {
2366 strError =
2367 strprintf(Untranslated("Bind address family for %s not supported"),
2368 addrBind.ToStringAddrPort());
2370 strError.original);
2371 return false;
2372 }
2373
2374 std::unique_ptr<Sock> sock =
2375 CreateSock(addrBind.GetSAFamily(), SOCK_STREAM, IPPROTO_TCP);
2376 if (!sock) {
2377 strError =
2378 strprintf(Untranslated("Couldn't open socket for incoming "
2379 "connections (socket returned error %s)"),
2382 strError.original);
2383 return false;
2384 }
2385
2386 // Allow binding if the port is still in TIME_WAIT state after
2387 // the program was closed and restarted.
2388 if (sock->SetSockOpt(SOL_SOCKET, SO_REUSEADDR, (sockopt_arg_type)&nOne,
2389 sizeof(int)) == SOCKET_ERROR) {
2390 strError = strprintf(
2392 "Error setting SO_REUSEADDR on socket: %s, continuing anyway"),
2394 LogPrintf("%s\n", strError.original);
2395 }
2396
2397 // Some systems don't have IPV6_V6ONLY but are always v6only; others do have
2398 // the option and enable it by default or not. Try to enable it, if
2399 // possible.
2400 if (addrBind.IsIPv6()) {
2401#ifdef IPV6_V6ONLY
2402 if (sock->SetSockOpt(IPPROTO_IPV6, IPV6_V6ONLY, (sockopt_arg_type)&nOne,
2403 sizeof(int)) == SOCKET_ERROR) {
2404 strError = strprintf(Untranslated("Error setting IPV6_V6ONLY on "
2405 "socket: %s, continuing anyway"),
2407 LogPrintf("%s\n", strError.original);
2408 }
2409#endif
2410#ifdef WIN32
2411 int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED;
2412 if (sock->SetSockOpt(IPPROTO_IPV6, IPV6_PROTECTION_LEVEL,
2413 (sockopt_arg_type)&nProtLevel,
2414 sizeof(int)) == SOCKET_ERROR) {
2415 strError =
2416 strprintf(Untranslated("Error setting IPV6_PROTECTION_LEVEL on "
2417 "socket: %s, continuing anyway"),
2419 LogPrintf("%s\n", strError.original);
2420 }
2421#endif
2422 }
2423
2424 if (sock->Bind(reinterpret_cast<struct sockaddr *>(&sockaddr), len) ==
2425 SOCKET_ERROR) {
2426 int nErr = WSAGetLastError();
2427 if (nErr == WSAEADDRINUSE) {
2428 strError = strprintf(_("Unable to bind to %s on this computer. %s "
2429 "is probably already running."),
2430 addrBind.ToStringAddrPort(), PACKAGE_NAME);
2431 } else {
2432 strError = strprintf(_("Unable to bind to %s on this computer "
2433 "(bind returned error %s)"),
2434 addrBind.ToStringAddrPort(),
2435 NetworkErrorString(nErr));
2436 }
2437
2439 strError.original);
2440 return false;
2441 }
2442 LogPrintf("Bound to %s\n", addrBind.ToStringAddrPort());
2443
2444 // Listen for incoming connections
2445 if (sock->Listen(SOMAXCONN) == SOCKET_ERROR) {
2446 strError = strprintf(_("Listening for incoming connections "
2447 "failed (listen returned error %s)"),
2450 strError.original);
2451 return false;
2452 }
2453
2454 vhListenSocket.emplace_back(std::move(sock), permissions);
2455 return true;
2456}
2457
2458void Discover() {
2459 if (!fDiscover) {
2460 return;
2461 }
2462
2463 for (const CNetAddr &addr : GetLocalAddresses()) {
2464 if (AddLocal(addr, LOCAL_IF)) {
2465 LogPrintf("%s: %s\n", __func__, addr.ToStringAddr());
2466 }
2467 }
2468}
2469
2471 LogPrintf("%s: %s\n", __func__, active);
2472
2473 if (fNetworkActive == active) {
2474 return;
2475 }
2476
2477 fNetworkActive = active;
2478
2479 if (m_client_interface) {
2480 m_client_interface->NotifyNetworkActiveChanged(fNetworkActive);
2481 }
2482}
2483
2484CConnman::CConnman(const Config &configIn, uint64_t nSeed0In, uint64_t nSeed1In,
2485 AddrMan &addrmanIn, bool network_active)
2486 : config(&configIn), addrman(addrmanIn), nSeed0(nSeed0In),
2487 nSeed1(nSeed1In) {
2488 SetTryNewOutboundPeer(false);
2489
2490 Options connOptions;
2491 Init(connOptions);
2492 SetNetworkActive(network_active);
2493}
2494
2496 return nLastNodeId.fetch_add(1);
2497}
2498
2499bool CConnman::Bind(const CService &addr, unsigned int flags,
2500 NetPermissionFlags permissions) {
2501 if (!(flags & BF_EXPLICIT) && !IsReachable(addr)) {
2502 return false;
2503 }
2504 bilingual_str strError;
2505 if (!BindListenPort(addr, strError, permissions)) {
2507 m_client_interface->ThreadSafeMessageBox(
2508 strError, "", CClientUIInterface::MSG_ERROR);
2509 }
2510 return false;
2511 }
2512
2513 if (addr.IsRoutable() && fDiscover && !(flags & BF_DONT_ADVERTISE) &&
2515 AddLocal(addr, LOCAL_BIND);
2516 }
2517
2518 return true;
2519}
2520
2521bool CConnman::InitBinds(const Options &options) {
2522 for (const auto &addrBind : options.vBinds) {
2523 if (!Bind(addrBind, BF_EXPLICIT | BF_REPORT_ERROR,
2525 return false;
2526 }
2527 }
2528 for (const auto &addrBind : options.vWhiteBinds) {
2529 if (!Bind(addrBind.m_service, BF_EXPLICIT | BF_REPORT_ERROR,
2530 addrBind.m_flags)) {
2531 return false;
2532 }
2533 }
2534 for (const auto &addr_bind : options.onion_binds) {
2537 return false;
2538 }
2539 }
2540 if (options.bind_on_any) {
2541 // Don't consider errors to bind on IPv6 "::" fatal because the host OS
2542 // may not have IPv6 support and the user did not explicitly ask us to
2543 // bind on that.
2544 const CService ipv6_any{in6_addr(IN6ADDR_ANY_INIT),
2545 GetListenPort()}; // ::
2547
2548 struct in_addr inaddr_any;
2549 inaddr_any.s_addr = htonl(INADDR_ANY);
2550 const CService ipv4_any{inaddr_any, GetListenPort()}; // 0.0.0.0
2552 return false;
2553 }
2554 }
2555 return true;
2556}
2557
2558bool CConnman::Start(CScheduler &scheduler, const Options &connOptions) {
2559 Init(connOptions);
2560
2561 if (fListen && !InitBinds(connOptions)) {
2562 if (m_client_interface) {
2563 m_client_interface->ThreadSafeMessageBox(
2564 _("Failed to listen on any port. Use -listen=0 if you want "
2565 "this."),
2567 }
2568 return false;
2569 }
2570
2571 Proxy i2p_sam;
2572 if (GetProxy(NET_I2P, i2p_sam) && connOptions.m_i2p_accept_incoming) {
2573 m_i2p_sam_session = std::make_unique<i2p::sam::Session>(
2574 gArgs.GetDataDirNet() / "i2p_private_key", i2p_sam, &interruptNet);
2575 }
2576
2577 for (const auto &strDest : connOptions.vSeedNodes) {
2578 AddAddrFetch(strDest);
2579 }
2580
2582 // Load addresses from anchors.dat
2583 m_anchors =
2588 }
2589 LogPrintf(
2590 "%i block-relay-only anchors will be tried for connections.\n",
2591 m_anchors.size());
2592 }
2593
2594 if (m_client_interface) {
2595 m_client_interface->InitMessage(
2596 _("Starting network threads...").translated);
2597 }
2598
2599 fAddressesInitialized = true;
2600
2601 if (semOutbound == nullptr) {
2602 // initialize semaphore
2603 semOutbound = std::make_unique<CSemaphore>(
2604 std::min(m_max_outbound, nMaxConnections));
2605 }
2606 if (semAddnode == nullptr) {
2607 // initialize semaphore
2608 semAddnode = std::make_unique<CSemaphore>(nMaxAddnode);
2609 }
2610
2611 //
2612 // Start threads
2613 //
2614 assert(m_msgproc.size() > 0);
2615 InterruptSocks5(false);
2617 flagInterruptMsgProc = false;
2618
2619 {
2621 fMsgProcWake = false;
2622 }
2623
2624 // Send and receive from sockets, accept connections
2625 threadSocketHandler = std::thread(&util::TraceThread, "net",
2626 [this] { ThreadSocketHandler(); });
2627
2628 if (!gArgs.GetBoolArg("-dnsseed", DEFAULT_DNSSEED)) {
2629 LogPrintf("DNS seeding disabled\n");
2630 } else {
2631 threadDNSAddressSeed = std::thread(&util::TraceThread, "dnsseed",
2632 [this] { ThreadDNSAddressSeed(); });
2633 }
2634
2635 // Initiate manual connections
2636 threadOpenAddedConnections = std::thread(
2637 &util::TraceThread, "addcon", [this] { ThreadOpenAddedConnections(); });
2638
2639 if (connOptions.m_use_addrman_outgoing &&
2640 !connOptions.m_specified_outgoing.empty()) {
2641 if (m_client_interface) {
2642 m_client_interface->ThreadSafeMessageBox(
2643 _("Cannot provide specific connections and have addrman find "
2644 "outgoing connections at the same."),
2646 }
2647 return false;
2648 }
2649 if (connOptions.m_use_addrman_outgoing ||
2650 !connOptions.m_specified_outgoing.empty()) {
2652 std::thread(&util::TraceThread, "opencon",
2653 [this, connect = connOptions.m_specified_outgoing] {
2654 ThreadOpenConnections(connect, nullptr);
2655 });
2656 }
2657
2658 // Process messages
2659 threadMessageHandler = std::thread(&util::TraceThread, "msghand",
2660 [this] { ThreadMessageHandler(); });
2661
2662 if (m_i2p_sam_session) {
2664 std::thread(&util::TraceThread, "i2paccept",
2665 [this] { ThreadI2PAcceptIncoming(); });
2666 }
2667
2668 // Dump network addresses
2669 scheduler.scheduleEvery(
2670 [this]() {
2671 this->DumpAddresses();
2672 return true;
2673 },
2675
2676 return true;
2677}
2678
2680public:
2681 CNetCleanup() = default;
2682
2684#ifdef WIN32
2685 // Shutdown Windows Sockets
2686 WSACleanup();
2687#endif
2688 }
2689};
2691
2693 {
2695 flagInterruptMsgProc = true;
2696 }
2697 condMsgProc.notify_all();
2698
2699 interruptNet();
2700 InterruptSocks5(true);
2701
2702 if (semOutbound) {
2703 for (int i = 0; i < m_max_outbound; i++) {
2704 semOutbound->post();
2705 }
2706 }
2707
2708 if (semAddnode) {
2709 for (int i = 0; i < nMaxAddnode; i++) {
2710 semAddnode->post();
2711 }
2712 }
2713}
2714
2716 if (threadI2PAcceptIncoming.joinable()) {
2718 }
2719 if (threadMessageHandler.joinable()) {
2720 threadMessageHandler.join();
2721 }
2722 if (threadOpenConnections.joinable()) {
2723 threadOpenConnections.join();
2724 }
2725 if (threadOpenAddedConnections.joinable()) {
2727 }
2728 if (threadDNSAddressSeed.joinable()) {
2729 threadDNSAddressSeed.join();
2730 }
2731 if (threadSocketHandler.joinable()) {
2732 threadSocketHandler.join();
2733 }
2734}
2735
2738 DumpAddresses();
2739 fAddressesInitialized = false;
2740
2742 // Anchor connections are only dumped during clean shutdown.
2743 std::vector<CAddress> anchors_to_dump =
2745 if (anchors_to_dump.size() > MAX_BLOCK_RELAY_ONLY_ANCHORS) {
2746 anchors_to_dump.resize(MAX_BLOCK_RELAY_ONLY_ANCHORS);
2747 }
2750 anchors_to_dump);
2751 }
2752 }
2753
2754 // Delete peer connections.
2755 std::vector<CNode *> nodes;
2756 WITH_LOCK(m_nodes_mutex, nodes.swap(m_nodes));
2757 for (CNode *pnode : nodes) {
2758 pnode->CloseSocketDisconnect();
2759 DeleteNode(pnode);
2760 }
2761
2762 for (CNode *pnode : m_nodes_disconnected) {
2763 DeleteNode(pnode);
2764 }
2765 m_nodes_disconnected.clear();
2766 vhListenSocket.clear();
2767 semOutbound.reset();
2768 semAddnode.reset();
2769}
2770
2772 assert(pnode);
2773 for (auto interface : m_msgproc) {
2774 interface->FinalizeNode(*config, *pnode);
2775 }
2776 delete pnode;
2777}
2778
2780 Interrupt();
2781 Stop();
2782}
2783
2784std::vector<CAddress>
2785CConnman::GetAddresses(size_t max_addresses, size_t max_pct,
2786 std::optional<Network> network) const {
2787 std::vector<CAddress> addresses =
2788 addrman.GetAddr(max_addresses, max_pct, network);
2789 if (m_banman) {
2790 addresses.erase(std::remove_if(addresses.begin(), addresses.end(),
2791 [this](const CAddress &addr) {
2792 return m_banman->IsDiscouraged(
2793 addr) ||
2794 m_banman->IsBanned(addr);
2795 }),
2796 addresses.end());
2797 }
2798 return addresses;
2799}
2800
2801std::vector<CAddress>
2802CConnman::GetAddresses(CNode &requestor, size_t max_addresses, size_t max_pct) {
2803 auto local_socket_bytes = requestor.addrBind.GetAddrBytes();
2805 .Write(requestor.addr.GetNetwork())
2806 .Write(local_socket_bytes)
2807 .Finalize();
2808 const auto current_time = GetTime<std::chrono::microseconds>();
2809 auto r = m_addr_response_caches.emplace(cache_id, CachedAddrResponse{});
2810 CachedAddrResponse &cache_entry = r.first->second;
2811 // New CachedAddrResponse have expiration 0.
2812 if (cache_entry.m_cache_entry_expiration < current_time) {
2813 cache_entry.m_addrs_response_cache =
2814 GetAddresses(max_addresses, max_pct, /* network */ std::nullopt);
2815 // Choosing a proper cache lifetime is a trade-off between the privacy
2816 // leak minimization and the usefulness of ADDR responses to honest
2817 // users.
2818 //
2819 // Longer cache lifetime makes it more difficult for an attacker to
2820 // scrape enough AddrMan data to maliciously infer something useful. By
2821 // the time an attacker scraped enough AddrMan records, most of the
2822 // records should be old enough to not leak topology info by e.g.
2823 // analyzing real-time changes in timestamps.
2824 //
2825 // It takes only several hundred requests to scrape everything from an
2826 // AddrMan containing 100,000 nodes, so ~24 hours of cache lifetime
2827 // indeed makes the data less inferable by the time most of it could be
2828 // scraped (considering that timestamps are updated via ADDR
2829 // self-announcements and when nodes communicate). We also should be
2830 // robust to those attacks which may not require scraping *full*
2831 // victim's AddrMan (because even several timestamps of the same handful
2832 // of nodes may leak privacy).
2833 //
2834 // On the other hand, longer cache lifetime makes ADDR responses
2835 // outdated and less useful for an honest requestor, e.g. if most nodes
2836 // in the ADDR response are no longer active.
2837 //
2838 // However, the churn in the network is known to be rather low. Since we
2839 // consider nodes to be "terrible" (see IsTerrible()) if the timestamps
2840 // are older than 30 days, max. 24 hours of "penalty" due to cache
2841 // shouldn't make any meaningful difference in terms of the freshness of
2842 // the response.
2843 cache_entry.m_cache_entry_expiration =
2844 current_time + 21h +
2845 FastRandomContext().randrange<std::chrono::microseconds>(6h);
2846 }
2847 return cache_entry.m_addrs_response_cache;
2848}
2849
2850bool CConnman::AddNode(const std::string &strNode) {
2852 for (const std::string &it : m_added_nodes) {
2853 if (strNode == it) {
2854 return false;
2855 }
2856 }
2857
2858 m_added_nodes.push_back(strNode);
2859 return true;
2860}
2861
2862bool CConnman::RemoveAddedNode(const std::string &strNode) {
2864 for (std::vector<std::string>::iterator it = m_added_nodes.begin();
2865 it != m_added_nodes.end(); ++it) {
2866 if (strNode == *it) {
2867 m_added_nodes.erase(it);
2868 return true;
2869 }
2870 }
2871 return false;
2872}
2873
2876 // Shortcut if we want total
2878 return m_nodes.size();
2879 }
2880
2881 int nNum = 0;
2882 for (const auto &pnode : m_nodes) {
2883 if (flags & (pnode->IsInboundConn() ? ConnectionDirection::In
2885 nNum++;
2886 }
2887 }
2888
2889 return nNum;
2890}
2891
2892void CConnman::GetNodeStats(std::vector<CNodeStats> &vstats) const {
2893 vstats.clear();
2895 vstats.reserve(m_nodes.size());
2896 for (CNode *pnode : m_nodes) {
2897 vstats.emplace_back();
2898 pnode->copyStats(vstats.back());
2899 vstats.back().m_mapped_as = pnode->addr.GetMappedAS(addrman.GetAsmap());
2900 }
2901}
2902
2905
2906 for (auto &&pnode : m_nodes) {
2907 if (pnode->GetId() == id) {
2908 pnode->copyStats(stats);
2909 stats.m_mapped_as = pnode->addr.GetMappedAS(addrman.GetAsmap());
2910 return true;
2911 }
2912 }
2913
2914 return false;
2915}
2916
2917bool CConnman::DisconnectNode(const std::string &strNode) {
2919 if (CNode *pnode = FindNode(strNode)) {
2921 "disconnect by address%s matched peer=%d; disconnecting\n",
2922 (fLogIPs ? strprintf("=%s", strNode) : ""), pnode->GetId());
2923 pnode->fDisconnect = true;
2924 return true;
2925 }
2926 return false;
2927}
2928
2930 bool disconnected = false;
2932 for (CNode *pnode : m_nodes) {
2933 if (subnet.Match(pnode->addr)) {
2935 "disconnect by subnet%s matched peer=%d; disconnecting\n",
2936 (fLogIPs ? strprintf("=%s", subnet.ToString()) : ""),
2937 pnode->GetId());
2938 pnode->fDisconnect = true;
2939 disconnected = true;
2940 }
2941 }
2942 return disconnected;
2943}
2944
2946 return DisconnectNode(CSubNet(addr));
2947}
2948
2951 for (CNode *pnode : m_nodes) {
2952 if (id == pnode->GetId()) {
2953 LogPrint(BCLog::NET, "disconnect by id peer=%d; disconnecting\n",
2954 pnode->GetId());
2955 pnode->fDisconnect = true;
2956 return true;
2957 }
2958 }
2959 return false;
2960}
2961
2962void CConnman::RecordBytesRecv(uint64_t bytes) {
2963 nTotalBytesRecv += bytes;
2964}
2965
2966void CConnman::RecordBytesSent(uint64_t bytes) {
2968 nTotalBytesSent += bytes;
2969
2970 const auto now = GetTime<std::chrono::seconds>();
2971 if (nMaxOutboundCycleStartTime + MAX_UPLOAD_TIMEFRAME < now) {
2972 // timeframe expired, reset cycle
2973 nMaxOutboundCycleStartTime = now;
2974 nMaxOutboundTotalBytesSentInCycle = 0;
2975 }
2976
2977 // TODO, exclude peers with download permission
2978 nMaxOutboundTotalBytesSentInCycle += bytes;
2979}
2980
2983 return nMaxOutboundLimit;
2984}
2985
2986std::chrono::seconds CConnman::GetMaxOutboundTimeframe() const {
2987 return MAX_UPLOAD_TIMEFRAME;
2988}
2989
2990std::chrono::seconds CConnman::GetMaxOutboundTimeLeftInCycle() const {
2992 if (nMaxOutboundLimit == 0) {
2993 return 0s;
2994 }
2995
2996 if (nMaxOutboundCycleStartTime.count() == 0) {
2997 return MAX_UPLOAD_TIMEFRAME;
2998 }
2999
3000 const std::chrono::seconds cycleEndTime =
3001 nMaxOutboundCycleStartTime + MAX_UPLOAD_TIMEFRAME;
3002 const auto now = GetTime<std::chrono::seconds>();
3003 return (cycleEndTime < now) ? 0s : cycleEndTime - now;
3004}
3005
3006bool CConnman::OutboundTargetReached(bool historicalBlockServingLimit) const {
3008 if (nMaxOutboundLimit == 0) {
3009 return false;
3010 }
3011
3012 if (historicalBlockServingLimit) {
3013 // keep a large enough buffer to at least relay each block once.
3014 const std::chrono::seconds timeLeftInCycle =
3016 const uint64_t buffer =
3017 timeLeftInCycle / std::chrono::minutes{10} * ONE_MEGABYTE;
3018 if (buffer >= nMaxOutboundLimit ||
3019 nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit - buffer) {
3020 return true;
3021 }
3022 } else if (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit) {
3023 return true;
3024 }
3025
3026 return false;
3027}
3028
3031 if (nMaxOutboundLimit == 0) {
3032 return 0;
3033 }
3034
3035 return (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit)
3036 ? 0
3037 : nMaxOutboundLimit - nMaxOutboundTotalBytesSentInCycle;
3038}
3039
3041 return nTotalBytesRecv;
3042}
3043
3046 return nTotalBytesSent;
3047}
3048
3050 return nLocalServices;
3051}
3052
3053void CNode::invsPolled(uint32_t count) {
3054 invCounters += count;
3055}
3056
3057void CNode::invsVoted(uint32_t count) {
3058 invCounters += uint64_t(count) << 32;
3059}
3060
3061void CNode::updateAvailabilityScore(double decayFactor) {
3062 if (!m_avalanche_enabled) {
3063 return;
3064 }
3065
3066 uint64_t windowInvCounters = invCounters.exchange(0);
3067 double previousScore = availabilityScore;
3068
3069 int64_t polls = windowInvCounters & std::numeric_limits<uint32_t>::max();
3070 int64_t votes = windowInvCounters >> 32;
3071
3073 decayFactor * (2 * votes - polls) + (1. - decayFactor) * previousScore;
3074}
3075
3077 // The score is set atomically so there is no need to lock the statistics
3078 // when reading.
3079 return availabilityScore;
3080}
3081
3082CNode::CNode(NodeId idIn, std::shared_ptr<Sock> sock, const CAddress &addrIn,
3083 uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn,
3084 uint64_t nLocalExtraEntropyIn, const CAddress &addrBindIn,
3085 const std::string &addrNameIn, ConnectionType conn_type_in,
3086 bool inbound_onion, CNodeOptions &&node_opts)
3087 : m_deserializer{std::make_unique<V1TransportDeserializer>(
3089 m_serializer{
3091 m_permission_flags{node_opts.permission_flags}, m_sock{sock},
3092 m_connected(GetTime<std::chrono::seconds>()), addr{addrIn},
3093 addrBind{addrBindIn},
3094 m_addr_name{addrNameIn.empty() ? addr.ToStringAddrPort() : addrNameIn},
3095 m_inbound_onion{inbound_onion}, m_prefer_evict{node_opts.prefer_evict},
3096 nKeyedNetGroup{nKeyedNetGroupIn}, m_conn_type{conn_type_in}, id{idIn},
3097 nLocalHostNonce{nLocalHostNonceIn},
3098 nLocalExtraEntropy{nLocalExtraEntropyIn},
3099 m_recv_flood_size{node_opts.recv_flood_size},
3100 m_i2p_sam_session{std::move(node_opts.i2p_sam_session)} {
3101 if (inbound_onion) {
3102 assert(conn_type_in == ConnectionType::INBOUND);
3103 }
3104
3105 for (const std::string &msg : getAllNetMessageTypes()) {
3106 mapRecvBytesPerMsgType[msg] = 0;
3107 }
3108 mapRecvBytesPerMsgType[NET_MESSAGE_TYPE_OTHER] = 0;
3109
3110 if (fLogIPs) {
3111 LogPrint(BCLog::NET, "Added connection to %s peer=%d\n", m_addr_name,
3112 id);
3113 } else {
3114 LogPrint(BCLog::NET, "Added connection peer=%d\n", id);
3115 }
3116}
3117
3120
3121 size_t nSizeAdded = 0;
3122 for (const auto &msg : vRecvMsg) {
3123 // vRecvMsg contains only completed CNetMessage
3124 // the single possible partially deserialized message are held by
3125 // TransportDeserializer
3126 nSizeAdded += msg.m_raw_message_size;
3127 }
3128
3130 m_msg_process_queue.splice(m_msg_process_queue.end(), vRecvMsg);
3131 m_msg_process_queue_size += nSizeAdded;
3132 pauseRecv(m_msg_process_queue_size > m_recv_flood_size);
3133}
3134
3135std::optional<std::pair<CNetMessage, bool>> CNode::PollMessage() {
3137 if (m_msg_process_queue.empty()) {
3138 return std::nullopt;
3139 }
3140
3141 std::list<CNetMessage> msgs;
3142 // Just take one message
3143 msgs.splice(msgs.begin(), m_msg_process_queue, m_msg_process_queue.begin());
3144 m_msg_process_queue_size -= msgs.front().m_raw_message_size;
3145 pauseRecv(m_msg_process_queue_size > m_recv_flood_size);
3146
3147 return std::make_pair(std::move(msgs.front()),
3148 !m_msg_process_queue.empty());
3149}
3150
3152 return pnode && pnode->fSuccessfullyConnected && !pnode->fDisconnect;
3153}
3154
3156 size_t nMessageSize = msg.data.size();
3157 LogPrint(BCLog::NETDEBUG, "sending %s (%d bytes) peer=%d\n", msg.m_type,
3158 nMessageSize, pnode->GetId());
3159 if (gArgs.GetBoolArg("-capturemessages", false)) {
3160 CaptureMessage(pnode->addr, msg.m_type, msg.data,
3161 /*is_incoming=*/false);
3162 }
3163
3164 TRACE6(net, outbound_message, pnode->GetId(), pnode->m_addr_name.c_str(),
3165 pnode->ConnectionTypeAsString().c_str(), msg.m_type.c_str(),
3166 msg.data.size(), msg.data.data());
3167
3168 // make sure we use the appropriate network transport format
3169 std::vector<uint8_t> serializedHeader;
3170 pnode->m_serializer->prepareForTransport(*config, msg, serializedHeader);
3171 size_t nTotalSize = nMessageSize + serializedHeader.size();
3172
3173 size_t nBytesSent = 0;
3174 {
3175 LOCK(pnode->cs_vSend);
3176 bool optimisticSend(pnode->vSendMsg.empty());
3177
3178 // log total amount of bytes per message type
3179 pnode->AccountForSentBytes(msg.m_type, nTotalSize);
3180 pnode->nSendSize += nTotalSize;
3181
3182 if (pnode->nSendSize > nSendBufferMaxSize) {
3183 pnode->fPauseSend = true;
3184 }
3185 pnode->vSendMsg.push_back(std::move(serializedHeader));
3186 if (nMessageSize) {
3187 pnode->vSendMsg.push_back(std::move(msg.data));
3188 }
3189
3190 // If write queue empty, attempt "optimistic write"
3191 bool data_left;
3192 if (optimisticSend) {
3193 std::tie(nBytesSent, data_left) = SocketSendData(*pnode);
3194 }
3195 }
3196 if (nBytesSent) {
3197 RecordBytesSent(nBytesSent);
3198 }
3199}
3200
3201bool CConnman::ForNode(NodeId id, std::function<bool(CNode *pnode)> func) {
3202 CNode *found = nullptr;
3204 for (auto &&pnode : m_nodes) {
3205 if (pnode->GetId() == id) {
3206 found = pnode;
3207 break;
3208 }
3209 }
3210 return found != nullptr && NodeFullyConnected(found) && func(found);
3211}
3212
3214 return CSipHasher(nSeed0, nSeed1).Write(id);
3215}
3216
3218 std::vector<uint8_t> vchNetGroup(ad.GetGroup(addrman.GetAsmap()));
3219
3221 .Write(vchNetGroup)
3222 .Finalize();
3223}
3224
3239std::string getSubVersionEB(uint64_t MaxBlockSize) {
3240 // Prepare EB string we are going to add to SubVer:
3241 // 1) translate from byte to MB and convert to string
3242 // 2) limit the EB string to the first decimal digit (floored)
3243 std::stringstream ebMBs;
3244 ebMBs << (MaxBlockSize / (ONE_MEGABYTE / 10));
3245 std::string eb = ebMBs.str();
3246 eb.insert(eb.size() - 1, ".", 1);
3247 if (eb.substr(0, 1) == ".") {
3248 eb = "0" + eb;
3249 }
3250 return eb;
3251}
3252
3253std::string userAgent(const Config &config) {
3254 // format excessive blocksize value
3255 std::string eb = getSubVersionEB(config.GetMaxBlockSize());
3256 std::vector<std::string> uacomments;
3257 uacomments.push_back("EB" + eb);
3258
3259 // Comments are checked for char compliance at startup, it is safe to add
3260 // them to the user agent string
3261 for (const std::string &cmt : gArgs.GetArgs("-uacomment")) {
3262 uacomments.push_back(cmt);
3263 }
3264
3265 const std::string client_name = gArgs.GetArg("-uaclientname", CLIENT_NAME);
3266 const std::string client_version =
3267 gArgs.GetArg("-uaclientversion", FormatVersion(CLIENT_VERSION));
3268
3269 // Size compliance is checked at startup, it is safe to not check it again
3270 return FormatUserAgent(client_name, client_version, uacomments);
3271}
3272
3273void CaptureMessageToFile(const CAddress &addr, const std::string &msg_type,
3274 Span<const uint8_t> data, bool is_incoming) {
3275 // Note: This function captures the message at the time of processing,
3276 // not at socket receive/send time.
3277 // This ensures that the messages are always in order from an application
3278 // layer (processing) perspective.
3279 auto now = GetTime<std::chrono::microseconds>();
3280
3281 // Windows folder names can not include a colon
3282 std::string clean_addr = addr.ToStringAddrPort();
3283 std::replace(clean_addr.begin(), clean_addr.end(), ':', '_');
3284
3285 fs::path base_path = gArgs.GetDataDirNet() / "message_capture" / clean_addr;
3286 fs::create_directories(base_path);
3287
3288 fs::path path =
3289 base_path / (is_incoming ? "msgs_recv.dat" : "msgs_sent.dat");
3290 AutoFile f{fsbridge::fopen(path, "ab")};
3291
3292 ser_writedata64(f, now.count());
3293 f << Span{msg_type};
3294 for (auto i = msg_type.length(); i < CMessageHeader::MESSAGE_TYPE_SIZE;
3295 ++i) {
3296 f << uint8_t{'\0'};
3297 }
3298 uint32_t size = data.size();
3299 ser_writedata32(f, size);
3300 f << data;
3301}
3302
3303std::function<void(const CAddress &addr, const std::string &msg_type,
3304 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:2990
bool OutboundTargetReached(bool historicalBlockServingLimit) const
check if the outbound target is reached.
Definition: net.cpp:3006
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:2269
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:3201
void DeleteNode(CNode *pnode)
Definition: net.cpp:2771
bool RemoveAddedNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2862
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:1726
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:1730
std::atomic< bool > flagInterruptMsgProc
Definition: net.h:1344
void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:2692
void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:1563
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:2495
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:2558
std::atomic< NodeId > nLastNodeId
Definition: net.h:1260
void RecordBytesSent(uint64_t bytes)
Definition: net.cpp:2966
int GetExtraBlockRelayCount() const
Definition: net.cpp:1758
void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:1555
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:3029
std::thread threadDNSAddressSeed
Definition: net.h:1361
std::atomic< ServiceFlags > nLocalServices
Services this node offers.
Definition: net.h:1301
void ThreadI2PAcceptIncoming()
Definition: net.cpp:2320
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:2986
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:3049
bool DisconnectNode(const std::string &node)
Definition: net.cpp:2917
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:2521
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:2219
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const
Return vector of current BLOCK_RELAY peers.
Definition: net.cpp:2117
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition: net.cpp:3213
uint64_t GetMaxOutboundTarget() const
Definition: net.cpp:2981
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:1303
void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition: net.cpp:2186
RecursiveMutex cs_totalBytesSent
Definition: net.h:1227
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
Definition: net.cpp:2499
std::thread threadOpenConnections
Definition: net.h:1364
size_t GetNodeCount(ConnectionDirection) const
Definition: net.cpp:2874
void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:1707
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:2892
std::vector< AddedNodeInfo > GetAddedNodeInfo() const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2129
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:1742
uint64_t GetTotalBytesRecv() const
Definition: net.cpp:3040
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:3151
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:2484
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:2785
void SetNetworkActive(bool active)
Definition: net.cpp:2470
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:3217
Mutex mutexMsgProc
Definition: net.h:1343
bool fAddressesInitialized
Definition: net.h:1251
virtual ~CConnman()
Definition: net.cpp:2779
void StopThreads()
Definition: net.cpp:2715
bool AddNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2850
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:2962
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:1547
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:3155
void StopNodes()
Definition: net.cpp:2736
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:1534
void DumpAddresses()
Definition: net.cpp:1698
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:3044
void ThreadOpenConnections(std::vector< std::string > connect, std::function< void(const CAddress &, ConnectionType)> mockOpenConnection) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:1772
void AcceptConnection(const ListenSocket &hListenSocket)
Definition: net.cpp:1037
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
Definition: net.cpp:2358
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:2683
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:3082
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:3118
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:3135
double getAvailabilityScore() const
Definition: net.cpp:3076
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:3061
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:3053
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:3057
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:114
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:3305
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:3239
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:3273
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:2690
std::string userAgent(const Config &config)
Definition: net.cpp:3253
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:2458
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())