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