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