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