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