Bitcoin Core 32.99.0
P2P Digital Currency
Loading...
Searching...
No Matches
net.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-present 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#include <bitcoin-build-config.h> // IWYU pragma: keep
7
8#include <net.h>
9
10#include <addrdb.h>
11#include <addrman.h>
12#include <banman.h>
13#include <chainparams.h>
14#include <common/args.h>
15#include <common/netif.h>
16#include <compat/compat.h>
17#include <consensus/consensus.h>
18#include <crypto/common.h>
19#include <crypto/hex_base.h>
20#include <i2p.h>
21#include <key.h>
22#include <logging.h>
23#include <memusage.h>
24#include <net_permissions.h>
25#include <netaddress.h>
26#include <netbase.h>
27#include <netgroup.h>
28#include <node/eviction.h>
29#include <node/interface_ui.h>
30#include <prevector.h>
31#include <protocol.h>
32#include <pubkey.h>
33#include <random.h>
34#include <scheduler.h>
35#include <serialize.h>
36#include <span.h>
37#include <tinyformat.h>
38#include <util/btcsignals.h>
39#include <util/fs.h>
40#include <util/overflow.h>
41#include <util/sock.h>
42#include <util/strencodings.h>
43#include <util/thread.h>
44#include <util/threadinterrupt.h>
45#include <util/trace.h>
46#include <util/translation.h>
47#include <util/vector.h>
48
49#include <algorithm>
50#include <array>
51#include <compare>
52#include <cstdint>
53#include <cstring>
54#include <exception>
55#include <functional>
56#include <ios>
57#include <list>
58#include <optional>
59#include <ranges>
60#include <ratio>
61#include <set>
62#include <string_view>
63#include <unordered_map>
64#include <vector>
65
71
73static constexpr size_t MAX_BLOCK_RELAY_ONLY_ANCHORS = 2;
74static_assert (MAX_BLOCK_RELAY_ONLY_ANCHORS <= static_cast<size_t>(MAX_BLOCK_RELAY_ONLY_CONNECTIONS), "MAX_BLOCK_RELAY_ONLY_ANCHORS must not exceed MAX_BLOCK_RELAY_ONLY_CONNECTIONS.");
76const char* const ANCHORS_DATABASE_FILENAME = "anchors.dat";
77
78// How often to dump addresses to peers.dat
79static constexpr std::chrono::minutes DUMP_PEERS_INTERVAL{15};
80
82static constexpr int DNSSEEDS_TO_QUERY_AT_ONCE = 3;
83
85static constexpr int SEED_OUTBOUND_CONNECTION_THRESHOLD = 2;
86
96static constexpr std::chrono::seconds DNSSEEDS_DELAY_FEW_PEERS{11};
97static constexpr std::chrono::minutes DNSSEEDS_DELAY_MANY_PEERS{5};
98static constexpr int DNSSEEDS_DELAY_PEER_THRESHOLD = 1000; // "many" vs "few" peers
99
101static constexpr std::chrono::seconds MAX_UPLOAD_TIMEFRAME{60 * 60 * 24};
102
103// A random time period (0 to 1 seconds) is added to feeler connections to prevent synchronization.
104static constexpr auto FEELER_SLEEP_WINDOW{1s};
105
107static constexpr auto EXTRA_NETWORK_PEER_INTERVAL{5min};
108
112 BF_REPORT_ERROR = (1U << 0),
117 BF_DONT_ADVERTISE = (1U << 1),
118};
119
120// The set of sockets cannot be modified while waiting
121// The sleep time needs to be small to avoid new sockets stalling
123
124const std::string NET_MESSAGE_TYPE_OTHER = "*other*";
125
126static const uint64_t RANDOMIZER_ID_NETGROUP = 0x6c0edd8036ef4036ULL; // SHA256("netgroup")[0:8]
127static const uint64_t RANDOMIZER_ID_LOCALHOSTNONCE = 0xd93e69e2bbfa5735ULL; // SHA256("localhostnonce")[0:8]
128static const uint64_t RANDOMIZER_ID_NETWORKKEY = 0x0e8a2b136c592a7dULL; // SHA256("networkkey")[0:8]
129//
130// Global state variables
131//
132bool fDiscover = true;
133bool fListen = true;
135std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(g_maplocalhost_mutex);
136std::string strSubVersion;
137
139{
140 return sizeof(*this) + memusage::DynamicUsage(m_type) + memusage::DynamicUsage(data);
141}
142
143size_t CNetMessage::GetMemoryUsage() const noexcept
144{
145 return sizeof(*this) + memusage::DynamicUsage(m_type) + m_recv.GetMemoryUsage();
146}
147
148void CConnman::AddAddrFetch(const std::string& strDest)
149{
151 m_addr_fetches.push_back(strDest);
152}
153
155{
156 // If -bind= is provided with ":port" part, use that (first one if multiple are provided).
157 for (const std::string& bind_arg : gArgs.GetArgs("-bind")) {
158 constexpr uint16_t dummy_port = 0;
159
160 const std::optional<CService> bind_addr{Lookup(bind_arg, dummy_port, /*fAllowLookup=*/false)};
161 if (bind_addr.has_value() && bind_addr->GetPort() != dummy_port) return bind_addr->GetPort();
162 }
163
164 // Otherwise, if -whitebind= without NetPermissionFlags::NoBan is provided, use that
165 // (-whitebind= is required to have ":port").
166 for (const std::string& whitebind_arg : gArgs.GetArgs("-whitebind")) {
168 bilingual_str error;
171 return whitebind.m_service.GetPort();
172 }
173 }
174 }
175
176 // Otherwise, if -port= is provided, use that. Otherwise use the default port.
177 return static_cast<uint16_t>(gArgs.GetIntArg("-port", Params().GetDefaultPort()));
178}
179
180// Determine the "best" local address for a particular peer.
181[[nodiscard]] static std::optional<CService> GetLocal(const CNode& peer)
182{
183 if (!fListen) return std::nullopt;
184
185 std::optional<CService> addr;
186 int nBestScore = -1;
187 int nBestReachability = -1;
188 {
190 for (const auto& [local_addr, local_service_info] : mapLocalHost) {
191 // For privacy reasons, don't advertise our privacy-network address
192 // to other networks and don't advertise our other-network address
193 // to privacy networks.
194 if (local_addr.GetNetwork() != peer.ConnectedThroughNetwork()
195 && (local_addr.IsPrivacyNet() || peer.IsConnectedThroughPrivacyNet())) {
196 continue;
197 }
198 const int nScore{local_service_info.nScore};
199 const int nReachability{local_addr.GetReachabilityFrom(peer.addr)};
201 addr.emplace(CService{local_addr, local_service_info.nPort});
203 nBestScore = nScore;
204 }
205 }
206 }
207 return addr;
208}
209
211static std::vector<CAddress> ConvertSeeds(const std::vector<uint8_t> &vSeedsIn)
212{
213 // It'll only connect to one or two seed nodes because once it connects,
214 // it'll get a pile of addresses with newer timestamps.
215 // Seed nodes are given a random 'last seen time' of between one and two
216 // weeks ago.
217 const auto one_week{7 * 24h};
218 std::vector<CAddress> vSeedsOut;
221 while (!s.empty()) {
223 s >> endpoint;
226 LogDebug(BCLog::NET, "Added hardcoded seed: %s\n", addr.ToStringAddrPort());
227 vSeedsOut.push_back(addr);
228 }
229 return vSeedsOut;
230}
231
232// Determine the "best" local address for a particular peer.
233// If none, return the unroutable 0.0.0.0 but filled in with
234// the normal parameters, since the IP may be changed to a useful
235// one by discovery.
237{
238 return GetLocal(peer).value_or(CService{CNetAddr(), GetListenPort()});
239}
240
241static int GetnScore(const CService& addr)
242{
244 const auto it = mapLocalHost.find(addr);
245 return (it != mapLocalHost.end()) ? it->second.nScore : 0;
246}
247
248// Is our peer's addrLocal potentially useful as an external IP source?
250{
251 CService addrLocal = pnode->GetAddrLocal();
252 // Tor/I2P peers can't see our clearnet address and the Tor/I2P address won't fit in addrMe (addrv1). so ignore it.
253 return fDiscover && !pnode->IsConnectedThroughPrivacyNet() &&
254 pnode->addr.IsRoutable() && addrLocal.IsRoutable() &&
255 g_reachable_nets.Contains(addrLocal);
256}
257
258std::optional<CService> GetLocalAddrForPeer(CNode& node)
259{
260 CService addrLocal{GetLocalAddress(node)};
261 // If discovery is enabled, sometimes give our peer the address it
262 // tells us that it sees us as in case it has a better idea of our
263 // address than we do.
265 if (IsPeerAddrLocalGood(&node) && (!addrLocal.IsRoutable() ||
266 rng.randbits((GetnScore(addrLocal) > LOCAL_MANUAL) ? 3 : 1) == 0))
267 {
268 if (node.IsInboundConn()) {
269 // For inbound connections, assume both the address and the port
270 // as seen from the peer.
271 addrLocal = CService{node.GetAddrLocal()};
272 } else {
273 // For outbound connections, assume just the address as seen from
274 // the peer and leave the port in `addrLocal` as returned by
275 // `GetLocalAddress()` above. The peer has no way to observe our
276 // listening port when we have initiated the connection.
277 addrLocal.SetIP(node.GetAddrLocal());
278 }
279 }
280 if (addrLocal.IsRoutable()) {
281 LogDebug(BCLog::NET, "Advertising address %s to peer=%d\n", addrLocal.ToStringAddrPort(), node.GetId());
282 return addrLocal;
283 }
284 // Address is unroutable. Don't advertise.
285 return std::nullopt;
286}
287
289{
291 return mapLocalHost.clear();
292}
293
294// learn a new local address
295bool AddLocal(const CService& addr_, int nScore, bool add_even_if_unreachable)
296{
298
299 if (!addr.IsRoutable())
300 return false;
301
302 if (!fDiscover && nScore < LOCAL_MANUAL)
303 return false;
304
306 return false;
307
308 if (fLogIPs) {
309 LogInfo("AddLocal(%s,%i)\n", addr.ToStringAddrPort(), nScore);
310 }
311
312 {
314 const auto [it, is_newly_added] = mapLocalHost.emplace(addr, LocalServiceInfo());
315 LocalServiceInfo &info = it->second;
316 if (is_newly_added || nScore >= info.nScore) {
317 info.nScore = SaturatingAdd(nScore, is_newly_added ? 0 : 1);
318 info.nPort = addr.GetPort();
319 }
320 }
321
322 return true;
323}
324
325bool AddLocal(const CNetAddr& addr, int nScore, bool add_even_if_unreachable)
326{
327 return AddLocal(CService(addr, GetListenPort()), nScore, add_even_if_unreachable);
328}
329
330void RemoveLocal(const CService& addr)
331{
333 if (fLogIPs) {
334 LogInfo("RemoveLocal(%s)\n", addr.ToStringAddrPort());
335 }
336
337 mapLocalHost.erase(addr);
338}
339
341bool SeenLocal(const CService& addr)
342{
344 const auto it = mapLocalHost.find(addr);
345 if (it == mapLocalHost.end()) return false;
346 it->second.nScore = SaturatingAdd(it->second.nScore, 1);
347 return true;
348}
349
350
352bool IsLocal(const CService& addr)
353{
355 return mapLocalHost.contains(addr);
356}
357
358bool CConnman::AlreadyConnectedToHost(std::string_view host) const
359{
361 return std::ranges::any_of(m_nodes, [&host](CNode* node) { return node->m_addr_name == host; });
362}
363
365{
367 return std::ranges::any_of(m_nodes, [&addr_port](CNode* node) { return node->addr == addr_port; });
368}
369
371{
373 return std::ranges::any_of(m_nodes, [&addr](CNode* node) { return node->addr == addr; });
374}
375
377{
379 for (const CNode* pnode : m_nodes) {
380 // Omit private broadcast connections from this check to prevent this privacy attack:
381 // - We connect to a peer in an attempt to privately broadcast a transaction. From our
382 // VERSION message the peer deducts that this is a short-lived connection for
383 // broadcasting a transaction, takes our nonce and delays their VERACK.
384 // - The peer starts connecting to (clearnet) nodes and sends them a VERSION message
385 // which contains our nonce. If the peer manages to connect to us we would disconnect.
386 // - Upon a disconnect, the peer knows our clearnet address. They go back to the short
387 // lived privacy broadcast connection and continue with VERACK.
388 if (!pnode->fSuccessfullyConnected && !pnode->IsInboundConn() && !pnode->IsPrivateBroadcastConn() &&
389 pnode->GetLocalNonce() == nonce)
390 return false;
391 }
392 return true;
393}
394
396 const char* pszDest,
397 bool fCountFailure,
398 ConnectionType conn_type,
399 bool use_v2transport,
400 const std::optional<Proxy>& proxy_override)
401{
404 assert(conn_type != ConnectionType::INBOUND);
405
406 if (pszDest == nullptr) {
407 if (IsLocal(addrConnect))
408 return nullptr;
409
410 // Look for an existing connection
412 LogInfo("Failed to open new connection to %s, already connected", addrConnect.ToStringAddrPort());
413 return nullptr;
414 }
415 }
416
417 LogDebug(BCLog::NET, "trying %s connection (%s) to %s, lastseen=%.1fhrs\n",
418 use_v2transport ? "v2" : "v1",
419 ConnectionTypeAsString(conn_type),
420 pszDest ? pszDest : addrConnect.ToStringAddrPort(),
422
423 // Resolve
426
427 // Collection of addresses to try to connect to: either all dns resolved addresses if a domain name (pszDest) is provided, or addrConnect otherwise.
428 std::vector<CAddress> connect_to{};
429 if (pszDest) {
430 std::vector<CService> resolved{Lookup(pszDest, default_port, fNameLookup && !HaveNameProxy(), 256)};
431 if (!resolved.empty()) {
432 std::shuffle(resolved.begin(), resolved.end(), FastRandomContext());
433 // If the connection is made by name, it can be the case that the name resolves to more than one address.
434 // We don't want to connect any more of them if we are already connected to one
435 for (const auto& r : resolved) {
437 if (!addrConnect.IsValid()) {
438 LogDebug(BCLog::NET, "Resolver returned invalid address %s for %s\n", addrConnect.ToStringAddrPort(), pszDest);
439 return nullptr;
440 }
441 // It is possible that we already have a connection to the IP/port pszDest resolved to.
442 // In that case, drop the connection that was just created.
444 LogInfo("Not opening a connection to %s, already connected to %s\n", pszDest, addrConnect.ToStringAddrPort());
445 return nullptr;
446 }
447 // Add the address to the resolved addresses vector so we can try to connect to it later on
448 connect_to.push_back(addrConnect);
449 }
450 } else {
451 // For resolution via proxy
452 connect_to.push_back(addrConnect);
453 }
454 } else {
455 // Connect via addrConnect directly
456 connect_to.push_back(addrConnect);
457 }
458
459 // Connect
460 std::unique_ptr<Sock> sock;
462 assert(!addr_bind.IsValid());
463 std::unique_ptr<i2p::sam::Session> i2p_transient_session;
464
465 for (auto& target_addr : connect_to) {
466 if (target_addr.IsValid()) {
467 const std::optional<Proxy> use_proxy{
468 proxy_override.has_value() ? proxy_override : GetProxy(target_addr.GetNetwork()),
469 };
470 bool proxyConnectionFailed = false;
471
472 if (target_addr.IsI2P() && use_proxy) {
474 bool connected{false};
475
476 // If an I2P SAM session already exists, normally we would re-use it. But in the case of
477 // private broadcast we force a new transient session. A Connect() using m_i2p_sam_session
478 // would use our permanent I2P address as a source address.
481 } else {
482 {
484 if (m_unused_i2p_sessions.empty()) {
486 std::make_unique<i2p::sam::Session>(*use_proxy, m_interrupt_net);
487 } else {
490 }
491 }
493 if (!connected) {
497 }
498 }
499 }
500
501 if (connected) {
502 sock = std::move(conn.sock);
503 addr_bind = conn.me;
504 }
505 } else if (use_proxy) {
506 LogDebug(BCLog::PROXY, "Using proxy: %s to connect to %s\n", use_proxy->ToString(), target_addr.ToStringAddrPort());
508 } else {
509 // No proxy needed (none set for target network). Private broadcast connections
510 // must always use a proxy, otherwise they would leak the originator's IP address.
511 if (Assume(conn_type != ConnectionType::PRIVATE_BROADCAST)) {
513 }
514 }
516 // If a connection to the node was attempted, and failure (if any) is not caused by a problem connecting to
517 // the proxy, mark this as an attempt.
518 addrman.get().Attempt(target_addr, fCountFailure);
519 }
520 } else if (pszDest) {
521 if (const auto name_proxy = GetNameProxy()) {
522 std::string host;
524 SplitHostPort(pszDest, port, host);
527 }
528 }
529 // Check any other resolved address (if any) if we fail to connect
530 if (!sock) {
531 continue;
532 }
533
535 std::vector<NetWhitelistPermissions> whitelist_permissions = conn_type == ConnectionType::MANUAL ? vWhitelistedRangeOutgoing : std::vector<NetWhitelistPermissions>{};
537
538 // Add node
539 NodeId id = GetNewNodeId();
541 if (!addr_bind.IsValid()) {
542 addr_bind = GetBindAddress(*sock);
543 }
545 .Write(target_addr.GetNetClass())
546 .Write(addr_bind.GetAddrBytes())
547 // For outbound connections, the port of the bound address is randomly
548 // assigned by the OS and would therefore not be useful for seeding.
549 .Write(0)
550 .Finalize();
551 CNode* pnode = new CNode(id,
552 std::move(sock),
555 nonce,
556 addr_bind,
557 pszDest ? pszDest : "",
558 conn_type,
559 /*inbound_onion=*/false,
562 .permission_flags = permission_flags,
563 .proxy_override = proxy_override,
564 .i2p_sam_session = std::move(i2p_transient_session),
565 .recv_flood_size = nReceiveFloodSize,
566 .use_v2transport = use_v2transport,
567 });
568 pnode->AddRef();
569
570 // We're making a new connection, harvest entropy from the time (and our peer count)
572
573 return pnode;
574 }
575
576 return nullptr;
577}
578
580{
581 fDisconnect = true;
583 if (m_sock) {
584 LogDebug(BCLog::NET, "Resetting socket for %s", LogPeer());
585 m_sock.reset();
586
588 GetId(),
589 m_addr_name.c_str(),
593 }
594 m_i2p_sam_session.reset();
595}
596
597void CConnman::AddWhitelistPermissionFlags(NetPermissionFlags& flags, std::optional<CNetAddr> addr, const std::vector<NetWhitelistPermissions>& ranges) const {
598 for (const auto& subnet : ranges) {
599 if (addr.has_value() && subnet.m_subnet.Match(addr.value())) {
600 NetPermissions::AddFlag(flags, subnet.m_flags);
601 }
602 }
609 }
610}
611
618
622 if (Assume(!m_addr_local.IsValid())) { // Addr local can only be set once during version msg processing
624 }
625}
626
631
636
637#undef X
638#define X(name) stats.name = name
640{
641 stats.nodeid = this->GetId();
642 X(addr);
643 X(addrBind);
645 X(m_last_send);
646 X(m_last_recv);
649 X(m_connected);
650 X(m_addr_name);
651 X(nVersion);
652 {
654 X(cleanSubVer);
655 }
656 stats.fInbound = IsInboundConn();
659 {
660 LOCK(cs_vSend);
661 X(mapSendBytesPerMsgType);
662 X(nSendBytes);
663 }
664 {
665 LOCK(cs_vRecv);
666 X(mapRecvBytesPerMsgType);
667 X(nRecvBytes);
668 Transport::Info info = m_transport->GetInfo();
669 stats.m_transport_type = info.transport_type;
670 if (info.session_id) stats.m_session_id = HexStr(*info.session_id);
671 }
673
676
677 // Leave string empty if addrLocal invalid (not filled in yet)
679 stats.addrLocal = addrLocalUnlocked.IsValid() ? addrLocalUnlocked.ToStringAddrPort() : "";
680
681 X(m_conn_type);
682}
683#undef X
684
685bool CNode::ReceiveMsgBytes(std::span<const uint8_t> msg_bytes, bool& complete)
686{
687 complete = false;
688 const auto time{NodeClock::now()};
689 LOCK(cs_vRecv);
690 m_last_recv = time;
691 nRecvBytes += msg_bytes.size();
692 while (msg_bytes.size() > 0) {
693 // absorb network data
694 if (!m_transport->ReceivedBytes(msg_bytes)) {
695 // Serious transport problem, disconnect from the peer.
696 return false;
697 }
698
699 if (m_transport->ReceivedMessageComplete()) {
700 // decompose a transport agnostic CNetMessage from the deserializer
701 bool reject_message{false};
702 CNetMessage msg = m_transport->GetReceivedMessage(time, reject_message);
703 if (reject_message) {
704 // Message deserialization failed. Drop the message but don't disconnect the peer.
705 // store the size of the corrupt message
706 mapRecvBytesPerMsgType.at(NET_MESSAGE_TYPE_OTHER) += msg.m_raw_message_size;
707 continue;
708 }
709
710 // Store received bytes per message type.
711 // To prevent a memory DOS, only allow known message types.
712 auto i = mapRecvBytesPerMsgType.find(msg.m_type);
713 if (i == mapRecvBytesPerMsgType.end()) {
714 i = mapRecvBytesPerMsgType.find(NET_MESSAGE_TYPE_OTHER);
715 }
716 assert(i != mapRecvBytesPerMsgType.end());
717 i->second += msg.m_raw_message_size;
718
719 // push the message to the process queue,
720 vRecvMsg.push_back(std::move(msg));
721
722 complete = true;
723 }
724 }
725
726 return true;
727}
728
729std::string CNode::LogPeer() const
730{
731 auto peer_info{strprintf("peer=%d", GetId())};
732 if (fLogIPs) {
733 return strprintf("%s, peeraddr=%s", peer_info, addr.ToStringAddrPort());
734 } else {
735 return peer_info;
736 }
737}
738
739std::string CNode::DisconnectMsg() const
740{
741 return strprintf("disconnecting %s", LogPeer());
742}
743
745 : m_magic_bytes{Params().MessageStart()}, m_node_id{node_id}
746{
747 LOCK(m_recv_mutex);
748 Reset();
749}
750
752{
753 return {.transport_type = TransportProtocolType::V1, .session_id = {}};
754}
755
756int V1Transport::readHeader(std::span<const uint8_t> msg_bytes)
757{
759 // copy data to temporary parsing buffer
761 unsigned int nCopy = std::min<unsigned int>(nRemaining, msg_bytes.size());
762
763 memcpy(&hdrbuf[nHdrPos], msg_bytes.data(), nCopy);
764 nHdrPos += nCopy;
765
766 // if header incomplete, exit
768 return nCopy;
769
770 // deserialize to CMessageHeader
771 try {
772 hdrbuf >> hdr;
773 }
774 catch (const std::exception&) {
775 LogDebug(BCLog::NET, "Header error: Unable to deserialize, peer=%d\n", m_node_id);
776 return -1;
777 }
778
779 // Check start string, network magic
780 if (hdr.pchMessageStart != m_magic_bytes) {
781 LogDebug(BCLog::NET, "Header error: Wrong MessageStart %s received, peer=%d\n", HexStr(hdr.pchMessageStart), m_node_id);
782 return -1;
783 }
784
785 // reject messages larger than MAX_SIZE or MAX_PROTOCOL_MESSAGE_LENGTH
786 // NOTE: failing to perform this check previously allowed a malicious peer to make us allocate 32MiB of memory per
787 // connection. See https://bitcoincore.org/en/2024/07/03/disclose_receive_buffer_oom.
788 if (hdr.nMessageSize > MAX_SIZE || hdr.nMessageSize > MAX_PROTOCOL_MESSAGE_LENGTH) {
789 LogDebug(BCLog::NET, "Header error: Size too large (%s, %u bytes), peer=%d\n", SanitizeString(hdr.GetMessageType()), hdr.nMessageSize, m_node_id);
790 return -1;
791 }
792
793 // switch state to reading message data
794 in_data = true;
795
796 return nCopy;
797}
798
799int V1Transport::readData(std::span<const uint8_t> msg_bytes)
800{
802 unsigned int nRemaining = hdr.nMessageSize - nDataPos;
803 unsigned int nCopy = std::min<unsigned int>(nRemaining, msg_bytes.size());
804
805 if (vRecv.size() < nDataPos + nCopy) {
806 // Allocate up to 256 KiB ahead, but never more than the total message size.
807 vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024));
808 }
809
810 hasher.Write(msg_bytes.first(nCopy));
811 memcpy(&vRecv[nDataPos], msg_bytes.data(), nCopy);
812 nDataPos += nCopy;
813
814 return nCopy;
815}
816
818{
821 if (data_hash.IsNull())
822 hasher.Finalize(data_hash);
823 return data_hash;
824}
825
827{
829 // Initialize out parameter
830 reject_message = false;
831 // decompose a single CNetMessage from the TransportDeserializer
833 CNetMessage msg(std::move(vRecv));
834
835 // store message type string, time, and sizes
836 msg.m_type = hdr.GetMessageType();
837 msg.m_time = time;
838 msg.m_message_size = hdr.nMessageSize;
839 msg.m_raw_message_size = hdr.nMessageSize + CMessageHeader::HEADER_SIZE;
840
841 uint256 hash = GetMessageHash();
842
843 // We just received a message off the wire, harvest entropy from the time (and the message checksum)
844 RandAddEvent(ReadLE32(hash.begin()));
845
846 // Check checksum and header message type string
847 if (memcmp(hash.begin(), hdr.pchChecksum, CMessageHeader::CHECKSUM_SIZE) != 0) {
848 LogDebug(BCLog::NET, "Header error: Wrong checksum (%s, %u bytes), expected %s was %s, peer=%d\n",
849 SanitizeString(msg.m_type), msg.m_message_size,
850 HexStr(std::span{hash}.first(CMessageHeader::CHECKSUM_SIZE)),
851 HexStr(hdr.pchChecksum),
852 m_node_id);
853 reject_message = true;
854 } else if (!hdr.IsMessageTypeValid()) {
855 LogDebug(BCLog::NET, "Header error: Invalid message type (%s, %u bytes), peer=%d\n",
856 SanitizeString(hdr.GetMessageType()), msg.m_message_size, m_node_id);
857 reject_message = true;
858 }
859
860 // Always reset the network deserializer (prepare for the next message)
861 Reset();
862 return msg;
863}
864
866{
867 AssertLockNotHeld(m_send_mutex);
868 // Determine whether a new message can be set.
869 LOCK(m_send_mutex);
870 if (m_sending_header || m_bytes_sent < m_message_to_send.data.size()) return false;
871
872 // create dbl-sha256 checksum
873 uint256 hash = Hash(msg.data);
874
875 // create header
876 CMessageHeader hdr(m_magic_bytes, msg.m_type.c_str(), msg.data.size());
877 memcpy(hdr.pchChecksum, hash.begin(), CMessageHeader::CHECKSUM_SIZE);
878
879 // serialize header
880 m_header_to_send.clear();
882
883 // update state
884 m_message_to_send = std::move(msg);
885 m_sending_header = true;
886 m_bytes_sent = 0;
887 return true;
888}
889
891{
892 AssertLockNotHeld(m_send_mutex);
893 LOCK(m_send_mutex);
894 if (m_sending_header) {
895 return {std::span{m_header_to_send}.subspan(m_bytes_sent),
896 // We have more to send after the header if the message has payload, or if there
897 // is a next message after that.
898 have_next_message || !m_message_to_send.data.empty(),
899 m_message_to_send.m_type
900 };
901 } else {
902 return {std::span{m_message_to_send.data}.subspan(m_bytes_sent),
903 // We only have more to send after this message's payload if there is another
904 // message.
906 m_message_to_send.m_type
907 };
908 }
909}
910
912{
913 AssertLockNotHeld(m_send_mutex);
914 LOCK(m_send_mutex);
917 // We're done sending a message's header. Switch to sending its data bytes.
918 m_sending_header = false;
919 m_bytes_sent = 0;
920 } else if (!m_sending_header && m_bytes_sent == m_message_to_send.data.size()) {
921 // We're done sending a message's data. Wipe the data vector to reduce memory consumption.
923 m_bytes_sent = 0;
924 }
925}
926
927size_t V1Transport::GetSendMemoryUsage() const noexcept
928{
931 // Don't count sending-side fields besides m_message_to_send, as they're all small and bounded.
932 return m_message_to_send.GetMemoryUsage();
933}
934
935namespace {
936
942const std::array<std::string, BIP324_SHORTIDS_IMPLEMENTED> V2_MESSAGE_IDS = {
943 "", // 12 bytes follow encoding the message type like in V1
972 "", "", "", // Unimplemented message types 29-31
973 "", "", "", "", // Unimplemented message types 32-35
974 "", // Unimplemented message type 36
976};
977
978class V2MessageMap
979{
980 std::unordered_map<std::string, uint8_t> m_map;
981
982public:
983 V2MessageMap() noexcept
984 {
985 for (size_t i = 1; i < std::size(V2_MESSAGE_IDS); ++i) {
986 m_map.emplace(V2_MESSAGE_IDS[i], i);
987 }
988 }
989
990 std::optional<uint8_t> operator()(const std::string& message_name) const noexcept
991 {
992 auto it = m_map.find(message_name);
993 if (it == m_map.end()) return std::nullopt;
994 return it->second;
995 }
996};
997
998const V2MessageMap V2_MESSAGE_MAP;
999
1000std::vector<uint8_t> GenerateRandomGarbage() noexcept
1001{
1002 std::vector<uint8_t> ret;
1006 return ret;
1007}
1008
1009} // namespace
1010
1012{
1013 AssertLockHeld(m_send_mutex);
1015 Assume(m_send_buffer.empty());
1016 // Initialize the send buffer with ellswift pubkey + provided garbage.
1018 std::copy(std::begin(m_cipher.GetOurPubKey()), std::end(m_cipher.GetOurPubKey()), MakeWritableByteSpan(m_send_buffer).begin());
1019 std::copy(m_send_garbage.begin(), m_send_garbage.end(), m_send_buffer.begin() + EllSwiftPubKey::size());
1020 // We cannot wipe m_send_garbage as it will still be used as AAD later in the handshake.
1021}
1022
1023V2Transport::V2Transport(NodeId nodeid, bool initiating, const CKey& key, std::span<const std::byte> ent32, std::vector<uint8_t> garbage) noexcept
1024 : m_cipher{key, ent32},
1025 m_initiating{initiating},
1026 m_nodeid{nodeid},
1027 m_v1_fallback{nodeid},
1028 m_recv_state{initiating ? RecvState::KEY : RecvState::KEY_MAYBE_V1},
1029 m_send_garbage{std::move(garbage)},
1030 m_send_state{initiating ? SendState::AWAITING_KEY : SendState::MAYBE_V1}
1031{
1032 Assume(m_send_garbage.size() <= MAX_GARBAGE_LEN);
1033 // Start sending immediately if we're the initiator of the connection.
1034 if (initiating) {
1035 LOCK(m_send_mutex);
1036 StartSendingHandshake();
1037 }
1038}
1039
1040V2Transport::V2Transport(NodeId nodeid, bool initiating) noexcept
1041 : V2Transport{nodeid, initiating, GenerateRandomKey(),
1043
1045{
1046 AssertLockHeld(m_recv_mutex);
1047 // Enforce allowed state transitions.
1048 switch (m_recv_state) {
1049 case RecvState::KEY_MAYBE_V1:
1050 Assume(recv_state == RecvState::KEY || recv_state == RecvState::V1);
1051 break;
1052 case RecvState::KEY:
1053 Assume(recv_state == RecvState::GARB_GARBTERM);
1054 break;
1055 case RecvState::GARB_GARBTERM:
1056 Assume(recv_state == RecvState::VERSION);
1057 break;
1058 case RecvState::VERSION:
1059 Assume(recv_state == RecvState::APP);
1060 break;
1061 case RecvState::APP:
1062 Assume(recv_state == RecvState::APP_READY);
1063 break;
1064 case RecvState::APP_READY:
1065 Assume(recv_state == RecvState::APP);
1066 break;
1067 case RecvState::V1:
1068 Assume(false); // V1 state cannot be left
1069 break;
1070 }
1071 // Change state.
1073}
1074
1076{
1077 AssertLockHeld(m_send_mutex);
1078 // Enforce allowed state transitions.
1079 switch (m_send_state) {
1080 case SendState::MAYBE_V1:
1081 Assume(send_state == SendState::V1 || send_state == SendState::AWAITING_KEY);
1082 break;
1083 case SendState::AWAITING_KEY:
1084 Assume(send_state == SendState::READY);
1085 break;
1086 case SendState::READY:
1087 case SendState::V1:
1088 Assume(false); // Final states
1089 break;
1090 }
1091 // Change state.
1093}
1094
1096{
1097 AssertLockNotHeld(m_recv_mutex);
1098 LOCK(m_recv_mutex);
1100
1102}
1103
1105{
1106 AssertLockHeld(m_recv_mutex);
1107 AssertLockNotHeld(m_send_mutex);
1109 // We still have to determine if this is a v1 or v2 connection. The bytes being received could
1110 // be the beginning of either a v1 packet (network magic + "version\x00\x00\x00\x00\x00"), or
1111 // of a v2 public key. BIP324 specifies that a mismatch with this 16-byte string should trigger
1112 // sending of the key.
1113 std::array<uint8_t, V1_PREFIX_LEN> v1_prefix = {0, 0, 0, 0, 'v', 'e', 'r', 's', 'i', 'o', 'n', 0, 0, 0, 0, 0};
1114 std::copy(std::begin(Params().MessageStart()), std::end(Params().MessageStart()), v1_prefix.begin());
1115 Assume(m_recv_buffer.size() <= v1_prefix.size());
1116 if (!std::equal(m_recv_buffer.begin(), m_recv_buffer.end(), v1_prefix.begin())) {
1117 // Mismatch with v1 prefix, so we can assume a v2 connection.
1118 SetReceiveState(RecvState::KEY); // Convert to KEY state, leaving received bytes around.
1119 // Transition the sender to AWAITING_KEY state and start sending.
1120 LOCK(m_send_mutex);
1123 } else if (m_recv_buffer.size() == v1_prefix.size()) {
1124 // Full match with the v1 prefix, so fall back to v1 behavior.
1125 LOCK(m_send_mutex);
1126 std::span<const uint8_t> feedback{m_recv_buffer};
1127 // Feed already received bytes to v1 transport. It should always accept these, because it's
1128 // less than the size of a v1 header, and these are the first bytes fed to m_v1_fallback.
1130 Assume(feedback.empty());
1131 Assume(ret);
1134 // Reset v2 transport buffers to save memory.
1135 ClearShrink(m_recv_buffer);
1137 } else {
1138 // We have not received enough to distinguish v1 from v2 yet. Wait until more bytes come.
1139 }
1140}
1141
1143{
1144 AssertLockHeld(m_recv_mutex);
1145 AssertLockNotHeld(m_send_mutex);
1147 Assume(m_recv_buffer.size() <= EllSwiftPubKey::size());
1148
1149 // As a special exception, if bytes 4-16 of the key on a responder connection match the
1150 // corresponding bytes of a V1 version message, but bytes 0-4 don't match the network magic
1151 // (if they did, we'd have switched to V1 state already), assume this is a peer from
1152 // another network, and disconnect them. They will almost certainly disconnect us too when
1153 // they receive our uniformly random key and garbage, but detecting this case specially
1154 // means we can log it.
1155 static constexpr std::array<uint8_t, 12> MATCH = {'v', 'e', 'r', 's', 'i', 'o', 'n', 0, 0, 0, 0, 0};
1156 static constexpr size_t OFFSET = std::tuple_size_v<MessageStartChars>;
1157 if (!m_initiating && m_recv_buffer.size() >= OFFSET + MATCH.size()) {
1158 if (std::equal(MATCH.begin(), MATCH.end(), m_recv_buffer.begin() + OFFSET)) {
1159 LogDebug(BCLog::NET, "V2 transport error: V1 peer with wrong MessageStart %s\n",
1160 HexStr(std::span(m_recv_buffer).first(OFFSET)));
1161 return false;
1162 }
1163 }
1164
1165 if (m_recv_buffer.size() == EllSwiftPubKey::size()) {
1166 // Other side's key has been fully received, and can now be Diffie-Hellman combined with
1167 // our key to initialize the encryption ciphers.
1168
1169 // Initialize the ciphers.
1170 EllSwiftPubKey ellswift(MakeByteSpan(m_recv_buffer));
1171 LOCK(m_send_mutex);
1173
1174 // Switch receiver state to GARB_GARBTERM.
1176 m_recv_buffer.clear();
1177
1178 // Switch sender state to READY.
1180
1181 // Append the garbage terminator to the send buffer.
1183 std::copy(m_cipher.GetSendGarbageTerminator().begin(),
1186
1187 // Construct version packet in the send buffer, with the sent garbage data as AAD.
1190 /*contents=*/VERSION_CONTENTS,
1192 /*ignore=*/false,
1194 // We no longer need the garbage.
1196 } else {
1197 // We still have to receive more key bytes.
1198 }
1199 return true;
1200}
1201
1203{
1204 AssertLockHeld(m_recv_mutex);
1207 if (m_recv_buffer.size() >= BIP324Cipher::GARBAGE_TERMINATOR_LEN) {
1209 // Garbage terminator received. Store garbage to authenticate it as AAD later.
1210 m_recv_aad = std::move(m_recv_buffer);
1212 m_recv_buffer.clear();
1214 } else if (m_recv_buffer.size() == MAX_GARBAGE_LEN + BIP324Cipher::GARBAGE_TERMINATOR_LEN) {
1215 // We've reached the maximum length for garbage + garbage terminator, and the
1216 // terminator still does not match. Abort.
1217 LogDebug(BCLog::NET, "V2 transport error: missing garbage terminator, peer=%d\n", m_nodeid);
1218 return false;
1219 } else {
1220 // We still need to receive more garbage and/or garbage terminator bytes.
1221 }
1222 } else {
1223 // We have less than GARBAGE_TERMINATOR_LEN (16) bytes, so we certainly need to receive
1224 // more first.
1225 }
1226 return true;
1227}
1228
1230{
1231 AssertLockHeld(m_recv_mutex);
1233
1234 // The maximum permitted contents length for a packet, consisting of:
1235 // - 0x00 byte: indicating long message type encoding
1236 // - 12 bytes of message type
1237 // - payload
1238 static constexpr size_t MAX_CONTENTS_LEN =
1240 std::min<size_t>(MAX_SIZE, MAX_PROTOCOL_MESSAGE_LENGTH);
1241
1242 if (m_recv_buffer.size() == BIP324Cipher::LENGTH_LEN) {
1243 // Length descriptor received.
1246 LogDebug(BCLog::NET, "V2 transport error: packet too large (%u bytes), peer=%d\n", m_recv_len, m_nodeid);
1247 return false;
1248 }
1249 } else if (m_recv_buffer.size() > BIP324Cipher::LENGTH_LEN && m_recv_buffer.size() == m_recv_len + BIP324Cipher::EXPANSION) {
1250 // Ciphertext received, decrypt it into m_recv_decode_buffer.
1251 // Note that it is impossible to reach this branch without hitting the branch above first,
1252 // as GetMaxBytesToProcess only allows up to LENGTH_LEN into the buffer before that point.
1254 bool ignore{false};
1255 bool ret = m_cipher.Decrypt(
1256 /*input=*/MakeByteSpan(m_recv_buffer).subspan(BIP324Cipher::LENGTH_LEN),
1257 /*aad=*/MakeByteSpan(m_recv_aad),
1258 /*ignore=*/ignore,
1260 if (!ret) {
1261 LogDebug(BCLog::NET, "V2 transport error: packet decryption failure (%u bytes), peer=%d\n", m_recv_len, m_nodeid);
1262 return false;
1263 }
1264 // We have decrypted a valid packet with the AAD we expected, so clear the expected AAD.
1266 // Feed the last 4 bytes of the Poly1305 authentication tag (and its timing) into our RNG.
1267 RandAddEvent(ReadLE32(m_recv_buffer.data() + m_recv_buffer.size() - 4));
1268
1269 // At this point we have a valid packet decrypted into m_recv_decode_buffer. If it's not a
1270 // decoy, which we simply ignore, use the current state to decide what to do with it.
1271 if (!ignore) {
1272 switch (m_recv_state) {
1273 case RecvState::VERSION:
1274 // Version message received; transition to application phase. The contents is
1275 // ignored, but can be used for future extensions.
1277 break;
1278 case RecvState::APP:
1279 // Application message decrypted correctly. It can be extracted using GetMessage().
1281 break;
1282 default:
1283 // Any other state is invalid (this function should not have been called).
1284 Assume(false);
1285 }
1286 }
1287 // Wipe the receive buffer where the next packet will be received into.
1288 ClearShrink(m_recv_buffer);
1289 // In all but APP_READY state, we can wipe the decoded contents.
1291 } else {
1292 // We either have less than 3 bytes, so we don't know the packet's length yet, or more
1293 // than 3 bytes but less than the packet's full ciphertext. Wait until those arrive.
1294 }
1295 return true;
1296}
1297
1299{
1300 AssertLockHeld(m_recv_mutex);
1301 switch (m_recv_state) {
1303 // During the KEY_MAYBE_V1 state we do not allow more than the length of v1 prefix into the
1304 // receive buffer.
1305 Assume(m_recv_buffer.size() <= V1_PREFIX_LEN);
1306 // As long as we're not sure if this is a v1 or v2 connection, don't receive more than what
1307 // is strictly necessary to distinguish the two (16 bytes). If we permitted more than
1308 // the v1 header size (24 bytes), we may not be able to feed the already-received bytes
1309 // back into the m_v1_fallback V1 transport.
1310 return V1_PREFIX_LEN - m_recv_buffer.size();
1311 case RecvState::KEY:
1312 // During the KEY state, we only allow the 64-byte key into the receive buffer.
1313 Assume(m_recv_buffer.size() <= EllSwiftPubKey::size());
1314 // As long as we have not received the other side's public key, don't receive more than
1315 // that (64 bytes), as garbage follows, and locating the garbage terminator requires the
1316 // key exchange first.
1317 return EllSwiftPubKey::size() - m_recv_buffer.size();
1319 // Process garbage bytes one by one (because terminator may appear anywhere).
1320 return 1;
1321 case RecvState::VERSION:
1322 case RecvState::APP:
1323 // These three states all involve decoding a packet. Process the length descriptor first,
1324 // so that we know where the current packet ends (and we don't process bytes from the next
1325 // packet or decoy yet). Then, process the ciphertext bytes of the current packet.
1326 if (m_recv_buffer.size() < BIP324Cipher::LENGTH_LEN) {
1327 return BIP324Cipher::LENGTH_LEN - m_recv_buffer.size();
1328 } else {
1329 // Note that BIP324Cipher::EXPANSION is the total difference between contents size
1330 // and encoded packet size, which includes the 3 bytes due to the packet length.
1331 // When transitioning from receiving the packet length to receiving its ciphertext,
1332 // the encrypted packet length is left in the receive buffer.
1333 return BIP324Cipher::EXPANSION + m_recv_len - m_recv_buffer.size();
1334 }
1336 // No bytes can be processed until GetMessage() is called.
1337 return 0;
1338 case RecvState::V1:
1339 // Not allowed (must be dealt with by the caller).
1340 Assume(false);
1341 return 0;
1342 }
1343 Assume(false); // unreachable
1344 return 0;
1345}
1346
1347bool V2Transport::ReceivedBytes(std::span<const uint8_t>& msg_bytes) noexcept
1348{
1349 AssertLockNotHeld(m_recv_mutex);
1351 static constexpr size_t MAX_RESERVE_AHEAD = 256 * 1024;
1352
1353 LOCK(m_recv_mutex);
1354 if (m_recv_state == RecvState::V1) return m_v1_fallback.ReceivedBytes(msg_bytes);
1355
1356 // Process the provided bytes in msg_bytes in a loop. In each iteration a nonzero number of
1357 // bytes (decided by GetMaxBytesToProcess) are taken from the beginning om msg_bytes, and
1358 // appended to m_recv_buffer. Then, depending on the receiver state, one of the
1359 // ProcessReceived*Bytes functions is called to process the bytes in that buffer.
1360 while (!msg_bytes.empty()) {
1361 // Decide how many bytes to copy from msg_bytes to m_recv_buffer.
1362 size_t max_read = GetMaxBytesToProcess();
1363
1364 // Reserve space in the buffer if there is not enough.
1365 if (m_recv_buffer.size() + std::min(msg_bytes.size(), max_read) > m_recv_buffer.capacity()) {
1366 switch (m_recv_state) {
1367 case RecvState::KEY_MAYBE_V1:
1368 case RecvState::KEY:
1369 case RecvState::GARB_GARBTERM:
1370 // During the initial states (key/garbage), allocate once to fit the maximum (4111
1371 // bytes).
1372 m_recv_buffer.reserve(MAX_GARBAGE_LEN + BIP324Cipher::GARBAGE_TERMINATOR_LEN);
1373 break;
1374 case RecvState::VERSION:
1375 case RecvState::APP: {
1376 // During states where a packet is being received, as much as is expected but never
1377 // more than MAX_RESERVE_AHEAD bytes in addition to what is received so far.
1378 // This means attackers that want to cause us to waste allocated memory are limited
1379 // to MAX_RESERVE_AHEAD above the largest allowed message contents size, and to
1380 // MAX_RESERVE_AHEAD more than they've actually sent us.
1381 size_t alloc_add = std::min(max_read, msg_bytes.size() + MAX_RESERVE_AHEAD);
1382 m_recv_buffer.reserve(m_recv_buffer.size() + alloc_add);
1383 break;
1384 }
1385 case RecvState::APP_READY:
1386 // The buffer is empty in this state.
1387 Assume(m_recv_buffer.empty());
1388 break;
1389 case RecvState::V1:
1390 // Should have bailed out above.
1391 Assume(false);
1392 break;
1393 }
1394 }
1395
1396 // Can't read more than provided input.
1397 max_read = std::min(msg_bytes.size(), max_read);
1398 // Copy data to buffer.
1399 m_recv_buffer.insert(m_recv_buffer.end(), UCharCast(msg_bytes.data()), UCharCast(msg_bytes.data() + max_read));
1400 msg_bytes = msg_bytes.subspan(max_read);
1401
1402 // Process data in the buffer.
1403 switch (m_recv_state) {
1404 case RecvState::KEY_MAYBE_V1:
1405 ProcessReceivedMaybeV1Bytes();
1406 if (m_recv_state == RecvState::V1) return true;
1407 break;
1408
1409 case RecvState::KEY:
1410 if (!ProcessReceivedKeyBytes()) return false;
1411 break;
1412
1413 case RecvState::GARB_GARBTERM:
1414 if (!ProcessReceivedGarbageBytes()) return false;
1415 break;
1416
1417 case RecvState::VERSION:
1418 case RecvState::APP:
1419 if (!ProcessReceivedPacketBytes()) return false;
1420 break;
1421
1422 case RecvState::APP_READY:
1423 return true;
1424
1425 case RecvState::V1:
1426 // We should have bailed out before.
1427 Assume(false);
1428 break;
1429 }
1430 // Make sure we have made progress before continuing.
1431 Assume(max_read > 0);
1432 }
1433
1434 return true;
1435}
1436
1437std::optional<std::string> V2Transport::GetMessageType(std::span<const uint8_t>& contents) noexcept
1438{
1439 if (contents.size() == 0) return std::nullopt; // Empty contents
1441 contents = contents.subspan(1); // Strip first byte.
1442
1443 if (first_byte != 0) {
1444 // Short (1 byte) encoding.
1445 if (first_byte < std::size(V2_MESSAGE_IDS)) {
1446 // Valid short message id.
1447 return V2_MESSAGE_IDS[first_byte];
1448 } else {
1449 // Unknown short message id.
1450 return std::nullopt;
1451 }
1452 }
1453
1455 return std::nullopt; // Long encoding needs 12 message type bytes.
1456 }
1457
1458 size_t msg_type_len{0};
1460 // Verify that message type bytes before the first 0x00 are in range. BIP324 specifies the
1461 // long message type encoding as "an ASCII message type (as in the v1 P2P protocol)".
1462 if (contents[msg_type_len] < ' ' || contents[msg_type_len] > 0x7E) {
1463 return {};
1464 }
1465 ++msg_type_len;
1466 }
1467 std::string ret{reinterpret_cast<const char*>(contents.data()), msg_type_len};
1469 // Verify that message type bytes after the first 0x00 are also 0x00.
1470 if (contents[msg_type_len] != 0) return {};
1471 ++msg_type_len;
1472 }
1473 // Strip message type bytes of contents.
1475 return ret;
1476}
1477
1479{
1480 AssertLockNotHeld(m_recv_mutex);
1481 LOCK(m_recv_mutex);
1482 if (m_recv_state == RecvState::V1) return m_v1_fallback.GetReceivedMessage(time, reject_message);
1483
1484 Assume(m_recv_state == RecvState::APP_READY);
1485 std::span<const uint8_t> contents{m_recv_decode_buffer};
1486 auto msg_type = GetMessageType(contents);
1487 CNetMessage msg{DataStream{}};
1488 // Note that BIP324Cipher::EXPANSION also includes the length descriptor size.
1489 msg.m_raw_message_size = m_recv_decode_buffer.size() + BIP324Cipher::EXPANSION;
1490 if (msg_type) {
1491 reject_message = false;
1492 msg.m_type = std::move(*msg_type);
1493 msg.m_time = time;
1494 msg.m_message_size = contents.size();
1495 msg.m_recv.resize(contents.size());
1496 std::copy(contents.begin(), contents.end(), UCharCast(msg.m_recv.data()));
1497 } else {
1498 LogDebug(BCLog::NET, "V2 transport error: invalid message type (%u bytes contents), peer=%d\n", m_recv_decode_buffer.size(), m_nodeid);
1499 reject_message = true;
1500 }
1502 SetReceiveState(RecvState::APP);
1503
1504 return msg;
1505}
1506
1508{
1509 AssertLockNotHeld(m_send_mutex);
1510 LOCK(m_send_mutex);
1511 if (m_send_state == SendState::V1) return m_v1_fallback.SetMessageToSend(msg);
1512 // We only allow adding a new message to be sent when in the READY state (so the packet cipher
1513 // is available) and the send buffer is empty. This limits the number of messages in the send
1514 // buffer to just one, and leaves the responsibility for queueing them up to the caller.
1515 if (!(m_send_state == SendState::READY && m_send_buffer.empty())) return false;
1516 // Construct contents (encoding message type + payload).
1517 std::vector<uint8_t> contents;
1518 auto short_message_id = V2_MESSAGE_MAP(msg.m_type);
1519 if (short_message_id) {
1520 contents.resize(1 + msg.data.size());
1522 std::copy(msg.data.begin(), msg.data.end(), contents.begin() + 1);
1523 } else {
1524 // Initialize with zeroes, and then write the message type string starting at offset 1.
1525 // This means contents[0] and the unused positions in contents[1..13] remain 0x00.
1526 contents.resize(1 + CMessageHeader::MESSAGE_TYPE_SIZE + msg.data.size(), 0);
1527 std::copy(msg.m_type.begin(), msg.m_type.end(), contents.data() + 1);
1528 std::copy(msg.data.begin(), msg.data.end(), contents.begin() + 1 + CMessageHeader::MESSAGE_TYPE_SIZE);
1529 }
1530 // Construct ciphertext in send buffer.
1532 m_cipher.Encrypt(MakeByteSpan(contents), {}, false, MakeWritableByteSpan(m_send_buffer));
1533 m_send_type = msg.m_type;
1534 // Release memory
1535 ClearShrink(msg.data);
1536 return true;
1537}
1538
1540{
1541 AssertLockNotHeld(m_send_mutex);
1542 LOCK(m_send_mutex);
1543 if (m_send_state == SendState::V1) return m_v1_fallback.GetBytesToSend(have_next_message);
1544
1545 if (m_send_state == SendState::MAYBE_V1) Assume(m_send_buffer.empty());
1546 Assume(m_send_pos <= m_send_buffer.size());
1547 return {
1548 std::span{m_send_buffer}.subspan(m_send_pos),
1549 // We only have more to send after the current m_send_buffer if there is a (next)
1550 // message to be sent, and we're capable of sending packets. */
1551 have_next_message && m_send_state == SendState::READY,
1553 };
1554}
1555
1557{
1558 AssertLockNotHeld(m_send_mutex);
1559 LOCK(m_send_mutex);
1560 if (m_send_state == SendState::V1) return m_v1_fallback.MarkBytesSent(bytes_sent);
1561
1562 if (m_send_state == SendState::AWAITING_KEY && m_send_pos == 0 && bytes_sent > 0) {
1563 LogDebug(BCLog::NET, "start sending v2 handshake to peer=%d\n", m_nodeid);
1564 }
1565
1567 Assume(m_send_pos <= m_send_buffer.size());
1570 }
1571 // Wipe the buffer when everything is sent.
1572 if (m_send_pos == m_send_buffer.size()) {
1573 m_send_pos = 0;
1575 }
1576}
1577
1579{
1580 AssertLockNotHeld(m_send_mutex);
1581 AssertLockNotHeld(m_recv_mutex);
1582 // Only outgoing connections need reconnection.
1583 if (!m_initiating) return false;
1584
1585 LOCK(m_recv_mutex);
1586 // We only reconnect in the very first state and when the receive buffer is empty. Together
1587 // these conditions imply nothing has been received so far.
1588 if (m_recv_state != RecvState::KEY) return false;
1589 if (!m_recv_buffer.empty()) return false;
1590 // Check if we've sent enough for the other side to disconnect us (if it was V1).
1591 LOCK(m_send_mutex);
1593}
1594
1595size_t V2Transport::GetSendMemoryUsage() const noexcept
1596{
1597 AssertLockNotHeld(m_send_mutex);
1598 LOCK(m_send_mutex);
1600
1602}
1603
1605{
1606 AssertLockNotHeld(m_recv_mutex);
1607 LOCK(m_recv_mutex);
1609
1610 Transport::Info info;
1611
1612 // Do not report v2 and session ID until the version packet has been received
1613 // and verified (confirming that the other side very likely has the same keys as us).
1618 } else {
1620 }
1621
1622 return info;
1623}
1624
1625std::pair<size_t, bool> CConnman::SocketSendData(CNode& node) const
1626{
1627 auto it = node.vSendMsg.begin();
1628 size_t nSentSize = 0;
1629 bool data_left{false};
1630 std::optional<bool> expected_more;
1631
1632 while (true) {
1633 if (it != node.vSendMsg.end()) {
1634 // If possible, move one message from the send queue to the transport. This fails when
1635 // there is an existing message still being sent, or (for v2 transports) when the
1636 // handshake has not yet completed.
1637 size_t memusage = it->GetMemoryUsage();
1638 if (node.m_transport->SetMessageToSend(*it)) {
1639 // Update memory usage of send buffer (as *it will be deleted).
1640 node.m_send_memusage -= memusage;
1641 ++it;
1642 }
1643 }
1644 const auto& [data, more, msg_type] = node.m_transport->GetBytesToSend(it != node.vSendMsg.end());
1645 // We rely on the 'more' value returned by GetBytesToSend to correctly predict whether more
1646 // bytes are still to be sent, to correctly set the MSG_MORE flag. As a sanity check,
1647 // verify that the previously returned 'more' was correct.
1648 if (expected_more.has_value()) Assume(!data.empty() == *expected_more);
1650 data_left = !data.empty(); // will be overwritten on next loop if all of data gets sent
1651 int nBytes = 0;
1652 if (!data.empty()) {
1653 LOCK(node.m_sock_mutex);
1654 // There is no socket in case we've already disconnected, or in test cases without
1655 // real connections. In these cases, we bail out immediately and just leave things
1656 // in the send queue and transport.
1657 if (!node.m_sock) {
1658 break;
1659 }
1661#ifdef MSG_MORE
1662 if (more) {
1663 flags |= MSG_MORE;
1664 }
1665#endif
1666 nBytes = node.m_sock->Send(data.data(), data.size(), flags);
1667 }
1668 if (nBytes > 0) {
1669 node.m_last_send = NodeClock::now();
1670 node.nSendBytes += nBytes;
1671 // Notify transport that bytes have been processed.
1672 node.m_transport->MarkBytesSent(nBytes);
1673 // Update statistics per message type.
1674 if (!msg_type.empty()) { // don't report v2 handshake bytes for now
1675 node.AccountForSentBytes(msg_type, nBytes);
1676 }
1677 nSentSize += nBytes;
1678 if ((size_t)nBytes != data.size()) {
1679 // could not send full message; stop sending more
1680 break;
1681 }
1682 } else {
1683 if (nBytes < 0) {
1684 // error
1685 int nErr = WSAGetLastError();
1687 LogDebug(BCLog::NET, "socket send error, %s: %s", node.DisconnectMsg(), NetworkErrorString(nErr));
1688 node.CloseSocketDisconnect();
1689 }
1690 }
1691 break;
1692 }
1693 }
1694
1695 const bool pause_send{node.m_send_memusage + node.m_transport->GetSendMemoryUsage() > nSendBufferMaxSize};
1696 if (pause_send && !node.fPauseSend) {
1697 node.m_pause_send_since = NodeClock::now();
1698 }
1699 node.fPauseSend = pause_send;
1700
1701 if (it == node.vSendMsg.end()) {
1702 assert(node.m_send_memusage == 0);
1703 }
1704 node.vSendMsg.erase(node.vSendMsg.begin(), it);
1705 return {nSentSize, data_left};
1706}
1707
1717{
1719
1720 std::vector<NodeEvictionCandidate> vEvictionCandidates;
1721 {
1722
1724 for (const CNode* node : m_nodes) {
1725 if (node->fDisconnect)
1726 continue;
1727 if (protect_peer.has_value() && node->GetId() == protect_peer) {
1728 continue;
1729 }
1730 if (evict_tx_relay_peer_only && !node->m_relays_txs) {
1731 continue;
1732 }
1734 .id = node->GetId(),
1735 .m_connected = node->m_connected,
1736 .m_min_ping_time = node->m_min_ping_time,
1737 .m_last_block_time = node->m_last_block_time,
1738 .m_last_tx_time = node->m_last_tx_time,
1739 .fRelevantServices = node->m_has_all_wanted_services,
1740 .m_relay_txs = node->m_relays_txs.load(),
1741 .fBloomFilter = node->m_bloom_filter_loaded.load(),
1742 .nKeyedNetGroup = node->nKeyedNetGroup,
1743 .prefer_evict = node->m_prefer_evict,
1744 .m_is_local = node->addr.IsLocal(),
1745 .m_network = node->ConnectedThroughNetwork(),
1746 .m_noban = node->HasPermission(NetPermissionFlags::NoBan),
1747 .m_conn_type = node->m_conn_type,
1748 };
1749 vEvictionCandidates.push_back(candidate);
1750 }
1751 }
1752 const std::optional<NodeId> node_id_to_evict = SelectNodeToEvict(std::move(vEvictionCandidates));
1753 if (!node_id_to_evict) {
1754 return false;
1755 }
1757 for (CNode* pnode : m_nodes) {
1758 if (pnode->GetId() == *node_id_to_evict) {
1759 LogDebug(BCLog::NET, "selected %s connection for eviction, %s", pnode->ConnectionTypeAsString(), pnode->DisconnectMsg());
1761 pnode->GetId(),
1762 pnode->m_addr_name.c_str(),
1763 pnode->ConnectionTypeAsString().c_str(),
1764 pnode->ConnectedThroughNetwork(),
1766 pnode->fDisconnect = true;
1767 return true;
1768 }
1769 }
1770 return false;
1771}
1772
1775
1777 socklen_t len = sizeof(sockaddr);
1778 auto sock = hListenSocket.sock->Accept((struct sockaddr*)&sockaddr, &len);
1779
1780 if (!sock) {
1781 const int nErr = WSAGetLastError();
1782 if (nErr != WSAEWOULDBLOCK) {
1783 LogInfo("socket error accept failed: %s\n", NetworkErrorString(nErr));
1784 }
1785 return;
1786 }
1787
1788 CService addr;
1789 if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr, len)) {
1790 LogWarning("Unknown socket family\n");
1791 } else {
1792 addr = MaybeFlipIPv6toCJDNS(addr);
1793 }
1794
1796
1798 hListenSocket.AddSocketPermissionFlags(permission_flags);
1799
1800 CreateNodeFromAcceptedSocket(std::move(sock), permission_flags, addr_bind, addr);
1801}
1802
1803void CConnman::CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock,
1804 NetPermissionFlags permission_flags,
1805 const CService& addr_bind,
1806 const CService& addr)
1807{
1809
1810 int nInbound = 0;
1811
1812 const bool inbound_onion = std::find(m_onion_binds.begin(), m_onion_binds.end(), addr_bind) != m_onion_binds.end();
1813
1814 // Tor inbound connections do not reveal the peer's actual network address.
1815 // Therefore do not apply address-based whitelist permissions to them.
1816 AddWhitelistPermissionFlags(permission_flags, inbound_onion ? std::optional<CNetAddr>{} : addr, vWhitelistedRangeIncoming);
1817
1818 {
1820 for (const CNode* pnode : m_nodes) {
1821 if (pnode->IsInboundConn()) nInbound++;
1822 }
1823 }
1824
1825 if (!fNetworkActive) {
1826 LogDebug(BCLog::NET, "connection from %s dropped: not accepting new connections\n", addr.ToStringAddrPort());
1827 return;
1828 }
1829
1830 if (!sock->IsSelectable()) {
1831 LogInfo("connection from %s dropped: non-selectable socket\n", addr.ToStringAddrPort());
1832 return;
1833 }
1834
1835 // According to the internet TCP_NODELAY is not carried into accepted sockets
1836 // on all platforms. Set it again here just to be sure.
1837 const int on{1};
1838 if (sock->SetSockOpt(IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) == SOCKET_ERROR) {
1839 LogDebug(BCLog::NET, "connection from %s: unable to set TCP_NODELAY, continuing anyway\n",
1840 addr.ToStringAddrPort());
1841 }
1842
1843 // Don't accept connections from banned peers.
1844 bool banned = m_banman && m_banman->IsBanned(addr);
1845 if (!NetPermissions::HasFlag(permission_flags, NetPermissionFlags::NoBan) && banned)
1846 {
1847 LogDebug(BCLog::NET, "connection from %s dropped (banned)\n", addr.ToStringAddrPort());
1848 return;
1849 }
1850
1851 // Only accept connections from discouraged peers if our inbound slots aren't (almost) full.
1852 bool discouraged = m_banman && m_banman->IsDiscouraged(addr);
1854 {
1855 LogDebug(BCLog::NET, "connection from %s dropped (discouraged)\n", addr.ToStringAddrPort());
1856 return;
1857 }
1858
1859 if (nInbound >= m_max_inbound)
1860 {
1861 if (!AttemptToEvictConnection(/*evict_tx_relay_peer_only=*/false)) {
1862 // No connection to evict, disconnect the new connection
1863 LogDebug(BCLog::NET, "failed to find an eviction candidate - connection dropped (full)\n");
1864 return;
1865 }
1866 }
1867
1868 NodeId id = GetNewNodeId();
1870
1871 // The V2Transport transparently falls back to V1 behavior when an incoming V1 connection is
1872 // detected, so use it whenever we signal NODE_P2P_V2.
1875
1878 .Write(addr_bind.GetAddrBytes())
1879 .Write(addr_bind.GetPort()) // inbound connections use bind port
1880 .Finalize();
1881 CNode* pnode = new CNode(id,
1882 std::move(sock),
1883 CAddress{addr, NODE_NONE},
1885 nonce,
1886 addr_bind,
1887 /*addrNameIn=*/"",
1890 network_id,
1892 .permission_flags = permission_flags,
1893 .prefer_evict = discouraged,
1894 .recv_flood_size = nReceiveFloodSize,
1895 .use_v2transport = use_v2transport,
1896 });
1897 pnode->AddRef();
1898 m_msgproc->InitializeNode(*pnode, local_services);
1899 {
1901 m_nodes.push_back(pnode);
1902 }
1903 LogDebug(BCLog::NET, "connection from %s accepted\n", addr.ToStringAddrPort());
1905 pnode->GetId(),
1906 pnode->m_addr_name.c_str(),
1907 pnode->ConnectionTypeAsString().c_str(),
1908 pnode->ConnectedThroughNetwork(),
1910
1911 // We received a new connection, harvest entropy from the time (and our peer count)
1913}
1914
1915bool CConnman::AddConnection(const std::string& address, ConnectionType conn_type, bool use_v2transport = false)
1916{
1919 std::optional<int> max_connections;
1920 switch (conn_type) {
1923 return false;
1924 // no separate per-type limit for MANUAL because semAddnode limits them
1926 break;
1928 max_connections = m_max_outbound_full_relay;
1929 break;
1931 max_connections = m_max_outbound_block_relay;
1932 break;
1933 // no limit for ADDR_FETCH because -seednode has no limit either
1935 break;
1936 // no limit for FEELER connections since they're short-lived
1938 break;
1939 } // no default case, so the compiler can warn about missing cases
1940
1941 // Count existing connections
1943 return std::count_if(m_nodes.begin(), m_nodes.end(), [conn_type](CNode* node) { return node->m_conn_type == conn_type; }););
1944
1945 // Max connections of specified type already exist
1946 if (max_connections != std::nullopt && existing_connections >= max_connections) return false;
1947
1948 // Max total automatic outbound or manual connections already exist
1950 if (!grant) return false;
1951
1952 OpenNetworkConnection(/*addrConnect=*/CAddress{},
1953 /*fCountFailure=*/false,
1954 /*grant_outbound=*/std::move(grant),
1955 /*pszDest=*/address.c_str(),
1956 /*conn_type=*/conn_type,
1957 /*use_v2transport=*/use_v2transport,
1958 /*proxy_override=*/std::nullopt);
1959 return true;
1960}
1961
1963{
1966
1967 // Use a temporary variable to accumulate desired reconnections, so we don't need
1968 // m_reconnections_mutex while holding m_nodes_mutex.
1970
1971 {
1973
1974 const bool network_active{fNetworkActive};
1975 if (!network_active) {
1976 // Disconnect any connected nodes
1977 for (CNode* pnode : m_nodes) {
1978 if (!pnode->fDisconnect) {
1979 LogDebug(BCLog::NET, "Network not active, %s", pnode->DisconnectMsg());
1980 pnode->fDisconnect = true;
1981 }
1982 }
1983 }
1984
1985 // Disconnect unused nodes
1986 std::vector<CNode*> nodes_copy = m_nodes;
1987 for (CNode* pnode : nodes_copy)
1988 {
1989 if (pnode->fDisconnect)
1990 {
1991 // remove from m_nodes
1992 std::erase(m_nodes, pnode);
1993
1994 // Add to reconnection list if appropriate. We don't reconnect right here, because
1995 // the creation of a connection is a blocking operation (up to several seconds),
1996 // and we don't want to hold up the socket handler thread for that long.
1997 if (network_active && pnode->m_transport->ShouldReconnectV1()) {
1998 reconnections_to_add.push_back({
1999 .proxy_override = pnode->m_proxy_override,
2000 .addr_connect = pnode->addr,
2001 .grant = std::move(pnode->grantOutbound),
2002 .destination = pnode->m_dest,
2003 .conn_type = pnode->m_conn_type,
2004 .use_v2transport = false});
2005 LogDebug(BCLog::NET, "retrying with v1 transport protocol for peer=%d\n", pnode->GetId());
2006 }
2007
2008 // release outbound grant (if any)
2009 pnode->grantOutbound.Release();
2010
2011 // close socket and cleanup
2012 pnode->CloseSocketDisconnect();
2013
2014 // update connection count by network
2015 if (pnode->IsManualOrFullOutboundConn()) --m_network_conn_counts[pnode->addr.GetNetwork()];
2016
2017 // hold in disconnected pool until all refs are released
2018 pnode->Release();
2019 m_nodes_disconnected.push_back(pnode);
2020 }
2021 }
2022 }
2023 {
2024 // Delete disconnected nodes
2027 {
2028 // Destroy the object only after other threads have stopped using it.
2029 if (pnode->GetRefCount() <= 0) {
2030 std::erase(m_nodes_disconnected, pnode);
2032 }
2033 }
2034 }
2035 {
2036 // Move entries from reconnections_to_add to m_reconnections.
2038 m_reconnections.splice(m_reconnections.end(), std::move(reconnections_to_add));
2039 }
2040}
2041
2043{
2045
2046 size_t nodes_size;
2047 {
2049 nodes_size = m_nodes.size();
2050 }
2051 if(nodes_size != nPrevNodeCount) {
2053 if (m_client_interface) {
2054 m_client_interface->NotifyNumConnectionsChanged(nodes_size);
2055 }
2056 }
2057}
2058
2060{
2061 return node.m_connected + m_peer_connect_timeout < now;
2062}
2063
2065{
2066 // Tests that see disconnects after using mocktime can start nodes with a
2067 // large timeout. For example, -peertimeout=999999999.
2068 const auto last_send{node.m_last_send.load()};
2069 const auto last_recv{node.m_last_recv.load()};
2070
2071 if (!ShouldRunInactivityChecks(node, now)) return false;
2072
2073 bool has_received{last_recv > NodeClock::epoch};
2074 bool has_sent{last_send > NodeClock::epoch};
2075
2076 if (!has_received || !has_sent) {
2077 std::string has_never;
2078 if (!has_received) has_never += ", never received from peer";
2079 if (!has_sent) has_never += ", never sent to peer";
2081 "socket no message in first %i seconds%s, %s",
2083 has_never,
2084 node.DisconnectMsg()
2085 );
2086 return true;
2087 }
2088
2089 if (now > last_send + TIMEOUT_INTERVAL) {
2091 "socket sending timeout: %is, %s", Ticks<std::chrono::seconds>(now - last_send),
2092 node.DisconnectMsg()
2093 );
2094 return true;
2095 }
2096
2097 if (now > last_recv + TIMEOUT_INTERVAL) {
2099 "socket receive timeout: %is, %s", Ticks<std::chrono::seconds>(now - last_recv),
2100 node.DisconnectMsg()
2101 );
2102 return true;
2103 }
2104
2105 if (node.fPauseSend) {
2106 const auto last_pause{node.m_pause_send_since.load()};
2107 if (now > last_pause + TIMEOUT_INTERVAL) {
2109 "send buffer full for %is, %s", Ticks<std::chrono::seconds>(now - last_pause),
2110 node.DisconnectMsg()
2111 );
2112 return true;
2113 }
2114 }
2115
2116 if (!node.fSuccessfullyConnected) {
2117 if (node.m_transport->GetInfo().transport_type == TransportProtocolType::DETECTING) {
2118 LogDebug(BCLog::NET, "V2 handshake timeout, %s", node.DisconnectMsg());
2119 } else {
2120 LogDebug(BCLog::NET, "version handshake timeout, %s", node.DisconnectMsg());
2121 }
2122 return true;
2123 }
2124
2125 return false;
2126}
2127
2129{
2130 Sock::EventsPerSock events_per_sock;
2131
2133 events_per_sock.emplace(hListenSocket.sock, Sock::Events{Sock::RecvEvent});
2134 }
2135
2136 for (CNode* pnode : nodes) {
2137 bool select_recv = !pnode->fPauseRecv;
2138 bool select_send;
2139 {
2140 LOCK(pnode->cs_vSend);
2141 // Sending is possible if either there are bytes to send right now, or if there will be
2142 // once a potential message from vSendMsg is handed to the transport. GetBytesToSend
2143 // determines both of these in a single call.
2144 const auto& [to_send, more, _msg_type] = pnode->m_transport->GetBytesToSend(!pnode->vSendMsg.empty());
2145 select_send = !to_send.empty() || more;
2146 }
2147 if (!select_recv && !select_send) continue;
2148
2149 LOCK(pnode->m_sock_mutex);
2150 if (pnode->m_sock) {
2152 events_per_sock.emplace(pnode->m_sock, Sock::Events{event});
2153 }
2154 }
2155
2156 return events_per_sock;
2157}
2158
2160{
2163
2164 Sock::EventsPerSock events_per_sock;
2165
2166 {
2167 const NodesSnapshot snap{*this, /*shuffle=*/false};
2168
2169 const auto timeout = std::chrono::milliseconds(SELECT_TIMEOUT_MILLISECONDS);
2170
2171 // Check for the readiness of the already connected sockets and the
2172 // listening sockets in one call ("readiness" as in poll(2) or
2173 // select(2)). If none are ready, wait for a short while and return
2174 // empty sets.
2175 events_per_sock = GenerateWaitSockets(snap.Nodes());
2176 if (events_per_sock.empty() || !events_per_sock.begin()->first->WaitMany(timeout, events_per_sock)) {
2177 m_interrupt_net->sleep_for(timeout);
2178 }
2179
2180 // Service (send/receive) each of the already connected nodes.
2181 SocketHandlerConnected(snap.Nodes(), events_per_sock);
2182 }
2183
2184 // Accept new connections from listening sockets.
2185 SocketHandlerListening(events_per_sock);
2186}
2187
2188void CConnman::SocketHandlerConnected(const std::vector<CNode*>& nodes,
2189 const Sock::EventsPerSock& events_per_sock)
2190{
2192
2193 const auto now{NodeClock::now()};
2194
2195 for (CNode* pnode : nodes) {
2196 if (m_interrupt_net->interrupted()) {
2197 return;
2198 }
2199
2200 //
2201 // Receive
2202 //
2203 bool recvSet = false;
2204 bool sendSet = false;
2205 bool errorSet = false;
2206 {
2207 LOCK(pnode->m_sock_mutex);
2208 if (!pnode->m_sock) {
2209 continue;
2210 }
2211 const auto it = events_per_sock.find(pnode->m_sock);
2212 if (it != events_per_sock.end()) {
2213 recvSet = it->second.occurred & Sock::RecvEvent;
2214 sendSet = it->second.occurred & Sock::SendEvent;
2215 errorSet = it->second.occurred & Sock::ErrorEvent;
2216 }
2217 }
2218
2219 if (sendSet) {
2220 // Send data
2221 auto [bytes_sent, data_left] = WITH_LOCK(pnode->cs_vSend, return SocketSendData(*pnode));
2222 if (bytes_sent) {
2224
2225 // If both receiving and (non-optimistic) sending were possible, we first attempt
2226 // sending. If that succeeds, but does not fully drain the send queue, do not
2227 // attempt to receive. This avoids needlessly queueing data if the remote peer
2228 // is slow at receiving data, by means of TCP flow control. We only do this when
2229 // sending actually succeeded to make sure progress is always made; otherwise a
2230 // deadlock would be possible when both sides have data to send, but neither is
2231 // receiving.
2232 if (data_left) recvSet = false;
2233 }
2234 }
2235
2236 if (recvSet || errorSet)
2237 {
2238 // typical socket buffer is 8K-64K
2239 uint8_t pchBuf[0x10000];
2240 int nBytes = 0;
2241 {
2242 LOCK(pnode->m_sock_mutex);
2243 if (!pnode->m_sock) {
2244 continue;
2245 }
2246 nBytes = pnode->m_sock->Recv(pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
2247 }
2248 if (nBytes > 0)
2249 {
2250 bool notify = false;
2251 if (!pnode->ReceiveMsgBytes({pchBuf, (size_t)nBytes}, notify)) {
2253 "receiving message bytes failed, %s",
2254 pnode->DisconnectMsg()
2255 );
2256 pnode->CloseSocketDisconnect();
2257 }
2259 if (notify) {
2260 pnode->MarkReceivedMsgsForProcessing();
2262 }
2263 }
2264 else if (nBytes == 0)
2265 {
2266 // socket closed gracefully
2267 if (!pnode->fDisconnect) {
2268 LogDebug(BCLog::NET, "socket closed, %s", pnode->DisconnectMsg());
2269 }
2270 pnode->CloseSocketDisconnect();
2271 }
2272 else if (nBytes < 0)
2273 {
2274 // error
2275 int nErr = WSAGetLastError();
2277 {
2278 if (!pnode->fDisconnect) {
2279 LogDebug(BCLog::NET, "socket recv error, %s: %s", pnode->DisconnectMsg(), NetworkErrorString(nErr));
2280 }
2281 pnode->CloseSocketDisconnect();
2282 }
2283 }
2284 }
2285
2286 if (InactivityCheck(*pnode, now)) pnode->fDisconnect = true;
2287 }
2288}
2289
2291{
2293
2295 if (m_interrupt_net->interrupted()) {
2296 return;
2297 }
2298 const auto it = events_per_sock.find(listen_socket.sock);
2299 if (it != events_per_sock.end() && it->second.occurred & Sock::RecvEvent) {
2301 }
2302 }
2303}
2304
2306{
2308
2309 while (!m_interrupt_net->interrupted()) {
2312 SocketHandler();
2313 }
2314}
2315
2317{
2318 {
2320 fMsgProcWake = true;
2321 }
2322 condMsgProc.notify_one();
2323}
2324
2326{
2328
2329 if (!gArgs.GetArgs("-seednode").empty()) {
2330 auto start = NodeClock::now();
2331 constexpr std::chrono::seconds SEEDNODE_TIMEOUT = 30s;
2332 LogInfo("-seednode enabled. Trying the provided seeds for %d seconds before defaulting to the dnsseeds.\n", SEEDNODE_TIMEOUT.count());
2333 while (!m_interrupt_net->interrupted()) {
2334 if (!m_interrupt_net->sleep_for(500ms)) {
2335 return;
2336 }
2337
2338 // Abort if we have spent enough time without reaching our target.
2339 // Giving seed nodes 30 seconds so this does not become a race against fixedseeds (which triggers after 1 min)
2340 if (NodeClock::now() > start + SEEDNODE_TIMEOUT) {
2341 LogInfo("Couldn't connect to enough peers via seed nodes. Handing fetch logic to the DNS seeds.\n");
2342 break;
2343 }
2344
2347 LogInfo("P2P peers available. Finished fetching data from seed nodes.\n");
2348 break;
2349 }
2350 }
2351 }
2352
2354 std::vector<std::string> seeds = m_params.DNSSeeds();
2355 std::shuffle(seeds.begin(), seeds.end(), rng);
2356 int seeds_right_now = 0; // Number of seeds left before testing if we have enough connections
2357
2358 if (gArgs.GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED)) {
2359 // When -forcednsseed is provided, query all.
2360 seeds_right_now = seeds.size();
2361 } else if (addrman.get().Size() == 0) {
2362 // If we have no known peers, query all.
2363 // This will occur on the first run, or if peers.dat has been
2364 // deleted.
2365 seeds_right_now = seeds.size();
2366 }
2367
2368 // Proceed with dnsseeds if seednodes hasn't reached the target or if forcednsseed is set
2370 // goal: only query DNS seed if address need is acute
2371 // * If we have a reasonable number of peers in addrman, spend
2372 // some time trying them first. This improves user privacy by
2373 // creating fewer identifying DNS requests, reduces trust by
2374 // giving seeds less influence on the network topology, and
2375 // reduces traffic to the seeds.
2376 // * When querying DNS seeds query a few at once, this ensures
2377 // that we don't give DNS seeds the ability to eclipse nodes
2378 // that query them.
2379 // * If we continue having problems, eventually query all the
2380 // DNS seeds, and if that fails too, also try the fixed seeds.
2381 // (done in ThreadOpenConnections)
2382 int found = 0;
2384
2385 for (const std::string& seed : seeds) {
2386 if (seeds_right_now == 0) {
2388
2389 if (addrman.get().Size() > 0) {
2390 LogInfo("Waiting %d seconds before querying DNS seeds.\n", seeds_wait_time.count());
2391 std::chrono::seconds to_wait = seeds_wait_time;
2392 while (to_wait.count() > 0) {
2393 // if sleeping for the MANY_PEERS interval, wake up
2394 // early to see if we have enough peers and can stop
2395 // this thread entirely freeing up its resources
2396 std::chrono::seconds w = std::min(DNSSEEDS_DELAY_FEW_PEERS, to_wait);
2397 if (!m_interrupt_net->sleep_for(w)) return;
2398 to_wait -= w;
2399
2401 if (found > 0) {
2402 LogInfo("%d addresses found from DNS seeds\n", found);
2403 LogInfo("P2P peers available. Finished DNS seeding.\n");
2404 } else {
2405 LogInfo("P2P peers available. Skipped DNS seeding.\n");
2406 }
2407 return;
2408 }
2409 }
2410 }
2411 }
2412
2413 if (m_interrupt_net->interrupted()) return;
2414
2415 // hold off on querying seeds if P2P network deactivated
2416 if (!fNetworkActive) {
2417 LogInfo("Waiting for network to be reactivated before querying DNS seeds.\n");
2418 do {
2419 if (!m_interrupt_net->sleep_for(1s)) return;
2420 } while (!fNetworkActive);
2421 }
2422
2423 LogInfo("Loading addresses from DNS seed %s\n", seed);
2424 // If -proxy is in use, we make an ADDR_FETCH connection to the DNS resolved peer address
2425 // for the base dns seed domain in chainparams
2426 if (HaveNameProxy()) {
2427 AddAddrFetch(seed);
2428 } else {
2429 std::vector<CAddress> vAdd;
2431 std::string host = strprintf("x%x.%s", requiredServiceBits, seed);
2433 if (!resolveSource.SetInternal(host)) {
2434 continue;
2435 }
2436 // Limit number of IPs learned from a single DNS seed. This limit exists to prevent the results from
2437 // one DNS seed from dominating AddrMan. Note that the number of results from a UDP DNS query is
2438 // bounded to 33 already, but it is possible for it to use TCP where a larger number of results can be
2439 // returned.
2440 unsigned int nMaxIPs = 32;
2441 const auto addresses{LookupHost(host, nMaxIPs, true)};
2442 if (!addresses.empty()) {
2443 for (const CNetAddr& ip : addresses) {
2445 addr.nTime = rng.rand_uniform_delay(Now<NodeSeconds>() - 3 * 24h, -4 * 24h); // use a random age between 3 and 7 days old
2446 vAdd.push_back(addr);
2447 found++;
2448 }
2449 addrman.get().Add(vAdd, resolveSource);
2450 } else {
2451 // If the seed does not support a subdomain with our desired service bits,
2452 // we make an ADDR_FETCH connection to the DNS resolved peer address for the
2453 // base dns seed domain in chainparams
2454 AddAddrFetch(seed);
2455 }
2456 }
2458 }
2459 LogInfo("%d addresses found from DNS seeds\n", found);
2460 } else {
2461 LogInfo("Skipping DNS seeds. Enough peers have been found\n");
2462 }
2463}
2464
2466{
2467 const auto start{SteadyClock::now()};
2468
2470
2471 LogDebug(BCLog::NET, "Flushed %d addresses to peers.dat %dms",
2472 addrman.get().Size(), Ticks<std::chrono::milliseconds>(SteadyClock::now() - start));
2473}
2474
2476{
2479 std::string strDest;
2480 {
2482 if (m_addr_fetches.empty())
2483 return;
2484 strDest = m_addr_fetches.front();
2485 m_addr_fetches.pop_front();
2486 }
2487 // Attempt v2 connection if we support v2 - we'll reconnect with v1 if our
2488 // peer doesn't support it or immediately disconnects us for another reason.
2490 CAddress addr;
2491 CountingSemaphoreGrant<> grant(*semOutbound, /*fTry=*/true);
2492 if (grant) {
2493 OpenNetworkConnection(/*addrConnect=*/addr,
2494 /*fCountFailure=*/false,
2495 /*grant_outbound=*/std::move(grant),
2496 /*pszDest=*/strDest.c_str(),
2497 /*conn_type=*/ConnectionType::ADDR_FETCH,
2498 /*use_v2transport=*/use_v2transport,
2499 /*proxy_override=*/std::nullopt);
2500 }
2501}
2502
2507
2509{
2511 LogDebug(BCLog::NET, "setting try another outbound peer=%s\n", flag ? "true" : "false");
2512}
2513
2515{
2516 LogDebug(BCLog::NET, "enabling extra block-relay-only peers\n");
2518}
2519
2520// Return the number of outbound connections that are full relay (not blocks only)
2522{
2524
2525 int nRelevant = 0;
2526 {
2528 for (const CNode* pnode : m_nodes) {
2529 if (pnode->fSuccessfullyConnected && pnode->IsFullOutboundConn()) ++nRelevant;
2530 }
2531 }
2532 return nRelevant;
2533}
2534
2535// Return the number of peers we have over our outbound connection limit
2536// Exclude peers that are marked for disconnect, or are going to be
2537// disconnected soon (eg ADDR_FETCH and FEELER)
2538// Also exclude peers that haven't finished initial connection handshake yet
2539// (so that we don't decide we're over our desired connection limit, and then
2540// evict some peer that has finished the handshake)
2542{
2544
2545 int full_outbound_peers = 0;
2546 {
2548 for (const CNode* pnode : m_nodes) {
2549 if (pnode->fSuccessfullyConnected && !pnode->fDisconnect && pnode->IsFullOutboundConn()) {
2551 }
2552 }
2553 }
2554 return std::max(full_outbound_peers - m_max_outbound_full_relay, 0);
2555}
2556
2558{
2560
2561 int block_relay_peers = 0;
2562 {
2564 for (const CNode* pnode : m_nodes) {
2565 if (pnode->fSuccessfullyConnected && !pnode->fDisconnect && pnode->IsBlockOnlyConn()) {
2567 }
2568 }
2569 }
2570 return std::max(block_relay_peers - m_max_outbound_block_relay, 0);
2571}
2572
2574{
2575 int tx_inbound_peers{0};
2576 {
2578 for (const CNode* pnode : m_nodes) {
2579 if (!pnode->fDisconnect && pnode->IsInboundConn() && pnode->m_relays_txs) {
2581 }
2582 }
2583 }
2585 return AttemptToEvictConnection(/*evict_tx_relay_peer_only=*/true, protect_peer);
2586 }
2587 return true;
2588}
2589
2590std::unordered_set<Network> CConnman::GetReachableEmptyNetworks() const
2591{
2592 std::unordered_set<Network> networks{};
2593 for (int n = 0; n < NET_MAX; n++) {
2594 enum Network net = (enum Network)n;
2595 if (net == NET_UNROUTABLE || net == NET_INTERNAL) continue;
2596 if (g_reachable_nets.Contains(net) && addrman.get().Size(net, std::nullopt) == 0) {
2597 networks.insert(net);
2598 }
2599 }
2600 return networks;
2601}
2602
2608
2609bool CConnman::MaybePickPreferredNetwork(std::optional<Network>& network)
2610{
2612
2613 std::array<Network, 5> nets{NET_IPV4, NET_IPV6, NET_ONION, NET_I2P, NET_CJDNS};
2614 std::shuffle(nets.begin(), nets.end(), FastRandomContext());
2615
2617 for (const auto net : nets) {
2618 if (g_reachable_nets.Contains(net) && m_network_conn_counts[net] == 0 && addrman.get().Size(net) != 0) {
2619 network = net;
2620 return true;
2621 }
2622 }
2623
2624 return false;
2625}
2626
2627void CConnman::ThreadOpenConnections(const std::vector<std::string> connect, std::span<const std::string> seed_nodes)
2628{
2634 // Connect to specific addresses
2635 if (!connect.empty())
2636 {
2637 // Attempt v2 connection if we support v2 - we'll reconnect with v1 if our
2638 // peer doesn't support it or immediately disconnects us for another reason.
2640 for (int64_t nLoop = 0;; nLoop++)
2641 {
2642 for (const std::string& strAddr : connect)
2643 {
2645 /*fCountFailure=*/false,
2646 /*grant_outbound=*/{},
2647 /*pszDest=*/strAddr.c_str(),
2648 /*conn_type=*/ConnectionType::MANUAL,
2649 /*use_v2transport=*/use_v2transport,
2650 /*proxy_override=*/std::nullopt);
2651 for (int i = 0; i < 10 && i < nLoop; i++)
2652 {
2653 if (!m_interrupt_net->sleep_for(500ms)) {
2654 return;
2655 }
2656 }
2657 }
2658 if (!m_interrupt_net->sleep_for(500ms)) {
2659 return;
2660 }
2662 }
2663 }
2664
2665 // Initiate network connections
2667
2668 // Minimum time before next feeler connection (in microseconds).
2672 const bool dnsseed = gArgs.GetBoolArg("-dnsseed", DEFAULT_DNSSEED);
2673 bool add_fixed_seeds = gArgs.GetBoolArg("-fixedseeds", DEFAULT_FIXEDSEEDS);
2674 const bool use_seednodes{!gArgs.GetArgs("-seednode").empty()};
2675
2677 bool add_addr_fetch{addrman.get().Size() == 0 && !seed_nodes.empty()};
2678 constexpr std::chrono::seconds ADD_NEXT_SEEDNODE = 10s;
2679
2680 if (!add_fixed_seeds) {
2681 LogInfo("Fixed seeds are disabled\n");
2682 }
2683
2684 while (!m_interrupt_net->interrupted()) {
2685 if (add_addr_fetch) {
2686 add_addr_fetch = false;
2687 const auto& seed{SpanPopBack(seed_nodes)};
2688 AddAddrFetch(seed);
2689
2690 if (addrman.get().Size() == 0) {
2691 LogInfo("Empty addrman, adding seednode (%s) to addrfetch\n", seed);
2692 } else {
2693 LogInfo("Couldn't connect to peers from addrman after %d seconds. Adding seednode (%s) to addrfetch\n", ADD_NEXT_SEEDNODE.count(), seed);
2694 }
2695 }
2696
2698
2699 if (!m_interrupt_net->sleep_for(500ms)) {
2700 return;
2701 }
2702
2704
2706 if (m_interrupt_net->interrupted()) {
2707 return;
2708 }
2709
2710 const std::unordered_set<Network> fixed_seed_networks{GetReachableEmptyNetworks()};
2711 if (add_fixed_seeds && !fixed_seed_networks.empty()) {
2712 // When the node starts with an empty peers.dat, there are a few other sources of peers before
2713 // we fallback on to fixed seeds: -dnsseed, -seednode, -addnode
2714 // If none of those are available, we fallback on to fixed seeds immediately, else we allow
2715 // 60 seconds for any of those sources to populate addrman.
2716 bool add_fixed_seeds_now = false;
2717 // It is cheapest to check if enough time has passed first.
2718 if (GetTime<std::chrono::seconds>() > start + std::chrono::minutes{1}) {
2719 add_fixed_seeds_now = true;
2720 LogInfo("Adding fixed seeds as 60 seconds have passed and addrman is empty for at least one reachable network\n");
2721 }
2722
2723 // Perform cheap checks before locking a mutex.
2724 else if (!dnsseed && !use_seednodes) {
2726 if (m_added_node_params.empty()) {
2727 add_fixed_seeds_now = true;
2728 LogInfo("Adding fixed seeds as -dnsseed=0 (or IPv4/IPv6 connections are disabled via -onlynet) and neither -addnode nor -seednode are provided\n");
2729 }
2730 }
2731
2732 if (add_fixed_seeds_now) {
2733 std::vector<CAddress> seed_addrs{ConvertSeeds(m_params.FixedSeeds())};
2734 // We will not make outgoing connections to peers that are unreachable
2735 // (e.g. because of -onlynet configuration).
2736 // Therefore, we do not add them to addrman in the first place.
2737 // In case previously unreachable networks become reachable
2738 // (e.g. in case of -onlynet changes by the user), fixed seeds will
2739 // be loaded only for networks for which we have no addresses.
2740 std::erase_if(seed_addrs, [&fixed_seed_networks](const CAddress& addr) { return !fixed_seed_networks.contains(addr.GetNetwork()); });
2742 local.SetInternal("fixedseeds");
2743 addrman.get().Add(seed_addrs, local);
2744 add_fixed_seeds = false;
2745 LogInfo("Added %d fixed seeds from reachable networks.\n", seed_addrs.size());
2746 }
2747 }
2748
2749 //
2750 // Choose an address to connect to based on most recently seen
2751 //
2753
2754 // Only connect out to one peer per ipv4/ipv6 network group (/16 for IPv4).
2755 int nOutboundFullRelay = 0;
2756 int nOutboundBlockRelay = 0;
2758 std::set<std::vector<unsigned char>> outbound_ipv46_peer_netgroups;
2759
2760 {
2762 for (const CNode* pnode : m_nodes) {
2763 if (pnode->IsFullOutboundConn()) nOutboundFullRelay++;
2764 if (pnode->IsBlockOnlyConn()) nOutboundBlockRelay++;
2765
2766 // Make sure our persistent outbound slots to ipv4/ipv6 peers belong to different netgroups.
2767 switch (pnode->m_conn_type) {
2768 // We currently don't take inbound connections into account. Since they are
2769 // free to make, an attacker could make them to prevent us from connecting to
2770 // certain peers.
2772 // Short-lived outbound connections should not affect how we select outbound
2773 // peers from addrman.
2777 break;
2781 const CAddress address{pnode->addr};
2782 if (address.IsTor() || address.IsI2P() || address.IsCJDNS()) {
2783 // Since our addrman-groups for these networks are
2784 // random, without relation to the route we
2785 // take to connect to these peers or to the
2786 // difficulty in obtaining addresses with diverse
2787 // groups, we don't worry about diversity with
2788 // respect to our addrman groups when connecting to
2789 // these networks.
2791 } else {
2793 }
2794 } // no default case, so the compiler can warn about missing cases
2795 }
2796 }
2797
2801 add_addr_fetch = true;
2802 }
2803 }
2804
2807 bool anchor = false;
2808 bool fFeeler = false;
2809 std::optional<Network> preferred_net;
2810
2811 // Determine what type of connection to open. Opening
2812 // BLOCK_RELAY connections to addresses from anchors.dat gets the highest
2813 // priority. Then we open OUTBOUND_FULL_RELAY priority until we
2814 // meet our full-relay capacity. Then we open BLOCK_RELAY connection
2815 // until we hit our block-relay-only peer limit.
2816 // GetTryNewOutboundPeer() gets set when a stale tip is detected, so we
2817 // try opening an additional OUTBOUND_FULL_RELAY connection. If none of
2818 // these conditions are met, check to see if it's time to try an extra
2819 // block-relay-only peer (to confirm our tip is current, see below) or the next_feeler
2820 // timer to decide if we should open a FEELER.
2821
2822 // Only consume anchors while the network is active; otherwise they would be
2823 // popped and then dropped by OpenNetworkConnection(), losing them for the
2824 // next activation and for the dump at shutdown.
2825 const bool have_anchors{fNetworkActive && WITH_LOCK(m_anchors_mutex, return !m_anchors.empty())};
2827 conn_type = ConnectionType::BLOCK_RELAY;
2828 anchor = true;
2830 // OUTBOUND_FULL_RELAY
2832 conn_type = ConnectionType::BLOCK_RELAY;
2833 } else if (GetTryNewOutboundPeer()) {
2834 // OUTBOUND_FULL_RELAY
2836 // Periodically connect to a peer (using regular outbound selection
2837 // methodology from addrman) and stay connected long enough to sync
2838 // headers, but not much else.
2839 //
2840 // Then disconnect the peer, if we haven't learned anything new.
2841 //
2842 // The idea is to make eclipse attacks very difficult to pull off,
2843 // because every few minutes we're finding a new peer to learn headers
2844 // from.
2845 //
2846 // This is similar to the logic for trying extra outbound (full-relay)
2847 // peers, except:
2848 // - we do this all the time on an exponential timer, rather than just when
2849 // our tip is stale
2850 // - we potentially disconnect our next-youngest block-relay-only peer, if our
2851 // newest block-relay-only peer delivers a block more recently.
2852 // See the eviction logic in net_processing.cpp.
2853 //
2854 // Because we can promote these connections to block-relay-only
2855 // connections, they do not get their own ConnectionType enum
2856 // (similar to how we deal with extra outbound peers).
2858 conn_type = ConnectionType::BLOCK_RELAY;
2859 } else if (now > next_feeler) {
2861 conn_type = ConnectionType::FEELER;
2862 fFeeler = true;
2867 // Full outbound connection management: Attempt to get at least one
2868 // outbound peer from each reachable network by making extra connections
2869 // and then protecting "only" peers from a network during outbound eviction.
2870 // This is not attempted if the user changed -maxconnections to a value
2871 // so low that less than MAX_OUTBOUND_FULL_RELAY_CONNECTIONS are made,
2872 // to prevent interactions with otherwise protected outbound peers.
2874 } else {
2875 // skip to next iteration of while loop
2876 continue;
2877 }
2878
2879 addrman.get().ResolveCollisions();
2880
2881 const auto current_time{NodeClock::now()};
2882 int nTries = 0;
2883 const auto reachable_nets{g_reachable_nets.All()};
2884
2885 while (!m_interrupt_net->interrupted()) {
2886 if (anchor) {
2887 std::optional<CAddress> anchor_addr;
2888 {
2890 if (!m_anchors.empty()) {
2891 anchor_addr = m_anchors.back();
2892 m_anchors.pop_back();
2893 }
2894 }
2895 if (anchor_addr) {
2897 !m_msgproc->HasAllDesirableServiceFlags(anchor_addr->nServices) ||
2900 LogDebug(BCLog::NET, "Trying to make an anchor connection to %s\n", addrConnect.ToStringAddrPort());
2901 break;
2902 }
2903 }
2904
2905 // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
2906 // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
2907 // already-connected network ranges, ...) before trying new addrman addresses.
2908 nTries++;
2909 if (nTries > 100)
2910 break;
2911
2912 CAddress addr;
2914
2915 if (fFeeler) {
2916 // First, try to get a tried table collision address. This returns
2917 // an empty (invalid) address if there are no collisions to try.
2918 std::tie(addr, addr_last_try) = addrman.get().SelectTriedCollision();
2919
2920 if (!addr.IsValid()) {
2921 // No tried table collisions. Select a new table address
2922 // for our feeler.
2923 std::tie(addr, addr_last_try) = addrman.get().Select(true, reachable_nets);
2924 } else if (AlreadyConnectedToAddress(addr)) {
2925 // If test-before-evict logic would have us connect to a
2926 // peer that we're already connected to, just mark that
2927 // address as Good(). We won't be able to initiate the
2928 // connection anyway, so this avoids inadvertently evicting
2929 // a currently-connected peer.
2930 addrman.get().Good(addr);
2931 // Select a new table address for our feeler instead.
2932 std::tie(addr, addr_last_try) = addrman.get().Select(true, reachable_nets);
2933 }
2934 } else {
2935 // Not a feeler
2936 // If preferred_net has a value set, pick an extra outbound
2937 // peer from that network. The eviction logic in net_processing
2938 // ensures that a peer from another network will be evicted.
2939 std::tie(addr, addr_last_try) = preferred_net.has_value()
2940 ? addrman.get().Select(false, {*preferred_net})
2941 : addrman.get().Select(false, reachable_nets);
2942 }
2943
2944 // Require outbound IPv4/IPv6 connections, other than feelers, to be to distinct network groups
2946 continue;
2947 }
2948
2949 // if we selected an invalid or local address, restart
2950 if (!addr.IsValid() || IsLocal(addr)) {
2951 break;
2952 }
2953
2954 if (!g_reachable_nets.Contains(addr)) {
2955 continue;
2956 }
2957
2958 // only consider very recently tried nodes after 30 failed attempts
2959 if (current_time - addr_last_try < 10min && nTries < 30) {
2960 continue;
2961 }
2962
2963 // for non-feelers, require all the services we'll want,
2964 // for feelers, only require they be a full node (only because most
2965 // SPV clients don't have a good address DB available)
2966 if (!fFeeler && !m_msgproc->HasAllDesirableServiceFlags(addr.nServices)) {
2967 continue;
2968 } else if (fFeeler && !MayHaveUsefulAddressDB(addr.nServices)) {
2969 continue;
2970 }
2971
2972 // Do not connect to bad ports, unless 50 invalid addresses have been selected already.
2973 if (nTries < 50 && (addr.IsIPv4() || addr.IsIPv6()) && IsBadPort(addr.GetPort())) {
2974 continue;
2975 }
2976
2977 // Do not make automatic outbound connections to addnode peers, to
2978 // not use our limited outbound slots for them and to ensure
2979 // addnode connections benefit from their intended protections.
2980 if (AddedNodesContain(addr)) {
2981 LogDebug(BCLog::NET, "Not making automatic %s%s connection to %s peer selected for manual (addnode) connection%s\n",
2982 preferred_net.has_value() ? "network-specific " : "",
2984 fLogIPs ? strprintf(": %s", addr.ToStringAddrPort()) : "");
2985 continue;
2986 }
2987
2988 addrConnect = addr;
2989 break;
2990 }
2991
2992 if (addrConnect.IsValid()) {
2993 if (fFeeler) {
2994 // Add small amount of random noise before connection to avoid synchronization.
2996 return;
2997 }
2998 LogDebug(BCLog::NET, "Making feeler connection to %s\n", addrConnect.ToStringAddrPort());
2999 }
3000
3001 if (preferred_net != std::nullopt) LogDebug(BCLog::NET, "Making network specific connection to %s on %s.\n", addrConnect.ToStringAddrPort(), GetNetworkName(preferred_net.value()));
3002
3003 // Record addrman failure attempts when node has at least 2 persistent outbound connections to peers with
3004 // different netgroups in ipv4/ipv6 networks + all peers in Tor/I2P/CJDNS networks.
3005 // Don't record addrman failure attempts when node is offline. This can be identified since all local
3006 // network connections (if any) belong in the same netgroup, and the size of `outbound_ipv46_peer_netgroups` would only be 1.
3008 // Use BIP324 transport when both us and them have NODE_V2_P2P set.
3009 const bool use_v2transport(addrConnect.nServices & GetLocalServices() & NODE_P2P_V2);
3010 OpenNetworkConnection(/*addrConnect=*/addrConnect,
3011 /*fCountFailure=*/count_failures,
3012 /*grant_outbound=*/std::move(grant),
3013 /*pszDest=*/nullptr,
3014 /*conn_type=*/conn_type,
3015 /*use_v2transport=*/use_v2transport,
3016 /*proxy_override=*/std::nullopt);
3017 }
3018 }
3019}
3020
3021std::vector<CAddress> CConnman::GetCurrentBlockRelayOnlyConns() const
3022{
3024 std::vector<CAddress> ret;
3026 for (const CNode* pnode : m_nodes) {
3027 if (pnode->IsBlockOnlyConn()) {
3028 ret.push_back(pnode->addr);
3029 }
3030 }
3031
3032 return ret;
3033}
3034
3035std::vector<AddedNodeInfo> CConnman::GetAddedNodeInfo(bool include_connected) const
3036{
3038
3039 std::vector<AddedNodeInfo> ret;
3040
3041 std::list<AddedNodeParams> lAddresses(0);
3042 {
3044 ret.reserve(m_added_node_params.size());
3045 std::copy(m_added_node_params.cbegin(), m_added_node_params.cend(), std::back_inserter(lAddresses));
3046 }
3047
3048
3049 // Build a map of all already connected addresses (by IP:port and by name) to inbound/outbound and resolved CService
3050 std::map<CService, bool> mapConnected;
3051 std::map<std::string, std::pair<bool, CService>> mapConnectedByName;
3052 {
3054 for (const CNode* pnode : m_nodes) {
3055 if (pnode->addr.IsValid()) {
3056 mapConnected[pnode->addr] = pnode->IsInboundConn();
3057 }
3058 std::string addrName{pnode->m_addr_name};
3059 if (!addrName.empty()) {
3060 mapConnectedByName[std::move(addrName)] = std::make_pair(pnode->IsInboundConn(), static_cast<const CService&>(pnode->addr));
3061 }
3062 }
3063 }
3064
3065 for (const auto& addr : lAddresses) {
3066 CService service{MaybeFlipIPv6toCJDNS(LookupNumeric(addr.m_added_node, GetDefaultPort(addr.m_added_node)))};
3067 AddedNodeInfo addedNode{addr, CService(), false, false};
3068 if (service.IsValid()) {
3069 // strAddNode is an IP:port
3070 auto it = mapConnected.find(service);
3071 if (it != mapConnected.end()) {
3072 if (!include_connected) {
3073 continue;
3074 }
3075 addedNode.resolvedAddress = service;
3076 addedNode.fConnected = true;
3077 addedNode.fInbound = it->second;
3078 }
3079 } else {
3080 // strAddNode is a name
3081 auto it = mapConnectedByName.find(addr.m_added_node);
3082 if (it != mapConnectedByName.end()) {
3083 if (!include_connected) {
3084 continue;
3085 }
3086 addedNode.resolvedAddress = it->second.second;
3087 addedNode.fConnected = true;
3088 addedNode.fInbound = it->second.first;
3089 }
3090 }
3091 ret.emplace_back(std::move(addedNode));
3092 }
3093
3094 return ret;
3095}
3096
3098{
3102
3103 while (true)
3104 {
3106 std::vector<AddedNodeInfo> vInfo = GetAddedNodeInfo(/*include_connected=*/false);
3107 bool tried = false;
3108 for (const AddedNodeInfo& info : vInfo) {
3109 if (!grant) {
3110 // If we've used up our semaphore and need a new one, let's not wait here since while we are waiting
3111 // the addednodeinfo state might change.
3112 break;
3113 }
3114 tried = true;
3116 /*fCountFailure=*/false,
3117 /*grant_outbound=*/std::move(grant),
3118 /*pszDest=*/info.m_params.m_added_node.c_str(),
3119 /*conn_type=*/ConnectionType::MANUAL,
3120 /*use_v2transport=*/info.m_params.m_use_v2transport,
3121 /*proxy_override=*/std::nullopt);
3122 if (!m_interrupt_net->sleep_for(500ms)) return;
3123 grant = CountingSemaphoreGrant<>(*semAddnode, /*fTry=*/true);
3124 }
3125 // See if any reconnections are desired.
3127 // Retry every 60 seconds if a connection was attempted, otherwise two seconds
3128 if (!m_interrupt_net->sleep_for(tried ? 60s : 2s)) {
3129 return;
3130 }
3131 }
3132}
3133
3134// if successful, this moves the passed grant to the constructed node
3136 bool fCountFailure,
3138 const char* pszDest,
3139 ConnectionType conn_type,
3140 bool use_v2transport,
3141 const std::optional<Proxy>& proxy_override)
3142{
3145 assert(conn_type != ConnectionType::INBOUND);
3146
3147 //
3148 // Initiate outbound network connection
3149 //
3150 if (m_interrupt_net->interrupted()) {
3151 return false;
3152 }
3153 if (!fNetworkActive) {
3154 return false;
3155 }
3156 if (!pszDest) {
3157 bool banned_or_discouraged = m_banman && (m_banman->IsDiscouraged(addrConnect) || m_banman->IsBanned(addrConnect));
3159 return false;
3160 }
3161 } else if (AlreadyConnectedToHost(pszDest)) {
3162 return false;
3163 }
3164
3165 CNode* pnode = ConnectNode(addrConnect, pszDest, fCountFailure, conn_type, use_v2transport, proxy_override);
3166
3167 if (!pnode)
3168 return false;
3169 pnode->grantOutbound = std::move(grant_outbound);
3170
3171 m_msgproc->InitializeNode(*pnode, m_local_services);
3172 {
3174 m_nodes.push_back(pnode);
3175
3176 // update connection count by network
3177 if (pnode->IsManualOrFullOutboundConn()) ++m_network_conn_counts[pnode->addr.GetNetwork()];
3178 }
3179
3181 pnode->GetId(),
3182 pnode->m_addr_name.c_str(),
3183 pnode->ConnectionTypeAsString().c_str(),
3184 pnode->ConnectedThroughNetwork(),
3186
3187 return true;
3188}
3189
3190std::optional<Network> CConnman::PrivateBroadcast::PickNetwork(std::optional<Proxy>& proxy) const
3191{
3193 std::optional<Proxy> clearnet_proxy;
3194 proxy.reset();
3197
3199 if (clearnet_proxy.has_value()) {
3201 nets.push_back(NET_IPV4);
3202 }
3204 nets.push_back(NET_IPV6);
3205 }
3206 }
3207 }
3209 nets.push_back(NET_I2P);
3210 }
3211
3212 if (nets.empty()) {
3213 return std::nullopt;
3214 }
3215
3216 const Network net{nets[FastRandomContext{}.randrange(nets.size())]};
3217 if (net == NET_IPV4 || net == NET_IPV6) {
3218 proxy = clearnet_proxy;
3219 }
3220 return net;
3221}
3222
3224{
3225 return m_num_to_open;
3226}
3227
3229{
3230 m_num_to_open += n;
3231 m_num_to_open.notify_all();
3232}
3233
3235{
3236 size_t current_value{m_num_to_open.load()};
3237 size_t new_value;
3238 do {
3239 new_value = current_value > n ? current_value - n : 0;
3240 } while (!m_num_to_open.compare_exchange_strong(current_value, new_value));
3241 return new_value;
3242}
3243
3245{
3246 m_num_to_open.wait(0);
3247}
3248
3250{
3251 if (m_outbound_tor_ok_at_least_once.load()) {
3252 if (const auto tor_proxy = GetProxy(NET_ONION)) {
3253 return tor_proxy;
3254 }
3255 }
3256 return std::nullopt;
3257}
3258
3260
3262{
3264
3266
3267 while (!flagInterruptMsgProc)
3268 {
3269 bool fMoreWork = false;
3270
3271 {
3272 // Randomize the order in which we process messages from/to our peers.
3273 // This prevents attacks in which an attacker exploits having multiple
3274 // consecutive connections in the m_nodes list.
3275 const NodesSnapshot snap{*this, /*shuffle=*/true};
3276
3277 for (CNode* pnode : snap.Nodes()) {
3278 if (pnode->fDisconnect)
3279 continue;
3280
3281 // Receive messages
3282 bool fMoreNodeWork{m_msgproc->ProcessMessages(*pnode, flagInterruptMsgProc)};
3283 fMoreWork |= (fMoreNodeWork && !pnode->fPauseSend);
3285 return;
3286 // Send messages
3287 m_msgproc->SendMessages(*pnode);
3288
3290 return;
3291 }
3292 }
3293
3294 WAIT_LOCK(mutexMsgProc, lock);
3295 if (!fMoreWork) {
3296 condMsgProc.wait_until(lock, std::chrono::steady_clock::now() + std::chrono::milliseconds(100), [this]() EXCLUSIVE_LOCKS_REQUIRED(mutexMsgProc) { return fMsgProcWake; });
3297 }
3298 fMsgProcWake = false;
3299 }
3300}
3301
3303{
3305
3306 static constexpr auto err_wait_begin = 1s;
3307 static constexpr auto err_wait_cap = 5min;
3308 auto err_wait = err_wait_begin;
3309
3310 bool advertising_listen_addr = false;
3312
3313 auto SleepOnFailure = [&]() {
3314 m_interrupt_net->sleep_for(err_wait);
3315 if (err_wait < err_wait_cap) {
3316 err_wait += 1s;
3317 }
3318 };
3319
3320 while (!m_interrupt_net->interrupted()) {
3321
3322 if (!m_i2p_sam_session->Listen(conn)) {
3323 if (advertising_listen_addr && conn.me.IsValid()) {
3324 RemoveLocal(conn.me);
3326 }
3328 continue;
3329 }
3330
3334 }
3335
3336 if (!m_i2p_sam_session->Accept(conn)) {
3338 continue;
3339 }
3340
3342
3344 }
3345}
3346
3348{
3351
3352 size_t addrman_num_bad_addresses{0};
3353 while (!m_interrupt_net->interrupted()) {
3354
3355 if (!fNetworkActive) {
3356 m_interrupt_net->sleep_for(5s);
3357 continue;
3358 }
3359
3360 CountingSemaphoreGrant<> conn_max_grant{m_private_broadcast.m_sem_conn_max}; // Would block if too many are opened.
3361
3363
3364 if (m_interrupt_net->interrupted()) {
3365 break;
3366 }
3367
3368 std::optional<Proxy> proxy;
3369 const std::optional<Network> net{m_private_broadcast.PickNetwork(proxy)};
3370 if (!net.has_value()) {
3371 LogWarning("Unable to open -privatebroadcast connections: neither Tor nor I2P is reachable");
3372 m_interrupt_net->sleep_for(5s);
3373 continue;
3374 }
3375
3376 const auto [addr, _] = addrman.get().Select(/*new_only=*/false, {net.value()});
3377
3378 if (!addr.IsValid() || IsLocal(addr)) {
3380 if (addrman_num_bad_addresses > 100) {
3381 LogDebug(BCLog::PRIVBROADCAST, "Connections needed but addrman keeps returning bad addresses, will retry");
3382 m_interrupt_net->sleep_for(500ms);
3383 }
3384 continue;
3385 }
3387
3388 auto target_str{addr.ToStringAddrPort()};
3389 if (proxy.has_value()) {
3390 target_str += " through the proxy at " + proxy->ToString();
3391 }
3392
3393 const bool use_v2transport(addr.nServices & GetLocalServices() & NODE_P2P_V2);
3394
3395 if (OpenNetworkConnection(addr,
3396 /*fCountFailure=*/true,
3397 std::move(conn_max_grant),
3398 /*pszDest=*/nullptr,
3401 proxy)) {
3403 LogDebug(BCLog::PRIVBROADCAST, "Socket connected to %s; remaining connections to open: %d", target_str, remaining);
3404 } else {
3405 const size_t remaining{m_private_broadcast.NumToOpen()};
3406 if (remaining == 0) {
3407 LogDebug(BCLog::PRIVBROADCAST, "Failed to connect to %s, will not retry, no more connections needed", target_str);
3408 } else {
3409 LogDebug(BCLog::PRIVBROADCAST, "Failed to connect to %s, will retry to a different address; remaining connections to open: %d", target_str, remaining);
3410 m_interrupt_net->sleep_for(100ms); // Prevent busy loop if OpenNetworkConnection() fails fast repeatedly.
3411 }
3412 }
3413 }
3414}
3415
3417{
3418 int nOne = 1;
3419
3420 // Create socket for listening for incoming connections
3422 socklen_t len = sizeof(sockaddr);
3423 if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
3424 {
3425 strError = Untranslated(strprintf("Bind address family for %s not supported", addrBind.ToStringAddrPort()));
3426 LogError("%s\n", strError.original);
3427 return false;
3428 }
3429
3430 std::unique_ptr<Sock> sock = CreateSock(addrBind.GetSAFamily(), SOCK_STREAM, IPPROTO_TCP);
3431 if (!sock) {
3432 strError = Untranslated(strprintf("Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError())));
3433 LogError("%s\n", strError.original);
3434 return false;
3435 }
3436
3437#ifdef WIN32
3438 // Prevent another process from binding to the same address and port,
3439 // which could allow it to intercept incoming P2P connections. On Windows,
3440 // SO_REUSEADDR is NOT exclusive, so another process running under the same
3441 // user account could bind to the same port.
3442 if (sock->SetSockOpt(SOL_SOCKET, SO_EXCLUSIVEADDRUSE, &nOne, sizeof(int)) == SOCKET_ERROR) {
3443 strError = Untranslated(strprintf("Error setting SO_EXCLUSIVEADDRUSE on socket: %s", NetworkErrorString(WSAGetLastError())));
3444 LogError("%s\n", strError.original);
3445 return false;
3446 }
3447#else
3448 // Allow binding if the port is still in TIME_WAIT state after
3449 // the program was closed and restarted.
3450 if (sock->SetSockOpt(SOL_SOCKET, SO_REUSEADDR, &nOne, sizeof(int)) == SOCKET_ERROR) {
3451 strError = Untranslated(strprintf("Error setting SO_REUSEADDR on socket: %s, continuing anyway", NetworkErrorString(WSAGetLastError())));
3452 LogInfo("%s\n", strError.original);
3453 }
3454#endif
3455
3456 // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
3457 // and enable it by default or not. Try to enable it, if possible.
3458 if (addrBind.IsIPv6()) {
3459#ifdef IPV6_V6ONLY
3460 if (sock->SetSockOpt(IPPROTO_IPV6, IPV6_V6ONLY, &nOne, sizeof(int)) == SOCKET_ERROR) {
3461 strError = Untranslated(strprintf("Error setting IPV6_V6ONLY on socket: %s, continuing anyway", NetworkErrorString(WSAGetLastError())));
3462 LogInfo("%s\n", strError.original);
3463 }
3464#endif
3465#ifdef WIN32
3467 if (sock->SetSockOpt(IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, &nProtLevel, sizeof(int)) == SOCKET_ERROR) {
3468 strError = Untranslated(strprintf("Error setting IPV6_PROTECTION_LEVEL on socket: %s, continuing anyway", NetworkErrorString(WSAGetLastError())));
3469 LogInfo("%s\n", strError.original);
3470 }
3471#endif
3472 }
3473
3474 if (sock->Bind(reinterpret_cast<struct sockaddr*>(&sockaddr), len) == SOCKET_ERROR) {
3475 int nErr = WSAGetLastError();
3476 if (nErr == WSAEADDRINUSE)
3477 strError = strprintf(_("Unable to bind to %s on this computer. %s is probably already running."), addrBind.ToStringAddrPort(), CLIENT_NAME);
3478 else
3479 strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToStringAddrPort(), NetworkErrorString(nErr));
3480 LogError("%s\n", strError.original);
3481 return false;
3482 }
3483 LogInfo("Bound to %s\n", addrBind.ToStringAddrPort());
3484
3485 // Listen for incoming connections
3486 if (sock->Listen(SOMAXCONN) == SOCKET_ERROR)
3487 {
3488 strError = strprintf(_("Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError()));
3489 LogError("%s\n", strError.original);
3490 return false;
3491 }
3492
3493 vhListenSocket.emplace_back(std::move(sock), permissions);
3494 return true;
3495}
3496
3498{
3499 if (!fDiscover)
3500 return;
3501
3502 for (const CNetAddr &addr: GetLocalAddresses()) {
3503 if (AddLocal(addr, LOCAL_IF) && fLogIPs) {
3504 LogInfo("%s: %s\n", __func__, addr.ToStringAddr());
3505 }
3506 }
3507}
3508
3510{
3511 LogInfo("%s: %s\n", __func__, active);
3512
3513 if (fNetworkActive == active) {
3514 return;
3515 }
3516
3517 if (!active) {
3518 // Remember the current block-relay-only peers so they can be retried
3519 // once the network is re-enabled, or dumped at shutdown. Keep any
3520 // not-yet-tried anchors if there are no such peers.
3523 // Keep the oldest peers, as when saving anchors at shutdown.
3525 }
3526 if (!anchors.empty()) {
3528 m_anchors = std::move(anchors);
3529 }
3530 }
3531
3532 fNetworkActive = active;
3533
3534 if (m_client_interface) {
3535 m_client_interface->NotifyNetworkActiveChanged(fNetworkActive);
3536 }
3537}
3538
3542 const NetGroupManager& netgroupman,
3543 const CChainParams& params,
3544 bool network_active,
3545 std::shared_ptr<CThreadInterrupt> interrupt_net)
3547 , m_netgroupman{netgroupman}
3548 , nSeed0(nSeed0In)
3549 , nSeed1(nSeed1In)
3551 , m_params(params)
3552{
3553 SetTryNewOutboundPeer(false);
3554
3558}
3559
3561{
3562 return nLastNodeId.fetch_add(1, std::memory_order_relaxed);
3563}
3564
3569
3570uint16_t CConnman::GetDefaultPort(const std::string& addr) const
3571{
3572 CNetAddr a;
3573 return a.SetSpecial(addr) ? GetDefaultPort(a.GetNetwork()) : m_params.GetDefaultPort();
3574}
3575
3577{
3578 const CService addr{MaybeFlipIPv6toCJDNS(addr_)};
3579
3581 if (!BindListenPort(addr, strError, permissions)) {
3584 }
3585 return false;
3586 }
3587
3589 AddLocal(addr, LOCAL_BIND);
3590 }
3591
3592 return true;
3593}
3594
3595bool CConnman::InitBinds(const Options& options)
3596{
3597 for (const auto& addrBind : options.vBinds) {
3599 return false;
3600 }
3601 }
3602 for (const auto& addrBind : options.vWhiteBinds) {
3603 if (!Bind(addrBind.m_service, BF_REPORT_ERROR, addrBind.m_flags)) {
3604 return false;
3605 }
3606 }
3607 for (const auto& addr_bind : options.onion_binds) {
3609 return false;
3610 }
3611 }
3612 if (options.bind_on_any) {
3613 // Don't consider errors to bind on IPv6 "::" fatal because the host OS
3614 // may not have IPv6 support and the user did not explicitly ask us to
3615 // bind on that.
3618
3619 struct in_addr inaddr_any;
3620 inaddr_any.s_addr = htonl(INADDR_ANY);
3621 const CService ipv4_any{inaddr_any, GetListenPort()}; // 0.0.0.0
3623 return false;
3624 }
3625 }
3626 return true;
3627}
3628
3630{
3633
3634 if (fListen && !InitBinds(connOptions)) {
3635 if (m_client_interface) {
3636 m_client_interface->ThreadSafeMessageBox(
3637 _("Failed to listen on any port. Use -listen=0 if you want this."),
3639 }
3640 return false;
3641 }
3642
3643 if (connOptions.m_i2p_accept_incoming) {
3644 if (const auto i2p_sam = GetProxy(NET_I2P)) {
3645 m_i2p_sam_session = std::make_unique<i2p::sam::Session>(gArgs.GetDataDirNet() / "i2p_private_key",
3647 }
3648 }
3649
3650 // Randomize the order in which we may query seednode to potentially prevent connecting to the same one every restart (and signal that we have restarted)
3651 std::vector<std::string> seed_nodes = connOptions.vSeedNodes;
3652 if (!seed_nodes.empty()) {
3653 std::shuffle(seed_nodes.begin(), seed_nodes.end(), FastRandomContext{});
3654 }
3655
3657 // Load addresses from anchors.dat
3662 }
3663 if (fNetworkActive) {
3664 LogInfo("%i block-relay-only anchors will be tried for connections.\n", m_anchors.size());
3665 }
3666 }
3667
3668 if (m_client_interface) {
3669 m_client_interface->InitMessage(_("Starting network threads…"));
3670 }
3671
3672 fAddressesInitialized = true;
3673
3674 if (semOutbound == nullptr) {
3675 // initialize semaphore
3676 semOutbound = std::make_unique<std::counting_semaphore<>>(std::min(m_max_automatic_outbound, m_max_automatic_connections));
3677 }
3678 if (semAddnode == nullptr) {
3679 // initialize semaphore
3680 semAddnode = std::make_unique<std::counting_semaphore<>>(m_max_addnode);
3681 }
3682
3683 //
3684 // Start threads
3685 //
3687 m_interrupt_net->reset();
3688 flagInterruptMsgProc = false;
3689
3690 {
3692 fMsgProcWake = false;
3693 }
3694
3695 // Send and receive from sockets, accept connections
3696 threadSocketHandler = std::thread(&util::TraceThread, "net", [this] { ThreadSocketHandler(); });
3697
3698 if (!gArgs.GetBoolArg("-dnsseed", DEFAULT_DNSSEED))
3699 LogInfo("DNS seeding disabled\n");
3700 else
3701 threadDNSAddressSeed = std::thread(&util::TraceThread, "dnsseed", [this] { ThreadDNSAddressSeed(); });
3702
3703 // Initiate manual connections
3704 threadOpenAddedConnections = std::thread(&util::TraceThread, "addcon", [this] { ThreadOpenAddedConnections(); });
3705
3706 if (connOptions.m_use_addrman_outgoing && !connOptions.m_specified_outgoing.empty()) {
3707 if (m_client_interface) {
3708 m_client_interface->ThreadSafeMessageBox(
3709 _("Cannot provide specific connections and have addrman find outgoing connections at the same time."),
3711 }
3712 return false;
3713 }
3714 if (connOptions.m_use_addrman_outgoing || !connOptions.m_specified_outgoing.empty()) {
3715 threadOpenConnections = std::thread(
3716 &util::TraceThread, "opencon",
3717 [this, connect = connOptions.m_specified_outgoing, seed_nodes = std::move(seed_nodes)] { ThreadOpenConnections(connect, seed_nodes); });
3718 }
3719
3720 // Process messages
3721 threadMessageHandler = std::thread(&util::TraceThread, "msghand", [this] { ThreadMessageHandler(); });
3722
3723 if (m_i2p_sam_session) {
3725 std::thread(&util::TraceThread, "i2paccept", [this] { ThreadI2PAcceptIncoming(); });
3726 }
3727
3728 if (gArgs.GetBoolArg("-privatebroadcast", DEFAULT_PRIVATE_BROADCAST)) {
3730 std::thread(&util::TraceThread, "privbcast", [this] { ThreadPrivateBroadcast(); });
3731 }
3732
3733 // Dump network addresses
3734 scheduler.scheduleEvery([this] { DumpAddresses(); }, DUMP_PEERS_INTERVAL);
3735
3736 // Run the ASMap Health check once and then schedule it to run every 24h.
3737 if (m_netgroupman.UsingASMap()) {
3740 }
3741
3742 return true;
3743}
3744
3746{
3747public:
3748 CNetCleanup() = default;
3749
3751 {
3752#ifdef WIN32
3753 // Shutdown Windows Sockets
3754 WSACleanup();
3755#endif
3756 }
3757};
3759
3761{
3762 {
3764 flagInterruptMsgProc = true;
3765 }
3766 condMsgProc.notify_all();
3767
3768 (*m_interrupt_net)();
3770
3771 if (semOutbound) {
3772 for (int i=0; i<m_max_automatic_outbound; i++) {
3773 semOutbound->release();
3774 }
3775 }
3776
3777 if (semAddnode) {
3778 for (int i=0; i<m_max_addnode; i++) {
3779 semAddnode->release();
3780 }
3781 }
3782
3784 m_private_broadcast.NumToOpenAdd(1); // Just unblock NumToOpenWait() to be able to continue with shutdown.
3785}
3786
3788{
3789 if (threadPrivateBroadcast.joinable()) {
3791 }
3792 if (threadI2PAcceptIncoming.joinable()) {
3794 }
3795 if (threadMessageHandler.joinable())
3796 threadMessageHandler.join();
3797 if (threadOpenConnections.joinable())
3798 threadOpenConnections.join();
3799 if (threadOpenAddedConnections.joinable())
3801 if (threadDNSAddressSeed.joinable())
3802 threadDNSAddressSeed.join();
3803 if (threadSocketHandler.joinable())
3804 threadSocketHandler.join();
3805}
3806
3808{
3812
3814 DumpAddresses();
3815 fAddressesInitialized = false;
3816
3818 // Anchor connections are only dumped during clean shutdown.
3819 std::vector<CAddress> anchors_to_dump = GetCurrentBlockRelayOnlyConns();
3820 {
3822 if (!fNetworkActive && !m_anchors.empty()) {
3824 }
3825 }
3828 }
3830 }
3831 }
3832
3833 // Delete peer connections.
3834 std::vector<CNode*> nodes;
3836 for (CNode* pnode : nodes) {
3837 LogDebug(BCLog::NET, "Stopping node, %s", pnode->DisconnectMsg());
3838 pnode->CloseSocketDisconnect();
3840 }
3841
3844 }
3845 m_nodes_disconnected.clear();
3847 vhListenSocket.clear();
3848 semOutbound.reset();
3849 semAddnode.reset();
3850}
3851
3853{
3854 assert(pnode);
3855 m_msgproc->FinalizeNode(*pnode);
3856 delete pnode;
3857}
3858
3860{
3861 Interrupt();
3862 Stop();
3863}
3864
3865std::vector<CAddress> CConnman::GetAddressesUnsafe(size_t max_addresses, size_t max_pct, std::optional<Network> network, const bool filtered) const
3866{
3867 std::vector<CAddress> addresses = addrman.get().GetAddr(max_addresses, max_pct, network, filtered);
3868 if (m_banman) {
3869 std::erase_if(addresses, [this](const CAddress& addr) { return m_banman->IsDiscouraged(addr) || m_banman->IsBanned(addr); });
3870 }
3871 return addresses;
3872}
3873
3874std::vector<CAddress> CConnman::GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct)
3875{
3876 uint64_t network_id = requestor.m_network_key;
3879 CachedAddrResponse& cache_entry = r.first->second;
3880 if (cache_entry.m_cache_entry_expiration < current_time) { // If emplace() added new one it has expiration 0.
3882 // Choosing a proper cache lifetime is a trade-off between the privacy leak minimization
3883 // and the usefulness of ADDR responses to honest users.
3884 //
3885 // Longer cache lifetime makes it more difficult for an attacker to scrape
3886 // enough AddrMan data to maliciously infer something useful.
3887 // By the time an attacker scraped enough AddrMan records, most of
3888 // the records should be old enough to not leak topology info by
3889 // e.g. analyzing real-time changes in timestamps.
3890 //
3891 // It takes only several hundred requests to scrape everything from an AddrMan containing 100,000 nodes,
3892 // so ~24 hours of cache lifetime indeed makes the data less inferable by the time
3893 // most of it could be scraped (considering that timestamps are updated via
3894 // ADDR self-announcements and when nodes communicate).
3895 // We also should be robust to those attacks which may not require scraping *full* victim's AddrMan
3896 // (because even several timestamps of the same handful of nodes may leak privacy).
3897 //
3898 // On the other hand, longer cache lifetime makes ADDR responses
3899 // outdated and less useful for an honest requestor, e.g. if most nodes
3900 // in the ADDR response are no longer active.
3901 //
3902 // However, the churn in the network is known to be rather low. Since we consider
3903 // nodes to be "terrible" (see IsTerrible()) if the timestamps are older than 30 days,
3904 // max. 24 hours of "penalty" due to cache shouldn't make any meaningful difference
3905 // in terms of the freshness of the response.
3906 cache_entry.m_cache_entry_expiration = current_time +
3907 21h + FastRandomContext().randrange<std::chrono::microseconds>(6h);
3908 }
3909 return cache_entry.m_addrs_response_cache;
3910}
3911
3913{
3915 const bool resolved_is_valid{resolved.IsValid()};
3916
3918 for (const auto& it : m_added_node_params) {
3919 if (add.m_added_node == it.m_added_node || (resolved_is_valid && resolved == LookupNumeric(it.m_added_node, GetDefaultPort(it.m_added_node)))) return false;
3920 }
3921
3922 m_added_node_params.push_back(add);
3923 return true;
3924}
3925
3926bool CConnman::RemoveAddedNode(std::string_view node)
3927{
3929 for (auto it = m_added_node_params.begin(); it != m_added_node_params.end(); ++it) {
3930 if (node == it->m_added_node) {
3931 m_added_node_params.erase(it);
3932 return true;
3933 }
3934 }
3935 return false;
3936}
3937
3939{
3941 const std::string addr_str{addr.ToStringAddr()};
3942 const std::string addr_port_str{addr.ToStringAddrPort()};
3944 return (m_added_node_params.size() < 24 // bound the query to a reasonable limit
3945 && std::any_of(m_added_node_params.cbegin(), m_added_node_params.cend(),
3946 [&](const auto& p) { return p.m_added_node == addr_str || p.m_added_node == addr_port_str; }));
3947}
3948
3950{
3952 if (flags == ConnectionDirection::Both) // Shortcut if we want total
3953 return m_nodes.size();
3954
3955 int nNum = 0;
3956 for (const auto& pnode : m_nodes) {
3957 if (flags & (pnode->IsInboundConn() ? ConnectionDirection::In : ConnectionDirection::Out)) {
3958 nNum++;
3959 }
3960 }
3961
3962 return nNum;
3963}
3964
3965
3966std::map<CNetAddr, LocalServiceInfo> CConnman::getNetLocalAddresses() const
3967{
3969 return mapLocalHost;
3970}
3971
3973{
3974 return m_netgroupman.GetMappedAS(addr);
3975}
3976
3977void CConnman::GetNodeStats(std::vector<CNodeStats>& vstats) const
3978{
3980
3981 vstats.clear();
3983 vstats.reserve(m_nodes.size());
3984 for (CNode* pnode : m_nodes) {
3985 vstats.emplace_back();
3986 pnode->CopyStats(vstats.back());
3987 vstats.back().m_mapped_as = GetMappedAS(pnode->addr);
3988 }
3989}
3990
3991bool CConnman::DisconnectNode(std::string_view strNode)
3992{
3994 auto it = std::ranges::find_if(m_nodes, [&strNode](CNode* node) { return node->m_addr_name == strNode; });
3995 if (it != m_nodes.end()) {
3996 CNode* node{*it};
3997 LogDebug(BCLog::NET, "disconnect by address%s match, %s", (fLogIPs ? strprintf("=%s", strNode) : ""), node->DisconnectMsg());
3998 node->fDisconnect = true;
3999 return true;
4000 }
4001 return false;
4002}
4003
4005{
4007 bool disconnected = false;
4009 for (CNode* pnode : m_nodes) {
4010 if (subnet.Match(pnode->addr) && (disconnect_private_broadcast || !pnode->IsPrivateBroadcastConn())) {
4011 LogDebug(BCLog::NET, "disconnect by subnet%s match, %s", (fLogIPs ? strprintf("=%s", subnet.ToString()) : ""), pnode->DisconnectMsg());
4012 pnode->fDisconnect = true;
4013 disconnected = true;
4014 }
4015 }
4016 return disconnected;
4017}
4018
4020{
4022 return DisconnectNode(CSubNet(addr));
4023}
4024
4026{
4028 for(CNode* pnode : m_nodes) {
4029 if (id == pnode->GetId()) {
4030 LogDebug(BCLog::NET, "disconnect by id, %s", pnode->DisconnectMsg());
4031 pnode->fDisconnect = true;
4032 return true;
4033 }
4034 }
4035 return false;
4036}
4037
4039{
4040 nTotalBytesRecv += bytes;
4041}
4042
4044{
4047
4048 nTotalBytesSent += bytes;
4049
4050 const auto now = GetTime<std::chrono::seconds>();
4052 {
4053 // timeframe expired, reset cycle
4056 }
4057
4059}
4060
4067
4068std::chrono::seconds CConnman::GetMaxOutboundTimeframe() const
4069{
4070 return MAX_UPLOAD_TIMEFRAME;
4071}
4072
4079
4081{
4083
4084 if (nMaxOutboundLimit == 0)
4085 return 0s;
4086
4087 if (nMaxOutboundCycleStartTime.count() == 0)
4088 return MAX_UPLOAD_TIMEFRAME;
4089
4090 const std::chrono::seconds cycleEndTime = nMaxOutboundCycleStartTime + MAX_UPLOAD_TIMEFRAME;
4091 const auto now = GetTime<std::chrono::seconds>();
4092 return (cycleEndTime < now) ? 0s : cycleEndTime - now;
4093}
4094
4096{
4099 if (nMaxOutboundLimit == 0)
4100 return false;
4101
4103 {
4104 // keep a large enough buffer to at least relay each block once
4105 const std::chrono::seconds timeLeftInCycle = GetMaxOutboundTimeLeftInCycle_();
4106 const uint64_t buffer = timeLeftInCycle / std::chrono::minutes{10} * MAX_BLOCK_SERIALIZED_SIZE;
4108 return true;
4109 }
4111 return true;
4112
4113 return false;
4114}
4115
4125
4130
4137
4142
4143static util::NotNullUniquePtr<Transport> MakeTransport(NodeId id, bool use_v2transport, bool inbound) noexcept
4144{
4145 if (use_v2transport) {
4146 return util::NotNull{std::make_unique<V2Transport>(id, /*initiating=*/!inbound)};
4147 } else {
4148 return util::NotNull{std::make_unique<V1Transport>(id)};
4149 }
4150}
4151
4153 std::shared_ptr<Sock> sock,
4154 const CAddress& addrIn,
4157 const CService& addrBindIn,
4158 const std::string& addrNameIn,
4160 bool inbound_onion,
4163 : m_transport{MakeTransport(idIn, node_opts.use_v2transport, conn_type_in == ConnectionType::INBOUND)},
4164 m_permission_flags{node_opts.permission_flags},
4165 m_sock{sock},
4166 m_connected{NodeClock::now()},
4167 m_proxy_override{std::move(node_opts.proxy_override)},
4168 addr{addrIn},
4169 addrBind{addrBindIn},
4170 m_addr_name{addrNameIn.empty() ? addr.ToStringAddrPort() : addrNameIn},
4171 m_dest(addrNameIn),
4172 m_inbound_onion{inbound_onion},
4173 m_prefer_evict{node_opts.prefer_evict},
4174 nKeyedNetGroup{nKeyedNetGroupIn},
4175 m_network_key{network_key},
4176 m_conn_type{conn_type_in},
4177 id{idIn},
4178 nLocalHostNonce{nLocalHostNonceIn},
4179 m_recv_flood_size{node_opts.recv_flood_size},
4180 m_i2p_sam_session{std::move(node_opts.i2p_sam_session)}
4181{
4183
4184 for (const auto& msg : ALL_NET_MESSAGE_TYPES) {
4185 mapRecvBytesPerMsgType[msg] = 0;
4186 }
4187 mapRecvBytesPerMsgType[NET_MESSAGE_TYPE_OTHER] = 0;
4188
4189 if (fLogIPs) {
4190 LogDebug(BCLog::NET, "Added connection to %s peer=%d\n", m_addr_name, id);
4191 } else {
4192 LogDebug(BCLog::NET, "Added connection peer=%d\n", id);
4193 }
4194}
4195
4197{
4199
4200 size_t nSizeAdded = 0;
4201 for (const auto& msg : vRecvMsg) {
4202 // vRecvMsg contains only completed CNetMessage
4203 // the single possible partially deserialized message are held by TransportDeserializer
4204 nSizeAdded += msg.GetMemoryUsage();
4205 }
4206
4211}
4212
4213std::optional<std::pair<CNetMessage, bool>> CNode::PollMessage()
4214{
4216 if (m_msg_process_queue.empty()) return std::nullopt;
4217
4218 std::list<CNetMessage> msgs;
4219 // Just take one message
4220 msgs.splice(msgs.begin(), m_msg_process_queue, m_msg_process_queue.begin());
4221 m_msg_process_queue_size -= msgs.front().GetMemoryUsage();
4223
4224 return std::make_pair(std::move(msgs.front()), !m_msg_process_queue.empty());
4225}
4226
4228{
4229 return pnode && pnode->fSuccessfullyConnected && !pnode->fDisconnect;
4230}
4231
4234static bool IsOutboundMessageAllowedInPrivateBroadcast(std::string_view type) noexcept
4235{
4236 return type == NetMsgType::VERSION ||
4237 type == NetMsgType::VERACK ||
4238 type == NetMsgType::INV ||
4239 type == NetMsgType::TX ||
4240 type == NetMsgType::PING;
4241}
4242
4244{
4246
4247 if (pnode->IsPrivateBroadcastConn() && !IsOutboundMessageAllowedInPrivateBroadcast(msg.m_type)) {
4248 LogDebug(BCLog::PRIVBROADCAST, "Omitting send of message '%s', %s", msg.m_type, pnode->LogPeer());
4249 return;
4250 }
4251
4252 if (!m_private_broadcast.m_outbound_tor_ok_at_least_once.load() && !pnode->IsInboundConn() &&
4253 pnode->addr.IsTor() && msg.m_type == NetMsgType::VERACK) {
4254 // If we are sending the peer VERACK that means we successfully sent
4255 // and received another message to/from that peer (VERSION).
4257 }
4258
4259 size_t nMessageSize = msg.data.size();
4260 LogDebug(BCLog::NET, "sending %s (%d bytes) peer=%d\n", msg.m_type, nMessageSize, pnode->GetId());
4261 if (m_capture_messages) {
4262 CaptureMessage(pnode->addr, msg.m_type, msg.data, /*is_incoming=*/false);
4263 }
4264
4266 pnode->GetId(),
4267 pnode->m_addr_name.c_str(),
4268 pnode->ConnectionTypeAsString().c_str(),
4269 msg.m_type.c_str(),
4270 msg.data.size(),
4271 msg.data.data()
4272 );
4273
4274 size_t nBytesSent = 0;
4275 {
4276 LOCK(pnode->cs_vSend);
4277 // Check if the transport still has unsent bytes, and indicate to it that we're about to
4278 // give it a message to send.
4279 const auto& [to_send, more, _msg_type] =
4280 pnode->m_transport->GetBytesToSend(/*have_next_message=*/true);
4281 const bool queue_was_empty{to_send.empty() && pnode->vSendMsg.empty()};
4282
4283 // Update memory usage of send buffer.
4284 pnode->m_send_memusage += msg.GetMemoryUsage();
4285 if (pnode->m_send_memusage + pnode->m_transport->GetSendMemoryUsage() > nSendBufferMaxSize && !pnode->fPauseSend) {
4286 pnode->m_pause_send_since = NodeClock::now();
4287 pnode->fPauseSend = true;
4288 }
4289 // Move message to vSendMsg queue.
4290 pnode->vSendMsg.push_back(std::move(msg));
4291
4292 // If there was nothing to send before, and there is now (predicted by the "more" value
4293 // returned by the GetBytesToSend call above), attempt "optimistic write":
4294 // because the poll/select loop may pause for SELECT_TIMEOUT_MILLISECONDS before actually
4295 // doing a send, try sending from the calling thread if the queue was empty before.
4296 // With a V1Transport, more will always be true here, because adding a message always
4297 // results in sendable bytes there, but with V2Transport this is not the case (it may
4298 // still be in the handshake).
4299 if (queue_was_empty && more) {
4300 std::tie(nBytesSent, std::ignore) = SocketSendData(*pnode);
4301 }
4302 }
4304}
4305
4306bool CConnman::ForNode(NodeId id, std::function<bool(CNode* pnode)> func)
4307{
4309
4310 CNode* found = nullptr;
4312 for (auto&& pnode : m_nodes) {
4313 if(pnode->GetId() == id) {
4314 found = pnode;
4315 break;
4316 }
4317 }
4318 return found != nullptr && NodeFullyConnected(found) && func(found);
4319}
4320
4325
4327{
4328 std::vector<unsigned char> vchNetGroup(m_netgroupman.GetGroup(address));
4329
4331}
4332
4334{
4338 while (true) {
4339 // Move first element of m_reconnections to todo (avoiding an allocation inside the lock).
4340 decltype(m_reconnections) todo;
4341 {
4343 if (m_reconnections.empty()) break;
4344 todo.splice(todo.end(), m_reconnections, m_reconnections.begin());
4345 }
4346
4347 auto& item = *todo.begin();
4348 OpenNetworkConnection(item.addr_connect,
4349 // We only reconnect if the first attempt to connect succeeded at
4350 // connection time, but then failed after the CNode object was
4351 // created. Since we already know connecting is possible, do not
4352 // count failure to reconnect.
4353 /*fCountFailure=*/false,
4354 std::move(item.grant),
4355 item.destination.empty() ? nullptr : item.destination.c_str(),
4356 item.conn_type,
4357 item.use_v2transport,
4358 item.proxy_override);
4359 }
4360}
4361
4363{
4364 const std::vector<CAddress> v4_addrs{GetAddressesUnsafe(/*max_addresses=*/0, /*max_pct=*/0, Network::NET_IPV4, /*filtered=*/false)};
4365 const std::vector<CAddress> v6_addrs{GetAddressesUnsafe(/*max_addresses=*/0, /*max_pct=*/0, Network::NET_IPV6, /*filtered=*/false)};
4366 std::vector<CNetAddr> clearnet_addrs;
4367 clearnet_addrs.reserve(v4_addrs.size() + v6_addrs.size());
4368 std::transform(v4_addrs.begin(), v4_addrs.end(), std::back_inserter(clearnet_addrs),
4369 [](const CAddress& addr) { return static_cast<CNetAddr>(addr); });
4370 std::transform(v6_addrs.begin(), v6_addrs.end(), std::back_inserter(clearnet_addrs),
4371 [](const CAddress& addr) { return static_cast<CNetAddr>(addr); });
4373}
4374
4375// Dump binary message to file, with timestamp.
4376static void CaptureMessageToFile(const CAddress& addr,
4377 const std::string& msg_type,
4378 std::span<const unsigned char> data,
4379 bool is_incoming)
4380{
4381 // Note: This function captures the message at the time of processing,
4382 // not at socket receive/send time.
4383 // This ensures that the messages are always in order from an application
4384 // layer (processing) perspective.
4386
4387 // Windows folder names cannot include a colon
4388 std::string clean_addr = addr.ToStringAddrPort();
4389 std::replace(clean_addr.begin(), clean_addr.end(), ':', '_');
4390
4391 fs::path base_path = gArgs.GetDataDirNet() / "message_capture" / fs::u8path(clean_addr);
4392 fs::create_directories(base_path);
4393
4394 fs::path path = base_path / (is_incoming ? "msgs_recv.dat" : "msgs_sent.dat");
4395 AutoFile f{fsbridge::fopen(path, "ab")};
4396
4397 ser_writedata64(f, now.count());
4398 f << std::span{msg_type};
4399 for (auto i = msg_type.length(); i < CMessageHeader::MESSAGE_TYPE_SIZE; ++i) {
4400 f << uint8_t{'\0'};
4401 }
4402 uint32_t size = data.size();
4403 ser_writedata32(f, size);
4404 f << data;
4405
4406 if (f.fclose() != 0) {
4407 throw std::ios_base::failure(
4408 strprintf("Error closing %s after write, file contents are likely incomplete", fs::PathToString(path)));
4409 }
4410}
4411
4412std::function<void(const CAddress& addr,
4413 const std::string& msg_type,
4414 std::span<const unsigned char> data,
4415 bool is_incoming)>
bool DumpPeerAddresses(const ArgsManager &args, const AddrMan &addr)
Definition addrdb.cpp:185
std::vector< CAddress > ReadAnchors(const fs::path &anchors_db_path)
Read the anchor IP address database (anchors.dat)
Definition addrdb.cpp:234
void DumpAnchors(const fs::path &anchors_db_path, const std::vector< CAddress > &anchors)
Dump the anchor IP address database (anchors.dat)
Definition addrdb.cpp:228
ArgsManager gArgs
Definition args.cpp:39
int ret
int flags
const CChainParams & Params()
Return the currently selected parameters.
#define Assume(val)
Assume is the identity function.
Definition check.h:131
Stochastic address manager.
Definition addrman.h:110
std::vector< std::string > GetArgs(const std::string &strArg) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return a vector of strings of the given argument.
Definition args.cpp:423
fs::path GetDataDirNet() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get data directory path with appended network identifier.
Definition args.cpp:329
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Definition args.h:318
bool GetBoolArg(const std::string &strArg, bool fDefault) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return boolean argument or default value.
Definition args.cpp:561
Non-refcounted RAII wrapper for FILE*.
Definition streams.h:395
bool Decrypt(std::span< const std::byte > input, std::span< const std::byte > aad, bool &ignore, std::span< std::byte > contents) noexcept
Decrypt a packet.
Definition bip324.cpp:100
std::span< const std::byte > GetSendGarbageTerminator() const noexcept
Get the Garbage Terminator to send.
Definition bip324.h:92
static constexpr unsigned GARBAGE_TERMINATOR_LEN
Definition bip324.h:25
unsigned DecryptLength(std::span< const std::byte > input) noexcept
Decrypt the length of a packet.
Definition bip324.cpp:89
std::span< const std::byte > GetSessionID() const noexcept
Get the Session ID.
Definition bip324.h:89
const EllSwiftPubKey & GetOurPubKey() const noexcept
Retrieve our public key.
Definition bip324.h:56
std::span< const std::byte > GetReceiveGarbageTerminator() const noexcept
Get the expected Garbage Terminator to receive.
Definition bip324.h:95
static constexpr unsigned LENGTH_LEN
Definition bip324.h:27
static constexpr unsigned EXPANSION
Definition bip324.h:29
void Initialize(const EllSwiftPubKey &their_pubkey, bool initiator, bool self_decrypt=false) noexcept
Initialize when the other side's public key is received.
Definition bip324.cpp:34
void Encrypt(std::span< const std::byte > contents, std::span< const std::byte > aad, bool ignore, std::span< std::byte > output) noexcept
Encrypt a packet.
Definition bip324.cpp:73
A CService with information about it as peer.
Definition protocol.h:387
ServiceFlags nServices
Serialized as uint64_t in V1, and as CompactSize in V2.
Definition protocol.h:479
NodeSeconds nTime
Always included in serialization. The behavior is unspecified if the value is not representable as ui...
Definition protocol.h:477
static constexpr SerParams V2_NETWORK
Definition protocol.h:429
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition chainparams.h:77
const MessageStartChars & MessageStart() const
Definition chainparams.h:90
uint16_t GetDefaultPort() const
Definition chainparams.h:91
const std::vector< std::string > & DNSSeeds() const
Return the list of hostnames to look up for DNS seeds.
const std::vector< uint8_t > & FixedSeeds() const
RAII helper to atomically create a copy of m_nodes and add a reference to each of the nodes.
Definition net.h:1875
std::atomic_bool m_outbound_tor_ok_at_least_once
Remember if we ever established at least one outbound connection to a Tor peer, including sending and...
Definition net.h:1226
void NumToOpenAdd(size_t n)
Increment the number of new connections of type ConnectionType::PRIVATE_BROADCAST to be opened by CCo...
Definition net.cpp:3228
std::optional< Proxy > ProxyForIPv4or6() const
Check if private broadcast can be done to IPv4 or IPv6 peers and if so via which proxy.
Definition net.cpp:3249
size_t NumToOpenSub(size_t n)
Decrement the number of new connections of type ConnectionType::PRIVATE_BROADCAST to be opened by CCo...
Definition net.cpp:3234
void NumToOpenWait() const
Wait for the number of needed connections to become greater than 0.
Definition net.cpp:3244
size_t NumToOpen() const
Get the pending number of connections to open.
Definition net.cpp:3223
std::optional< Network > PickNetwork(std::optional< Proxy > &proxy) const
Choose a network to open a connection to.
Definition net.cpp:3190
std::counting_semaphore m_sem_conn_max
Semaphore used to guard against opening too many connections.
Definition net.h:1232
void AcceptConnection(const ListenSocket &hListenSocket) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition net.cpp:1773
std::unordered_set< Network > GetReachableEmptyNetworks() const
Return reachable networks for which we have no addresses in addrman and therefore may require loading...
Definition net.cpp:2590
std::condition_variable condMsgProc
Definition net.h:1766
std::thread threadMessageHandler
Definition net.h:1787
nSendBufferMaxSize
Definition net.h:1139
void PerformReconnections() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Attempt reconnections, if m_reconnections non-empty.
Definition net.cpp:4333
bool MaybePickPreferredNetwork(std::optional< Network > &network) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Search for a "preferred" network, a reachable network to which we currently don't have any OUTBOUND_F...
Definition net.cpp:2609
std::reference_wrapper< AddrMan > addrman
Definition net.h:1660
void StopNodes() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Definition net.cpp:3807
void DisconnectNodes() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex
Definition net.cpp:1962
m_max_outbound_full_relay
Definition net.h:1130
void DeleteNode(CNode *pnode)
Definition net.cpp:3852
void ThreadI2PAcceptIncoming() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition net.cpp:3302
void Stop() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
whitelist_relay
Definition net.h:1159
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:1868
bool GetTryNewOutboundPeer() const
Definition net.cpp:2503
const bool use_v2transport(GetLocalServices() &NODE_P2P_V2)
class CConnman::PrivateBroadcast m_private_broadcast
uint16_t GetDefaultPort(Network net) const
Definition net.cpp:3565
bool AlreadyConnectedToAddress(const CNetAddr &addr) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Determine whether we're already connected to a given address.
Definition net.cpp:370
bool ShouldRunInactivityChecks(const CNode &node, NodeClock::time_point now) const
Return true if we should disconnect the peer for failing an inactivity check.
Definition net.cpp:2059
std::thread threadI2PAcceptIncoming
Definition net.h:1788
std::vector< CAddress > GetAddresses(CNode &requestor, size_t max_addresses, size_t max_pct)
Return addresses from the per-requestor cache.
Definition net.cpp:3874
void SetTryNewOutboundPeer(bool flag)
Definition net.cpp:2508
std::atomic< bool > flagInterruptMsgProc
Definition net.h:1768
void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition net.cpp:3760
std::map< CNetAddr, LocalServiceInfo > getNetLocalAddresses() const
Definition net.cpp:3966
void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition net.cpp:2325
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Return vector of current BLOCK_RELAY peers.
Definition net.cpp:3021
m_onion_binds
Definition net.h:1157
bool AlreadyConnectedToAddressPort(const CService &addr_port) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Determine whether we're already connected to a given address:port.
Definition net.cpp:364
NodeId GetNewNodeId()
Definition net.cpp:3560
m_capture_messages
Definition net.h:1160
std::atomic< NodeId > nLastNodeId
Definition net.h:1672
bool AlreadyConnectedToHost(std::string_view host) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Determine whether we're already connected to a given "host:port".
Definition net.cpp:358
m_max_automatic_outbound
Definition net.h:1132
void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition net.cpp:2316
bool OutboundTargetReached(bool historicalBlockServingLimit) const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
check if the outbound target is reached if param historicalBlockServingLimit is set true,...
Definition net.cpp:4095
void SocketHandlerListening(const Sock::EventsPerSock &events_per_sock) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Accept incoming connections, one from each read-ready listening socket.
Definition net.cpp:2290
uint64_t GetMaxOutboundTarget() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition net.cpp:4061
std::thread threadDNSAddressSeed
Definition net.h:1783
void ASMapHealthCheck()
Definition net.cpp:4362
bool AddConnection(const std::string &address, ConnectionType conn_type, bool use_v2transport) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Attempts to open a connection.
Definition net.cpp:1915
void SocketHandlerConnected(const std::vector< CNode * > &nodes, const Sock::EventsPerSock &events_per_sock) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
Do the read/write for connected sockets that are ready for IO.
Definition net.cpp:2188
const uint64_t nSeed1
Definition net.h:1761
void StartExtraBlockRelayPeers()
Definition net.cpp:2514
const NetGroupManager & m_netgroupman
Definition net.h:1661
m_banman
Definition net.h:1137
std::chrono::seconds GetMaxOutboundTimeframe() const
Definition net.cpp:4068
uint64_t CalculateKeyedNetGroup(const CNetAddr &ad) const
Definition net.cpp:4326
unsigned int nPrevNodeCount
Definition net.h:1673
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, std::optional< CNetAddr > addr, const std::vector< NetWhitelistPermissions > &ranges) const
Definition net.cpp:597
ServiceFlags GetLocalServices() const
Used to convey which local services we are offering peers during node connection.
Definition net.cpp:4138
bool AddNode(const AddedNodeParams &add) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition net.cpp:3912
std::vector< AddedNodeInfo > GetAddedNodeInfo(bool include_connected) const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition net.cpp:3035
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type, bool use_v2transport, const std::optional< Proxy > &proxy_override) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Open a new P2P connection.
Definition net.cpp:395
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 This t...
Definition net.h:1794
bool InitBinds(const Options &options)
Definition net.cpp:3595
vWhitelistedRangeOutgoing
Definition net.h:1147
void AddAddrFetch(const std::string &strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex)
Definition net.cpp:148
std::vector< ListenSocket > vhListenSocket
Definition net.h:1657
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition net.cpp:4321
Mutex m_total_bytes_sent_mutex
Definition net.h:1636
void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition net.cpp:3097
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
Definition net.cpp:3576
void SetNetworkActive(bool active) EXCLUSIVE_LOCKS_REQUIRED(!m_anchors_mutex
Definition net.cpp:3509
bool EvictTxPeerIfFull(std::optional< NodeId > protect_peer=std::nullopt) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
If we are at capacity for inbound tx-relay peers, attempt to evict one.
Definition net.cpp:2573
std::thread threadOpenConnections
Definition net.h:1786
void ThreadPrivateBroadcast() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Definition net.cpp:3347
uint32_t GetMappedAS(const CNetAddr &addr) const
Definition net.cpp:3972
void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition net.cpp:2475
Mutex m_addr_fetches_mutex
Definition net.h:1663
m_peer_connect_timeout
Definition net.h:1141
Mutex m_reconnections_mutex
Mutex protecting m_reconnections.
Definition net.h:1842
bool Start(CScheduler &scheduler, const Options &options) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
Definition net.cpp:3629
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition net.h:1761
m_local_services
Definition net.h:1128
std::chrono::seconds GetMaxOutboundTimeLeftInCycle_() const EXCLUSIVE_LOCKS_REQUIRED(m_total_bytes_sent_mutex)
returns the time left in the current max outbound cycle in case of no limit, it will always return 0
Definition net.cpp:4080
uint64_t GetTotalBytesRecv() const
Definition net.cpp:4126
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:1625
bool OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CountingSemaphoreGrant<> &&grant_outbound, const char *pszDest, ConnectionType conn_type, bool use_v2transport, const std::optional< Proxy > &proxy_override) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Open a new P2P connection and initialize it with the PeerManager at m_msgproc.
Definition net.cpp:3135
m_max_outbound_block_relay
Definition net.h:1131
static bool NodeFullyConnected(const CNode *pnode)
Definition net.cpp:4227
std::unique_ptr< std::counting_semaphore<> > semOutbound
Definition net.h:1718
m_client_interface
Definition net.h:1136
nReceiveFloodSize
Definition net.h:1140
const CChainParams & m_params
Definition net.h:1908
bool MultipleManualOrFullOutboundConns(Network net) const EXCLUSIVE_LOCKS_REQUIRED(m_nodes_mutex)
Definition net.cpp:2603
bool AddedNodesContain(const CAddress &addr) const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition net.cpp:3938
whitelist_forcerelay
Definition net.h:1158
bool InactivityCheck(const CNode &node, NodeClock::time_point now) const
Return true if the peer is inactive and should be disconnected.
Definition net.cpp:2064
std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition net.cpp:4073
const std::shared_ptr< CThreadInterrupt > m_interrupt_net
This is signaled when network activity should cease.
Definition net.h:1774
void CreateNodeFromAcceptedSocket(std::unique_ptr< Sock > &&sock, NetPermissionFlags permission_flags, const CService &addr_bind, const CService &addr) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Create a CNode object from a socket that has just been accepted and add the node to the m_nodes membe...
Definition net.cpp:1803
void ThreadOpenConnections(std::vector< std::string > connect, std::span< const std::string > seed_nodes) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition net.cpp:2627
bool AttemptToEvictConnection(bool evict_tx_relay_peer_only, std::optional< NodeId > protect_peer=std::nullopt) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Try to find an inbound connection to evict.
Definition net.cpp:1716
void GetNodeStats(std::vector< CNodeStats > &vstats) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition net.cpp:3977
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition net.cpp:4306
m_max_automatic_connections
Definition net.h:1129
std::thread threadPrivateBroadcast
Definition net.h:1789
m_msgproc
Definition net.h:1138
Mutex mutexMsgProc
Definition net.h:1767
m_max_inbound
Definition net.h:1133
bool RemoveAddedNode(std::string_view node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition net.cpp:3926
bool fAddressesInitialized
Definition net.h:1659
std::vector< CAddress > GetAddressesUnsafe(size_t max_addresses, size_t max_pct, std::optional< Network > network, bool filtered=true) const
Return randomly selected addresses.
Definition net.cpp:3865
void NotifyNumConnectionsChanged() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition net.cpp:2042
~CConnman()
Definition net.cpp:3859
void StopThreads()
Definition net.cpp:3787
int GetExtraBlockRelayCount() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition net.cpp:2557
std::thread threadOpenAddedConnections
Definition net.h:1785
bool DisconnectNode(std::string_view node) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition net.cpp:3991
Mutex m_added_nodes_mutex
Definition net.h:1668
vWhitelistedRangeIncoming
Definition net.h:1146
void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
Definition net.cpp:2305
void RecordBytesSent(uint64_t bytes) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition net.cpp:4043
void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Definition net.cpp:3261
Mutex m_unused_i2p_sessions_mutex
Mutex protecting m_i2p_sam_sessions.
Definition net.h:1828
uint64_t GetTotalBytesSent() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition net.cpp:4131
std::unique_ptr< std::counting_semaphore<> > semAddnode
Definition net.h:1719
Mutex m_anchors_mutex
Addresses that were saved during the previous clean shutdown or when the network was deactivated.
Definition net.h:1757
size_t GetNodeCount(ConnectionDirection) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition net.cpp:3949
void RecordBytesRecv(uint64_t bytes)
Definition net.cpp:4038
int GetExtraFullOutboundCount() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition net.cpp:2541
uint64_t GetOutboundTargetBytesLeft() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
response the bytes left in the current max outbound cycle in case of no limit, it will always respons...
Definition net.cpp:4116
void SocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Check connected and listening sockets for IO readiness and process them accordingly.
Definition net.cpp:2159
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition net.cpp:4243
int m_max_addnode
Definition net.h:1740
std::list< CNode * > m_nodes_disconnected
Definition net.h:1670
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
Definition net.h:1781
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:1703
bool CheckIncomingNonce(uint64_t nonce) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition net.cpp:376
Sock::EventsPerSock GenerateWaitSockets(std::span< CNode *const > nodes)
Generate a collection of sockets to check for IO readiness.
Definition net.cpp:2128
std::atomic< uint64_t > nTotalBytesRecv
Definition net.h:1637
std::atomic< bool > fNetworkActive
Definition net.h:1658
std::atomic_bool m_start_extra_block_relay_peers
flag for initiating extra block-relay-only peer connections.
Definition net.h:1800
m_use_addrman_outgoing
Definition net.h:1135
CConnman(uint64_t seed0, uint64_t seed1, AddrMan &addrman, const NetGroupManager &netgroupman, const CChainParams &params, bool network_active=true, std::shared_ptr< CThreadInterrupt > interrupt_net=std::make_shared< CThreadInterrupt >())
Definition net.cpp:3539
void DumpAddresses()
Definition net.cpp:2465
Mutex m_nodes_mutex
Definition net.h:1671
std::thread threadSocketHandler
Definition net.h:1784
m_max_inbound_full_relay
Definition net.h:1134
nMaxOutboundLimit
Definition net.h:1144
int GetFullOutboundConnCount() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition net.cpp:2521
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
Definition net.cpp:3416
An encapsulated private key.
Definition key.h:46
Message header.
Definition protocol.h:29
static constexpr size_t MESSAGE_TYPE_SIZE
Definition protocol.h:31
static constexpr size_t CHECKSUM_SIZE
Definition protocol.h:33
static constexpr size_t HEADER_SIZE
Definition protocol.h:36
Network address.
Definition netaddress.h:113
Network GetNetClass() const
std::string ToStringAddr() const
bool IsRoutable() const
bool IsPrivacyNet() const
Whether this object is a privacy network.
Definition netaddress.h:190
bool SetSpecial(std::string_view addr)
Parse a Tor or I2P address and set this object to it.
bool IsValid() const
bool IsIPv4() const
Definition netaddress.h:158
bool IsIPv6() const
Definition netaddress.h:159
bool SetInternal(const std::string &name)
Create an "internal" address that represents a name or FQDN.
enum Network GetNetwork() const
~CNetCleanup()
Definition net.cpp:3750
CNetCleanup()=default
Transport protocol agnostic message container.
Definition net.h:243
size_t GetMemoryUsage() const noexcept
Compute total memory usage of this object (own memory + any dynamic memory).
Definition net.cpp:143
std::string m_type
Definition net.h:250
DataStream m_recv
received message data time of message receipt
Definition net.h:245
Information about a peer.
Definition net.h:687
std::atomic< int > nVersion
Definition net.h:734
bool IsInboundConn() const
Definition net.h:849
std::atomic_bool fPauseRecv
Definition net.h:754
std::string LogPeer() const
Helper function to log the peer id, optionally including IP address.
Definition net.cpp:729
NodeId GetId() const
Definition net.h:934
std::atomic< NodeClock::duration > m_last_ping_time
Last measured round-trip duration. Used only for stats.
Definition net.h:914
const std::string m_addr_name
Definition net.h:729
bool IsConnectedThroughPrivacyNet() const
Whether this peer connected through a privacy network.
Definition net.cpp:632
void CopyStats(CNodeStats &stats) EXCLUSIVE_LOCKS_REQUIRED(!m_subver_mutex
Definition net.cpp:639
std::string ConnectionTypeAsString() const
Definition net.h:988
const CService addrBind
Definition net.h:728
std::atomic< bool > m_bip152_highbandwidth_to
Definition net.h:885
std::list< CNetMessage > vRecvMsg
Definition net.h:1017
std::atomic< bool > m_bip152_highbandwidth_from
Definition net.h:887
const CAddress addr
Definition net.h:726
bool ReceiveMsgBytes(std::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:685
void SetAddrLocal(const CService &addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
May not be called more than once.
Definition net.cpp:619
const NodeClock::time_point m_connected
Unix epoch time at peer connection.
Definition net.h:720
std::atomic< NodeClock::time_point > m_last_recv
Definition net.h:718
CNode(NodeId id, std::shared_ptr< Sock > sock, const CAddress &addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const CService &addrBindIn, const std::string &addrNameIn, ConnectionType conn_type_in, bool inbound_onion, uint64_t network_key, CNodeOptions &&node_opts={})
Definition net.cpp:4152
void MarkReceivedMsgsForProcessing() EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex)
Move all messages from the received queue to the processing queue.
Definition net.cpp:4196
Mutex m_subver_mutex
Definition net.h:735
Mutex cs_vSend
Definition net.h:711
CNode * AddRef()
Definition net.h:973
std::string DisconnectMsg() const
Helper function to log disconnects.
Definition net.cpp:739
std::atomic< NodeClock::duration > m_min_ping_time
Lowest measured round-trip duration.
Definition net.h:918
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:4213
const util::NotNullUniquePtr< Transport > m_transport
Transport serializer/deserializer.
Definition net.h:691
Mutex m_msg_process_queue_mutex
Definition net.h:1019
std::atomic< NodeClock::time_point > m_last_send
Definition net.h:717
const ConnectionType m_conn_type
Definition net.h:763
Network ConnectedThroughNetwork() const
Get network the peer connected through.
Definition net.cpp:627
const size_t m_recv_flood_size
Definition net.h:1016
const NetPermissionFlags m_permission_flags
Definition net.h:693
Mutex m_addr_local_mutex
Definition net.h:1025
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e. connected via our Tor onion service.
Definition net.h:733
Mutex cs_vRecv
Definition net.h:713
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:905
Mutex m_sock_mutex
Definition net.h:712
std::atomic_bool fDisconnect
Definition net.h:749
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:911
CService GetAddrLocal() const EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
Definition net.cpp:612
void CloseSocketDisconnect() EXCLUSIVE_LOCKS_REQUIRED(!m_sock_mutex)
Definition net.cpp:579
std::string m_session_id
BIP324 session id string in hex, if any.
Definition net.h:234
std::string addrLocal
Definition net.h:222
bool fInbound
Definition net.h:209
TransportProtocolType m_transport_type
Transport protocol type.
Definition net.h:232
Network m_network
Definition net.h:228
NodeId nodeid
Definition net.h:200
Simple class for background tasks that should be run periodically or once "after a while".
Definition scheduler.h:39
void scheduleEvery(Function f, std::chrono::milliseconds delta) EXCLUSIVE_LOCKS_REQUIRED(!newTaskMutex)
Repeat f until the scheduler is stopped.
A combination of a network address (CNetAddr) and a (TCP) port.
Definition netaddress.h:531
bool SetSockAddr(const struct sockaddr *paddr, socklen_t addrlen)
Set CService from a network sockaddr.
uint16_t GetPort() const
sa_family_t GetSAFamily() const
Get the address family.
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Obtain the IPv4/6 socket address this represents.
std::string ToStringAddrPort() const
General SipHash-2-4 implementation.
Definition siphash.h:99
uint64_t Finalize() const
Compute the 64-bit SipHash-2-4 of the data written so far.
Definition siphash.cpp:45
CSipHasher & Write(uint64_t data)
Hash a 64-bit integer worth of data.
Definition siphash.cpp:14
std::string ToString() const
bool Match(const CNetAddr &addr) const
std::chrono::steady_clock Clock
RAII-style semaphore lock.
Double ended buffer combining vector and stream-like interfaces.
Definition streams.h:165
size_t GetMemoryUsage() const noexcept
Compute total memory usage of this object (own memory + any dynamic memory).
Definition streams.cpp:140
Fast randomness source.
Definition random.h:386
void fillrand(std::span< std::byte > output) noexcept
Fill a byte span with random bytes.
Definition random.cpp:626
Different type to mark Mutex at global scope.
Definition sync.h:142
Definition init.h:13
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition net.h:1050
Netgroup manager.
Definition netgroup.h:17
bool UsingASMap() const
Indicates whether ASMap is being used for clearnet bucketing.
Definition netgroup.cpp:135
void ASMapHealthCheck(const std::vector< CNetAddr > &clearnet_addrs) const
Analyze and log current health of ASMap based buckets.
Definition netgroup.cpp:119
std::vector< unsigned char > GetGroup(const CNetAddr &address) const
Get the canonical identifier of the network group for address.
Definition netgroup.cpp:29
uint32_t GetMappedAS(const CNetAddr &address) const
Get the autonomous system on the BGP path to address.
Definition netgroup.cpp:92
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)
Wrapper that overrides the GetParams() function of a stream.
Definition serialize.h:1169
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:329
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:336
I randrange(I range) noexcept
Generate a random integer in the range [0..range), with range > 0.
Definition random.h:254
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:365
uint64_t randbits(int bits) noexcept
Generate a random (bits)-bit integer.
Definition random.h:204
std::unordered_set< Network > All() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Definition netbase.h:141
bool Contains(Network net) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Definition netbase.h:128
static constexpr Event RecvEvent
If passed to Wait(), then it will wait for readiness to read from the socket.
Definition sock.h:151
uint8_t Event
Definition sock.h:146
static constexpr Event SendEvent
If passed to Wait(), then it will wait for readiness to send to the socket.
Definition sock.h:156
static constexpr Event ErrorEvent
Ignored if passed to Wait(), but could be set in the occurred events if an exceptional condition has ...
Definition sock.h:162
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:225
Minimal stream for reading from an existing byte array by std::span.
Definition streams.h:83
std::tuple< std::span< const uint8_t >, bool, const std::string & > BytesToSend
Return type for GetBytesToSend, consisting of:
Definition net.h:324
CNetMessage GetReceivedMessage(NodeClock::time_point time, bool &reject_message) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Retrieve a completed message from transport.
Definition net.cpp:826
bool SetMessageToSend(CSerializedNetMsg &msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Set the next message to send.
Definition net.cpp:865
Info GetInfo() const noexcept override
Retrieve information about this transport.
Definition net.cpp:751
int readData(std::span< const uint8_t > msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Definition net.cpp:799
const NodeId m_node_id
Definition net.h:384
Mutex m_send_mutex
Lock for sending state.
Definition net.h:419
const MessageStartChars m_magic_bytes
Definition net.h:383
size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Return the memory usage of this transport attributable to buffered data to send.
Definition net.cpp:927
const uint256 & GetMessageHash() const EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Definition net.cpp:817
void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Report how many bytes returned by the last GetBytesToSend() have been sent.
Definition net.cpp:911
int readHeader(std::span< const uint8_t > msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Definition net.cpp:756
bool CompleteInternal() const noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Definition net.h:411
bool ReceivedBytes(std::span< const uint8_t > &msg_bytes) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Feed wire bytes to the transport.
Definition net.h:440
V1Transport(NodeId node_id) noexcept
Definition net.cpp:744
BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Get bytes to send on the wire, if any, along with other information about it.
Definition net.cpp:890
void Reset() EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Definition net.h:399
Mutex m_recv_mutex
Lock for receive state.
Definition net.h:385
bool ReceivedMessageComplete() const override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Returns true if the current message is complete (so GetReceivedMessage can be called).
Definition net.h:432
void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Report how many bytes returned by the last GetBytesToSend() have been sent.
Definition net.cpp:1556
static constexpr uint32_t MAX_GARBAGE_LEN
Definition net.h:647
const NodeId m_nodeid
NodeId (for debug logging).
Definition net.h:593
size_t GetMaxBytesToProcess() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Determine how many received bytes can be processed in one go (not allowed in V1 state).
Definition net.cpp:1298
BIP324Cipher m_cipher
Cipher state.
Definition net.h:589
size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Return the memory usage of this transport attributable to buffered data to send.
Definition net.cpp:1595
void ProcessReceivedMaybeV1Bytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex
Process bytes in m_recv_buffer, while in KEY_MAYBE_V1 state.
Definition net.cpp:1104
SendState
State type that controls the sender side.
Definition net.h:558
@ READY
Normal sending state.
@ AWAITING_KEY
Waiting for the other side's public key.
@ V1
This transport is using v1 fallback.
V1Transport m_v1_fallback
Encapsulate a V1Transport to fall back to.
Definition net.h:595
static constexpr size_t V1_PREFIX_LEN
The length of the V1 prefix to match bytes initially received by responders with to determine if thei...
Definition net.h:472
void StartSendingHandshake() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex)
Put our public key + garbage in the send buffer.
Definition net.cpp:1011
bool ProcessReceivedPacketBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Process bytes in m_recv_buffer, while in VERSION/APP state.
Definition net.cpp:1229
CNetMessage GetReceivedMessage(NodeClock::time_point time, bool &reject_message) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Retrieve a completed message from transport.
Definition net.cpp:1478
bool ProcessReceivedKeyBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex
Process bytes in m_recv_buffer, while in KEY state.
Definition net.cpp:1142
const bool m_initiating
Whether we are the initiator side.
Definition net.h:591
Info GetInfo() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Retrieve information about this transport.
Definition net.cpp:1604
BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Get bytes to send on the wire, if any, along with other information about it.
Definition net.cpp:1539
void SetReceiveState(RecvState recv_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Change the receive state.
Definition net.cpp:1044
bool ProcessReceivedGarbageBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Process bytes in m_recv_buffer, while in GARB_GARBTERM state.
Definition net.cpp:1202
bool ReceivedMessageComplete() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Returns true if the current message is complete (so GetReceivedMessage can be called).
Definition net.cpp:1095
static constexpr std::array< std::byte, 0 > VERSION_CONTENTS
Contents of the version packet to send.
Definition net.h:468
static std::optional< std::string > GetMessageType(std::span< const uint8_t > &contents) noexcept
Given a packet's contents, find the message type (if valid), and strip it from contents.
Definition net.cpp:1437
bool ReceivedBytes(std::span< const uint8_t > &msg_bytes) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex
Feed wire bytes to the transport.
Definition net.cpp:1347
bool ShouldReconnectV1() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex
Whether upon disconnections, a reconnect with V1 is warranted.
Definition net.cpp:1578
bool SetMessageToSend(CSerializedNetMsg &msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Set the next message to send.
Definition net.cpp:1507
V2Transport(NodeId nodeid, bool initiating) noexcept
Construct a V2 transport with securely generated random keys.
Definition net.cpp:1040
RecvState
State type that defines the current contents of the receive buffer and/or how the next received bytes...
Definition net.h:493
@ VERSION
Version packet.
@ APP
Application packet.
@ GARB_GARBTERM
Garbage and garbage terminator.
@ V1
Nothing (this transport is using v1 fallback).
@ KEY_MAYBE_V1
(Responder only) either v2 public key or v1 header.
@ APP_READY
Nothing (an application packet is available for GetMessage()).
void SetSendState(SendState send_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex)
Change the send state.
Definition net.cpp:1075
constexpr unsigned char * begin()
Definition uint256.h:101
Implements a drop-in replacement for std::vector<T> which stores up to N elements directly (without h...
Definition prevector.h:37
void push_back(const T &value)
Definition prevector.h:392
256-bit opaque blob.
Definition uint256.h:196
NotNull is intended to be used to denote that a smart pointer type can not hold a nullptr value.
Definition not_null.h:45
static const PrecomputedData data
Precomputed COutPoint and CCoins values.
#define WSAEWOULDBLOCK
Definition compat.h:61
#define SOCKET_ERROR
Definition compat.h:68
#define WSAGetLastError()
Definition compat.h:59
#define WSAEMSGSIZE
Definition compat.h:63
#define COMPAT_IN6ADDR_ANY_INIT
Definition compat.h:45
#define MSG_NOSIGNAL
Definition compat.h:110
#define MSG_DONTWAIT
Definition compat.h:115
#define WSAEINPROGRESS
Definition compat.h:65
#define WSAEADDRINUSE
Definition compat.h:66
#define WSAEINTR
Definition compat.h:64
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
ConnectionType
Different types of connections to a peer.
@ PRIVATE_BROADCAST
Private broadcast connections are short-lived and only opened to privacy networks (Tor,...
@ BLOCK_RELAY
We use block-relay-only connections to help prevent against partition attacks.
@ MANUAL
We open manual connections to addresses that users explicitly requested via the addnode RPC or the -a...
@ 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.
@ ADDR_FETCH
AddrFetch connections are short lived connections used to solicit addresses from peers.
@ V1
Unencrypted, plaintext protocol.
@ V2
BIP324 protocol.
@ DETECTING
Peer could be v1 or v2.
constexpr unsigned int MAX_BLOCK_SERIALIZED_SIZE
The maximum allowed size for a serialized block, in bytes (only for buffer size limits)
Definition consensus.h:13
uint32_t ReadLE32(const B *ptr)
Definition common.h:27
static CService ip(uint32_t i)
std::optional< NodeId > SelectNodeToEvict(std::vector< NodeEvictionCandidate > &&vEvictionCandidates)
Select an inbound peer to evict after filtering out (protecting) peers having distinct,...
Definition eviction.cpp:175
static path u8path(std::string_view utf8_str)
Definition fs.h:80
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition fs.h:160
uint256 Hash(const T &in1)
Compute the 256-bit hash of an object.
Definition hash.h:83
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition hex_base.cpp:30
CKey GenerateRandomKey(bool compressed) noexcept
Definition key.cpp:354
#define LogWarning(...)
Definition log.h:137
#define LogInfo(...)
Definition log.h:136
#define LogError(...)
Definition log.h:138
#define LogDebug(category,...)
Definition log.h:154
bool fLogIPs
Definition logging.cpp:48
unsigned int nonce
@ PRIVBROADCAST
Definition categories.h:47
@ PROXY
Definition categories.h:31
constexpr const char * FILTERCLEAR
The filterclear message tells the receiving peer to remove a previously-set bloom filter.
Definition protocol.h:180
constexpr const char * FEEFILTER
The feefilter message tells the receiving peer not to inv us any txs which do not meet the specified ...
Definition protocol.h:192
constexpr const char * GETBLOCKS
The getblocks message requests an inv message that provides block header hashes starting from a parti...
Definition protocol.h:107
constexpr const char * HEADERS
The headers message sends one or more block headers to a node which previously requested certain head...
Definition protocol.h:123
constexpr const char * ADDR
The addr (IP address) message relays connection information for peers on the network.
Definition protocol.h:75
constexpr const char * GETBLOCKTXN
Contains a BlockTransactionsRequest Peer should respond with "blocktxn" message.
Definition protocol.h:212
constexpr const char * CMPCTBLOCK
Contains a CBlockHeaderAndShortTxIDs object - providing a header and list of "short txids".
Definition protocol.h:206
constexpr const char * CFCHECKPT
cfcheckpt is a response to a getcfcheckpt request containing a vector of evenly spaced filter headers...
Definition protocol.h:254
constexpr const char * GETCFILTERS
getcfilters requests compact filters for a range of blocks.
Definition protocol.h:224
constexpr const char * PONG
The pong message replies to a ping message, proving to the pinging node that the ponging node is stil...
Definition protocol.h:150
constexpr const char * BLOCKTXN
Contains a BlockTransactions.
Definition protocol.h:218
constexpr const char * CFHEADERS
cfheaders is a response to a getcfheaders request containing a filter header and a vector of filter h...
Definition protocol.h:242
constexpr const char * PING
The ping message is sent periodically to help confirm that the receiving peer is still connected.
Definition protocol.h:144
constexpr const char * FILTERLOAD
The filterload message tells the receiving peer to filter all relayed transactions and requested merk...
Definition protocol.h:164
constexpr const char * ADDRV2
The addrv2 message relays connection information for peers on the network just like the addr message,...
Definition protocol.h:81
constexpr const char * VERACK
The verack message acknowledges a previously-received version message, informing the connecting node ...
Definition protocol.h:70
constexpr const char * GETHEADERS
The getheaders message requests a headers message that provides block headers starting from a particu...
Definition protocol.h:113
constexpr const char * FILTERADD
The filteradd message tells the receiving peer to add a single element to a previously-set bloom filt...
Definition protocol.h:172
constexpr const char * CFILTER
cfilter is a response to a getcfilters request containing a single compact filter.
Definition protocol.h:229
constexpr const char * FEATURE
BIP 434 Peer feature negotiation.
Definition protocol.h:270
constexpr const char * GETDATA
The getdata message requests one or more data objects from another node.
Definition protocol.h:96
constexpr const char * SENDCMPCT
Contains a 1-byte bool and 8-byte LE version number.
Definition protocol.h:200
constexpr const char * GETCFCHECKPT
getcfcheckpt requests evenly spaced compact filter headers, enabling parallelized download and valida...
Definition protocol.h:249
constexpr const char * INV
The inv message (inventory message) transmits one or more inventories of objects known to the transmi...
Definition protocol.h:92
constexpr const char * TX
The tx message transmits a single transaction.
Definition protocol.h:117
constexpr const char * MEMPOOL
The mempool message requests the TXIDs of transactions that the receiving node has verified as valid ...
Definition protocol.h:139
constexpr const char * NOTFOUND
The notfound message is a reply to a getdata message which requested an object the receiving node doe...
Definition protocol.h:156
constexpr const char * MERKLEBLOCK
The merkleblock message is a reply to a getdata message which requested a block using the inventory t...
Definition protocol.h:102
constexpr const char * BLOCK
The block message transmits a single serialized block.
Definition protocol.h:127
constexpr const char * GETCFHEADERS
getcfheaders requests a compact filter header and the filter hashes for a range of blocks,...
Definition protocol.h:237
constexpr const char * VERSION
The version message provides information about the transmitting node to the receiving node at the beg...
Definition protocol.h:65
FILE * fopen(const fs::path &p, const char *mode)
Definition fs.cpp:23
static size_t DynamicUsage(const int8_t &v)
Dynamic memory usage for built-in types is zero.
Definition memusage.h:31
void TraceThread(std::string_view thread_name, std::function< void()> thread_func)
A wrapper for do-something-once thread functions.
Definition thread.cpp:15
uint16_t GetListenPort()
Definition net.cpp:154
static constexpr int DNSSEEDS_TO_QUERY_AT_ONCE
Number of DNS seeds to query when the number of connections is low.
Definition net.cpp:82
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition net.cpp:352
static const uint64_t RANDOMIZER_ID_NETGROUP
Definition net.cpp:126
static const uint64_t SELECT_TIMEOUT_MILLISECONDS
Definition net.cpp:122
static util::NotNullUniquePtr< Transport > MakeTransport(NodeId id, bool use_v2transport, bool inbound) noexcept
Definition net.cpp:4143
static const uint64_t RANDOMIZER_ID_NETWORKKEY
Definition net.cpp:128
void RemoveLocal(const CService &addr)
Definition net.cpp:330
BindFlags
Used to pass flags to the Bind() function.
Definition net.cpp:110
@ BF_REPORT_ERROR
Definition net.cpp:112
@ BF_NONE
Definition net.cpp:111
@ BF_DONT_ADVERTISE
Do not call AddLocal() for our special addresses, e.g., for incoming Tor connections,...
Definition net.cpp:117
bool fDiscover
Definition net.cpp:132
static const uint64_t RANDOMIZER_ID_LOCALHOSTNONCE
Definition net.cpp:127
static constexpr std::chrono::minutes DUMP_PEERS_INTERVAL
Definition net.cpp:79
static constexpr auto EXTRA_NETWORK_PEER_INTERVAL
Frequency to attempt extra connections to reachable networks we're not connected to yet.
Definition net.cpp:107
static constexpr int SEED_OUTBOUND_CONNECTION_THRESHOLD
Minimum number of outbound connections under which we will keep fetching our address seeds.
Definition net.cpp:85
void ClearLocal()
Definition net.cpp:288
static constexpr auto FEELER_SLEEP_WINDOW
Definition net.cpp:104
static constexpr int DNSSEEDS_DELAY_PEER_THRESHOLD
Definition net.cpp:98
bool fListen
Definition net.cpp:133
static constexpr size_t MAX_BLOCK_RELAY_ONLY_ANCHORS
Maximum number of block-relay-only anchor connections.
Definition net.cpp:73
static bool IsPeerAddrLocalGood(CNode *pnode)
Definition net.cpp:249
static constexpr std::chrono::seconds DNSSEEDS_DELAY_FEW_PEERS
How long to delay before querying DNS seeds.
Definition net.cpp:96
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition net.cpp:136
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
Definition net.cpp:258
const std::string NET_MESSAGE_TYPE_OTHER
Definition net.cpp:124
#define X(name)
Definition net.cpp:638
const char *const ANCHORS_DATABASE_FILENAME
Anchor IP address database file name.
Definition net.cpp:76
static std::vector< CAddress > ConvertSeeds(const std::vector< uint8_t > &vSeedsIn)
Convert the serialized seeds into usable address objects.
Definition net.cpp:211
static void CaptureMessageToFile(const CAddress &addr, const std::string &msg_type, std::span< const unsigned char > data, bool is_incoming)
Definition net.cpp:4376
CService GetLocalAddress(const CNode &peer)
Definition net.cpp:236
GlobalMutex g_maplocalhost_mutex
Definition net.cpp:134
static std::optional< CService > GetLocal(const CNode &peer)
Definition net.cpp:181
std::function< void(const CAddress &addr, const std::string &msg_type, std::span< const unsigned char > data, bool is_incoming)> CaptureMessage
Defaults to CaptureMessageToFile(), but can be overridden by unit tests.
Definition net.cpp:4416
static constexpr std::chrono::minutes DNSSEEDS_DELAY_MANY_PEERS
Definition net.cpp:97
bool AddLocal(const CService &addr_, int nScore, bool add_even_if_unreachable)
Definition net.cpp:295
static int GetnScore(const CService &addr)
Definition net.cpp:241
static bool IsOutboundMessageAllowedInPrivateBroadcast(std::string_view type) noexcept
Private broadcast connections only need to send certain message types.
Definition net.cpp:4234
static CNetCleanup instance_of_cnetcleanup
Definition net.cpp:3758
static constexpr std::chrono::seconds MAX_UPLOAD_TIMEFRAME
The default timeframe for -maxuploadtarget.
Definition net.cpp:101
bool SeenLocal(const CService &addr)
vote for a local address
Definition net.cpp:341
uint16_t GetListenPort()
Definition net.cpp:154
constexpr bool DEFAULT_PRIVATE_BROADCAST
Default for -privatebroadcast.
Definition net.h:98
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition net.cpp:352
void RemoveLocal(const CService &addr)
Definition net.cpp:330
constexpr std::chrono::minutes TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition net.h:64
bool fDiscover
Definition net.cpp:132
constexpr bool DEFAULT_FIXEDSEEDS
Definition net.h:106
bool fListen
Definition net.cpp:133
constexpr unsigned int MAX_PROTOCOL_MESSAGE_LENGTH
Maximum length of incoming protocol messages (no message over 4 MB is currently acceptable).
Definition net.h:70
constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL
Run the extra block-relay-only connection loop once every 5 minutes.
Definition net.h:68
const std::string NET_MESSAGE_TYPE_OTHER
Definition net.cpp:124
constexpr bool DEFAULT_FORCEDNSSEED
Definition net.h:104
constexpr bool DEFAULT_DNSSEED
Definition net.h:105
constexpr int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition net.h:78
GlobalMutex g_maplocalhost_mutex
Definition net.cpp:134
constexpr std::chrono::hours ASMAP_HEALTH_CHECK_INTERVAL
Interval for ASMap Health Check.
Definition net.h:102
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE, bool add_even_if_unreachable=false)
Definition net.cpp:295
constexpr auto FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes.
Definition net.h:66
std::function< void(const CAddress &addr, const std::string &msg_type, std::span< const unsigned char > data, bool is_incoming)> CaptureMessage
Defaults to CaptureMessageToFile(), but can be overridden by unit tests.
Definition net.cpp:4416
@ LOCAL_MANUAL
Definition net.h:164
@ LOCAL_BIND
Definition net.h:162
@ LOCAL_IF
Definition net.h:161
constexpr int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
Definition net.h:74
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:3497
NetPermissionFlags
int64_t NodeId
Identifier of a peer connection.
Definition net_types.h:15
constexpr uint16_t I2P_SAM31_PORT
SAM 3.1 and earlier do not support specifying ports and force the port to 0.
Definition netaddress.h:105
Network
A network type.
Definition netaddress.h:33
@ NET_I2P
I2P.
Definition netaddress.h:47
@ NET_CJDNS
CJDNS.
Definition netaddress.h:50
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
Definition netaddress.h:57
@ NET_ONION
TOR (v2 or v3)
Definition netaddress.h:44
@ NET_IPV6
IPv6.
Definition netaddress.h:41
@ NET_IPV4
IPv4.
Definition netaddress.h:38
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
Definition netaddress.h:35
@ NET_INTERNAL
A set of addresses that represent the hash of a string or FQDN.
Definition netaddress.h:54
std::optional< Proxy > GetNameProxy()
Definition netbase.cpp:744
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:650
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:173
std::string GetNetworkName(enum Network net)
Definition netbase.cpp:114
CThreadInterrupt g_socks5_interrupt
Interrupt SOCKS5 reads or writes.
Definition netbase.cpp:41
bool HaveNameProxy()
Definition netbase.cpp:753
CService GetBindAddress(const Sock &sock)
Get the bind address for a socket as CService.
Definition netbase.cpp:970
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:191
CService MaybeFlipIPv6toCJDNS(const CService &service)
If an IPv6 address belongs to the address range used by the CJDNS network and the CJDNS network is re...
Definition netbase.cpp:961
ReachableNets g_reachable_nets
Definition netbase.cpp:43
bool fNameLookup
Definition netbase.cpp:37
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:804
std::function< std::unique_ptr< Sock >(int, int, int)> CreateSock
Socket factory.
Definition netbase.cpp:577
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:216
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:866
std::optional< Proxy > GetProxy(enum Network net)
Definition netbase.cpp:726
ConnectionDirection
Definition netbase.h:35
std::vector< CNetAddr > GetLocalAddresses()
Return all local non-loopback IPv4 and IPv6 network addresses.
Definition netif.cpp:321
T SaturatingAdd(const T i, const T j) noexcept
Definition overflow.h:44
const std::array ALL_NET_MESSAGE_TYPES
All known message types (see above).
Definition protocol.h:274
constexpr ServiceFlags SeedsServiceFlags()
State independent service flags.
Definition protocol.h:366
ServiceFlags
nServices flags
Definition protocol.h:321
@ NODE_NONE
Definition protocol.h:324
@ NODE_P2P_V2
Definition protocol.h:342
constexpr ServiceFlags SeedsAssumedServiceFlags()
Service flags we assume for addresses obtained from the DNS seeds and the fixed seeds,...
Definition protocol.h:374
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:380
void RandAddEvent(const uint32_t event_info) noexcept
Gathers entropy from the low bits of the time at which events occur.
Definition random.cpp:617
uint256 GetRandHash() noexcept
Generate a random uint256.
Definition random.h:463
void ser_writedata32(Stream &s, uint32_t obj)
Definition serialize.h:66
constexpr uint64_t MAX_SIZE
The maximum size of a serialized object in bytes or number of elements (for eg vectors) when the size...
Definition serialize.h:35
void ser_writedata64(Stream &s, uint64_t obj)
Definition serialize.h:76
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
Definition sock.cpp:430
auto MakeByteSpan(const V &v) noexcept
Definition span.h:84
constexpr auto MakeUCharSpan(const V &v) -> decltype(UCharSpanCast(std::span{v}))
Like the std::span constructor, but for (const) unsigned char member types only.
Definition span.h:111
T & SpanPopBack(std::span< T > &span)
A span is an object that can refer to a contiguous sequence of objects.
Definition span.h:75
auto MakeWritableByteSpan(V &&v) noexcept
Definition span.h:89
unsigned char * UCharCast(char *c)
Definition span.h:95
Utilities for converting data from/to strings.
std::string m_added_node
Definition net.h:113
Cache responses to addr requests to minimize privacy leak.
Definition net.h:1684
std::vector< CAddress > m_addrs_response_cache
Definition net.h:1685
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition net.h:1109
std::vector< CService > onion_binds
Definition net.h:1111
std::vector< CService > vBinds
Definition net.h:1110
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
Definition net.h:1114
NetPermissionFlags permission_flags
Definition net.h:677
std::string m_type
Definition net.h:143
std::vector< unsigned char > data
Definition net.h:142
size_t GetMemoryUsage() const noexcept
Compute total memory usage of this object (own memory + any dynamic memory).
Definition net.cpp:138
An ElligatorSwift-encoded public key.
Definition pubkey.h:318
static constexpr size_t size()
Definition pubkey.h:335
uint16_t nPort
Definition net.h:188
Version of the system clock that is mockable in the context of tests (via FakeNodeClock or SetMockTim...
Definition time.h:27
static time_point now() noexcept
Return current system time or mocked time, if set.
Definition time.cpp:38
std::chrono::time_point< NodeClock > time_point
Definition time.h:28
static constexpr time_point epoch
Definition time.h:33
Auxiliary requested/occurred events to wait for in WaitMany().
Definition sock.h:190
std::optional< uint256 > session_id
Definition net.h:274
TransportProtocolType transport_type
Definition net.h:273
Bilingual messages:
Definition translation.h:24
An established connection with another peer.
Definition i2p.h:32
#define WAIT_LOCK(cs, name)
Definition sync.h:274
#define AssertLockNotHeld(cs)
Definition sync.h:149
#define LOCK(cs)
Definition sync.h:268
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition sync.h:299
#define AssertLockHeld(cs)
Definition sync.h:144
FastRandomContext rng
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#define GUARDED_BY(x)
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
#define TRACEPOINT(context,...)
Definition trace.h:56
#define TRACEPOINT_SEMAPHORE(context, event)
Definition trace.h:54
consteval auto _(util::TranslatedLiteral str)
Definition translation.h:79
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition translation.h:82
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.
constexpr int64_t count_seconds(std::chrono::seconds t)
Definition time.h:97
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
Definition time.h:35
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:82
assert(!tx.IsCoinBase())
void ClearShrink(V &v) noexcept
Clear a vector (or std::deque) and release its allocated memory.
Definition vector.h:56