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