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