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