Bitcoin ABC  0.24.7
P2P Digital Currency
net.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2019 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #if defined(HAVE_CONFIG_H)
7 #include <config/bitcoin-config.h>
8 #endif
9 
10 #include <net.h>
11 
12 #include <avalanche/avalanche.h>
13 #include <banman.h>
14 #include <clientversion.h>
15 #include <config.h>
16 #include <consensus/consensus.h>
17 #include <crypto/sha256.h>
18 #include <dnsseeds.h>
19 #include <netbase.h>
20 #include <node/ui_interface.h>
21 #include <protocol.h>
22 #include <random.h>
23 #include <scheduler.h>
24 #include <util/strencodings.h>
25 #include <util/translation.h>
26 
27 #ifdef WIN32
28 #include <cstring>
29 #else
30 #include <fcntl.h>
31 #endif
32 
33 #ifdef USE_POLL
34 #include <poll.h>
35 #endif
36 
37 #ifdef USE_UPNP
38 #include <miniupnpc/miniupnpc.h>
39 #include <miniupnpc/upnpcommands.h>
40 #include <miniupnpc/upnperrors.h>
41 // The minimum supported miniUPnPc API version is set to 10. This keeps
42 // compatibility with Ubuntu 16.04 LTS and Debian 8 libminiupnpc-dev packages.
43 static_assert(MINIUPNPC_API_VERSION >= 10,
44  "miniUPnPc API version >= 10 assumed");
45 #endif
46 
47 #include <algorithm>
48 #include <cmath>
49 #include <cstdint>
50 #include <limits>
51 #include <optional>
52 #include <unordered_map>
53 
55 static constexpr size_t MAX_BLOCK_RELAY_ONLY_ANCHORS = 2;
56 static_assert(MAX_BLOCK_RELAY_ONLY_ANCHORS <=
57  static_cast<size_t>(MAX_BLOCK_RELAY_ONLY_CONNECTIONS),
58  "MAX_BLOCK_RELAY_ONLY_ANCHORS must not exceed "
59  "MAX_BLOCK_RELAY_ONLY_CONNECTIONS.");
61 const char *const ANCHORS_DATABASE_FILENAME = "anchors.dat";
62 
63 // How often to dump addresses to peers.dat
64 static constexpr std::chrono::minutes DUMP_PEERS_INTERVAL{15};
65 
69 static constexpr int DNSSEEDS_TO_QUERY_AT_ONCE = 3;
70 
81 static constexpr std::chrono::seconds DNSSEEDS_DELAY_FEW_PEERS{11};
82 static constexpr std::chrono::minutes DNSSEEDS_DELAY_MANY_PEERS{5};
83 // "many" vs "few" peers
84 static constexpr int DNSSEEDS_DELAY_PEER_THRESHOLD = 1000;
85 
86 // We add a random period time (0 to 1 seconds) to feeler connections to prevent
87 // synchronization.
88 #define FEELER_SLEEP_WINDOW 1
89 
90 // MSG_NOSIGNAL is not available on some platforms, if it doesn't exist define
91 // it as 0
92 #if !defined(MSG_NOSIGNAL)
93 #define MSG_NOSIGNAL 0
94 #endif
95 
96 // MSG_DONTWAIT is not available on some platforms, if it doesn't exist define
97 // it as 0
98 #if !defined(MSG_DONTWAIT)
99 #define MSG_DONTWAIT 0
100 #endif
101 
103 enum BindFlags {
104  BF_NONE = 0,
105  BF_EXPLICIT = (1U << 0),
106  BF_REPORT_ERROR = (1U << 1),
111  BF_DONT_ADVERTISE = (1U << 2),
112 };
113 
114 // The set of sockets cannot be modified while waiting
115 // The sleep time needs to be small to avoid new sockets stalling
116 static const uint64_t SELECT_TIMEOUT_MILLISECONDS = 50;
117 
118 const std::string NET_MESSAGE_COMMAND_OTHER = "*other*";
119 
120 // SHA256("netgroup")[0:8]
121 static const uint64_t RANDOMIZER_ID_NETGROUP = 0x6c0edd8036ef4036ULL;
122 // SHA256("localhostnonce")[0:8]
123 static const uint64_t RANDOMIZER_ID_LOCALHOSTNONCE = 0xd93e69e2bbfa5735ULL;
124 // SHA256("localhostnonce")[8:16]
125 static const uint64_t RANDOMIZER_ID_EXTRAENTROPY = 0x94b05d41679a4ff7ULL;
126 // SHA256("addrcache")[0:8]
127 static const uint64_t RANDOMIZER_ID_ADDRCACHE = 0x1cf2e4ddd306dda9ULL;
128 //
129 // Global state variables
130 //
131 bool fDiscover = true;
132 bool fListen = true;
135 std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(cs_mapLocalHost);
136 static bool vfLimited[NET_MAX] GUARDED_BY(cs_mapLocalHost) = {};
137 
138 void CConnman::AddAddrFetch(const std::string &strDest) {
140  m_addr_fetches.push_back(strDest);
141 }
142 
143 uint16_t GetListenPort() {
144  return uint16_t(gArgs.GetArg("-port", Params().GetDefaultPort()));
145 }
146 
147 // find 'best' local address for a particular peer
148 bool GetLocal(CService &addr, const CNetAddr *paddrPeer) {
149  if (!fListen) {
150  return false;
151  }
152 
153  int nBestScore = -1;
154  int nBestReachability = -1;
155  {
157  for (const auto &entry : mapLocalHost) {
158  int nScore = entry.second.nScore;
159  int nReachability = entry.first.GetReachabilityFrom(paddrPeer);
160  if (nReachability > nBestReachability ||
161  (nReachability == nBestReachability && nScore > nBestScore)) {
162  addr = CService(entry.first, entry.second.nPort);
163  nBestReachability = nReachability;
164  nBestScore = nScore;
165  }
166  }
167  }
168  return nBestScore >= 0;
169 }
170 
172 static std::vector<CAddress>
173 convertSeed6(const std::vector<SeedSpec6> &vSeedsIn) {
174  // It'll only connect to one or two seed nodes because once it connects,
175  // it'll get a pile of addresses with newer timestamps. Seed nodes are given
176  // a random 'last seen time' of between one and two weeks ago.
177  const int64_t nOneWeek = 7 * 24 * 60 * 60;
178  std::vector<CAddress> vSeedsOut;
179  vSeedsOut.reserve(vSeedsIn.size());
180  FastRandomContext rng;
181  for (const auto &seed_in : vSeedsIn) {
182  struct in6_addr ip;
183  memcpy(&ip, seed_in.addr, sizeof(ip));
184  CAddress addr(CService(ip, seed_in.port),
186  addr.nTime = GetTime() - rng.randrange(nOneWeek) - nOneWeek;
187  vSeedsOut.push_back(addr);
188  }
189  return vSeedsOut;
190 }
191 
192 // Get best local address for a particular peer as a CAddress. Otherwise, return
193 // the unroutable 0.0.0.0 but filled in with the normal parameters, since the IP
194 // may be changed to a useful one by discovery.
196  ServiceFlags nLocalServices) {
197  CAddress ret(CService(CNetAddr(), GetListenPort()), nLocalServices);
198  CService addr;
199  if (GetLocal(addr, paddrPeer)) {
200  ret = CAddress(addr, nLocalServices);
201  }
202  ret.nTime = GetAdjustedTime();
203  return ret;
204 }
205 
206 static int GetnScore(const CService &addr) {
208  if (mapLocalHost.count(addr) == 0) {
209  return 0;
210  }
211  return mapLocalHost[addr].nScore;
212 }
213 
214 // Is our peer's addrLocal potentially useful as an external IP source?
216  CService addrLocal = pnode->GetAddrLocal();
217  return fDiscover && pnode->addr.IsRoutable() && addrLocal.IsRoutable() &&
218  IsReachable(addrLocal.GetNetwork());
219 }
220 
221 // Pushes our own address to a peer.
222 void AdvertiseLocal(CNode *pnode) {
223  if (fListen && pnode->fSuccessfullyConnected) {
224  CAddress addrLocal =
225  GetLocalAddress(&pnode->addr, pnode->GetLocalServices());
226  if (gArgs.GetBoolArg("-addrmantest", false)) {
227  // use IPv4 loopback during addrmantest
228  addrLocal =
229  CAddress(CService(LookupNumeric("127.0.0.1", GetListenPort())),
230  pnode->GetLocalServices());
231  }
232  // If discovery is enabled, sometimes give our peer the address it
233  // tells us that it sees us as in case it has a better idea of our
234  // address than we do.
235  FastRandomContext rng;
236  if (IsPeerAddrLocalGood(pnode) &&
237  (!addrLocal.IsRoutable() ||
238  rng.randbits((GetnScore(addrLocal) > LOCAL_MANUAL) ? 3 : 1) ==
239  0)) {
240  addrLocal.SetIP(pnode->GetAddrLocal());
241  }
242  if (addrLocal.IsRoutable() || gArgs.GetBoolArg("-addrmantest", false)) {
243  LogPrint(BCLog::NET, "AdvertiseLocal: advertising address %s\n",
244  addrLocal.ToString());
245  pnode->PushAddress(addrLocal, rng);
246  }
247  }
248 }
249 
250 // Learn a new local address.
251 bool AddLocal(const CService &addr, int nScore) {
252  if (!addr.IsRoutable()) {
253  return false;
254  }
255 
256  if (!fDiscover && nScore < LOCAL_MANUAL) {
257  return false;
258  }
259 
260  if (!IsReachable(addr)) {
261  return false;
262  }
263 
264  LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore);
265 
266  {
268  bool fAlready = mapLocalHost.count(addr) > 0;
269  LocalServiceInfo &info = mapLocalHost[addr];
270  if (!fAlready || nScore >= info.nScore) {
271  info.nScore = nScore + (fAlready ? 1 : 0);
272  info.nPort = addr.GetPort();
273  }
274  }
275 
276  return true;
277 }
278 
279 bool AddLocal(const CNetAddr &addr, int nScore) {
280  return AddLocal(CService(addr, GetListenPort()), nScore);
281 }
282 
283 void RemoveLocal(const CService &addr) {
285  LogPrintf("RemoveLocal(%s)\n", addr.ToString());
286  mapLocalHost.erase(addr);
287 }
288 
289 void SetReachable(enum Network net, bool reachable) {
290  if (net == NET_UNROUTABLE || net == NET_INTERNAL) {
291  return;
292  }
294  vfLimited[net] = !reachable;
295 }
296 
297 bool IsReachable(enum Network net) {
299  return !vfLimited[net];
300 }
301 
302 bool IsReachable(const CNetAddr &addr) {
303  return IsReachable(addr.GetNetwork());
304 }
305 
307 bool SeenLocal(const CService &addr) {
309  if (mapLocalHost.count(addr) == 0) {
310  return false;
311  }
312  mapLocalHost[addr].nScore++;
313  return true;
314 }
315 
317 bool IsLocal(const CService &addr) {
319  return mapLocalHost.count(addr) > 0;
320 }
321 
323  LOCK(cs_vNodes);
324  for (CNode *pnode : vNodes) {
325  if (static_cast<CNetAddr>(pnode->addr) == ip) {
326  return pnode;
327  }
328  }
329  return nullptr;
330 }
331 
333  LOCK(cs_vNodes);
334  for (CNode *pnode : vNodes) {
335  if (subNet.Match(static_cast<CNetAddr>(pnode->addr))) {
336  return pnode;
337  }
338  }
339  return nullptr;
340 }
341 
342 CNode *CConnman::FindNode(const std::string &addrName) {
343  LOCK(cs_vNodes);
344  for (CNode *pnode : vNodes) {
345  if (pnode->GetAddrName() == addrName) {
346  return pnode;
347  }
348  }
349  return nullptr;
350 }
351 
353  LOCK(cs_vNodes);
354  for (CNode *pnode : vNodes) {
355  if (static_cast<CService>(pnode->addr) == addr) {
356  return pnode;
357  }
358  }
359  return nullptr;
360 }
361 
362 bool CConnman::CheckIncomingNonce(uint64_t nonce) {
363  LOCK(cs_vNodes);
364  for (const CNode *pnode : vNodes) {
365  if (!pnode->fSuccessfullyConnected && !pnode->IsInboundConn() &&
366  pnode->GetLocalNonce() == nonce) {
367  return false;
368  }
369  }
370  return true;
371 }
372 
375  CAddress addr_bind;
376  struct sockaddr_storage sockaddr_bind;
377  socklen_t sockaddr_bind_len = sizeof(sockaddr_bind);
378  if (sock != INVALID_SOCKET) {
379  if (!getsockname(sock, (struct sockaddr *)&sockaddr_bind,
380  &sockaddr_bind_len)) {
381  addr_bind.SetSockAddr((const struct sockaddr *)&sockaddr_bind);
382  } else {
383  LogPrint(BCLog::NET, "Warning: getsockname failed\n");
384  }
385  }
386  return addr_bind;
387 }
388 
389 CNode *CConnman::ConnectNode(CAddress addrConnect, const char *pszDest,
390  bool fCountFailure, ConnectionType conn_type) {
391  assert(conn_type != ConnectionType::INBOUND);
392 
393  if (pszDest == nullptr) {
394  if (IsLocal(addrConnect)) {
395  return nullptr;
396  }
397 
398  // Look for an existing connection
399  CNode *pnode = FindNode(static_cast<CService>(addrConnect));
400  if (pnode) {
401  LogPrintf("Failed to open new connection, already connected\n");
402  return nullptr;
403  }
404  }
405 
407  LogPrint(BCLog::NET, "trying connection %s lastseen=%.1fhrs\n",
408  pszDest ? pszDest : addrConnect.ToString(),
409  pszDest
410  ? 0.0
411  : (double)(GetAdjustedTime() - addrConnect.nTime) / 3600.0);
412 
413  // Resolve
414  const int default_port = Params().GetDefaultPort();
415  if (pszDest) {
416  std::vector<CService> resolved;
417  if (Lookup(pszDest, resolved, default_port,
418  fNameLookup && !HaveNameProxy(), 256) &&
419  !resolved.empty()) {
420  addrConnect =
421  CAddress(resolved[GetRand(resolved.size())], NODE_NONE);
422  if (!addrConnect.IsValid()) {
424  "Resolver returned invalid address %s for %s\n",
425  addrConnect.ToString(), pszDest);
426  return nullptr;
427  }
428  // It is possible that we already have a connection to the IP/port
429  // pszDest resolved to. In that case, drop the connection that was
430  // just created, and return the existing CNode instead. Also store
431  // the name we used to connect in that CNode, so that future
432  // FindNode() calls to that name catch this early.
433  LOCK(cs_vNodes);
434  CNode *pnode = FindNode(static_cast<CService>(addrConnect));
435  if (pnode) {
436  pnode->MaybeSetAddrName(std::string(pszDest));
437  LogPrintf("Failed to open new connection, already connected\n");
438  return nullptr;
439  }
440  }
441  }
442 
443  // Connect
444  bool connected = false;
445  SOCKET hSocket = INVALID_SOCKET;
446  proxyType proxy;
447  if (addrConnect.IsValid()) {
448  bool proxyConnectionFailed = false;
449 
450  if (GetProxy(addrConnect.GetNetwork(), proxy)) {
451  hSocket = CreateSocket(proxy.proxy);
452  if (hSocket == INVALID_SOCKET) {
453  return nullptr;
454  }
455  connected = ConnectThroughProxy(
456  proxy, addrConnect.ToStringIP(), addrConnect.GetPort(), hSocket,
457  nConnectTimeout, proxyConnectionFailed);
458  } else {
459  // no proxy needed (none set for target network)
460  hSocket = CreateSocket(addrConnect);
461  if (hSocket == INVALID_SOCKET) {
462  return nullptr;
463  }
464  connected =
465  ConnectSocketDirectly(addrConnect, hSocket, nConnectTimeout,
466  conn_type == ConnectionType::MANUAL);
467  }
468  if (!proxyConnectionFailed) {
469  // If a connection to the node was attempted, and failure (if any)
470  // is not caused by a problem connecting to the proxy, mark this as
471  // an attempt.
472  addrman.Attempt(addrConnect, fCountFailure);
473  }
474  } else if (pszDest && GetNameProxy(proxy)) {
475  hSocket = CreateSocket(proxy.proxy);
476  if (hSocket == INVALID_SOCKET) {
477  return nullptr;
478  }
479  std::string host;
480  int port = default_port;
481  SplitHostPort(std::string(pszDest), port, host);
482  bool proxyConnectionFailed;
483  connected = ConnectThroughProxy(proxy, host, port, hSocket,
484  nConnectTimeout, proxyConnectionFailed);
485  }
486  if (!connected) {
487  CloseSocket(hSocket);
488  return nullptr;
489  }
490 
491  // Add node
492  NodeId id = GetNewNodeId();
494  .Write(id)
495  .Finalize();
496  uint64_t extra_entropy =
498  .Write(id)
499  .Finalize();
500  CAddress addr_bind = GetBindAddress(hSocket);
501  CNode *pnode =
502  new CNode(id, nLocalServices, GetBestHeight(), hSocket, addrConnect,
503  CalculateKeyedNetGroup(addrConnect), nonce, extra_entropy,
504  addr_bind, pszDest ? pszDest : "", conn_type);
505  pnode->AddRef();
506 
507  // We're making a new connection, harvest entropy from the time (and our
508  // peer count)
509  RandAddEvent(uint32_t(id));
510 
511  return pnode;
512 }
513 
515  fDisconnect = true;
516  LOCK(cs_hSocket);
517  if (hSocket != INVALID_SOCKET) {
518  LogPrint(BCLog::NET, "disconnecting peer=%d\n", id);
519  CloseSocket(hSocket);
520  }
521 }
522 
524  const CNetAddr &addr) const {
525  for (const auto &subnet : vWhitelistedRange) {
526  if (subnet.m_subnet.Match(addr)) {
527  NetPermissions::AddFlag(flags, subnet.m_flags);
528  }
529  }
530 }
531 
532 std::string CNode::ConnectionTypeAsString() const {
533  switch (m_conn_type) {
535  return "inbound";
537  return "manual";
539  return "feeler";
541  return "outbound-full-relay";
543  return "block-relay-only";
545  return "addr-fetch";
546  } // no default case, so the compiler can warn about missing cases
547 
548  assert(false);
549 }
550 
551 std::string CNode::GetAddrName() const {
552  LOCK(cs_addrName);
553  return addrName;
554 }
555 
556 void CNode::MaybeSetAddrName(const std::string &addrNameIn) {
557  LOCK(cs_addrName);
558  if (addrName.empty()) {
559  addrName = addrNameIn;
560  }
561 }
562 
565  return addrLocal;
566 }
567 
568 void CNode::SetAddrLocal(const CService &addrLocalIn) {
570  if (addrLocal.IsValid()) {
571  error("Addr local already set for node: %i. Refusing to change from %s "
572  "to %s",
573  id, addrLocal.ToString(), addrLocalIn.ToString());
574  } else {
575  addrLocal = addrLocalIn;
576  }
577 }
578 
581 }
582 
583 void CNode::copyStats(CNodeStats &stats, const std::vector<bool> &m_asmap) {
584  stats.nodeid = this->GetId();
585  stats.nServices = nServices;
586  stats.addr = addr;
587  stats.addrBind = addrBind;
589  stats.m_mapped_as = addr.GetMappedAS(m_asmap);
590  if (m_tx_relay != nullptr) {
591  LOCK(m_tx_relay->cs_filter);
592  stats.fRelayTxes = m_tx_relay->fRelayTxes;
593  } else {
594  stats.fRelayTxes = false;
595  }
596  stats.nLastSend = nLastSend;
597  stats.nLastRecv = nLastRecv;
598  stats.nLastTXTime = nLastTXTime;
602  stats.nTimeOffset = nTimeOffset;
603  stats.addrName = GetAddrName();
604  stats.nVersion = nVersion;
605  {
606  LOCK(cs_SubVer);
607  stats.cleanSubVer = cleanSubVer;
608  }
609  stats.fInbound = IsInboundConn();
612  {
613  LOCK(cs_vSend);
615  stats.nSendBytes = nSendBytes;
616  }
617  {
618  LOCK(cs_vRecv);
619  stats.mapRecvBytesPerMsgCmd = mapRecvBytesPerMsgCmd;
620  stats.nRecvBytes = nRecvBytes;
621  }
624  if (m_tx_relay != nullptr) {
625  LOCK(m_tx_relay->cs_feeFilter);
626  stats.minFeeFilter = m_tx_relay->minFeeFilter;
627  } else {
628  stats.minFeeFilter = Amount::zero();
629  }
630 
631  // It is common for nodes with good ping times to suddenly become lagged,
632  // due to a new block arriving or other large transfer. Merely reporting
633  // pingtime might fool the caller into thinking the node was still
634  // responsive, since pingtime does not update until the ping is complete,
635  // which might take a while. So, if a ping is taking an unusually long time
636  // in flight, the caller can immediately detect that this is happening.
637  std::chrono::microseconds ping_wait{0};
638  if ((0 != nPingNonceSent) && (0 != m_ping_start.load().count())) {
639  ping_wait = GetTime<std::chrono::microseconds>() - m_ping_start.load();
640  }
641 
642  // Raw ping time is in microseconds, but show it to user as whole seconds
643  // (Bitcoin users should be well used to small numbers with many decimal
644  // places by now :)
645  stats.m_ping_usec = nPingUsecTime;
647  stats.m_ping_wait_usec = count_microseconds(ping_wait);
648 
649  // Leave string empty if addrLocal invalid (not filled in yet)
650  CService addrLocalUnlocked = GetAddrLocal();
651  stats.addrLocal =
652  addrLocalUnlocked.IsValid() ? addrLocalUnlocked.ToString() : "";
653 
655 }
656 
657 bool CNode::ReceiveMsgBytes(const Config &config, const char *pch,
658  uint32_t nBytes, bool &complete) {
659  complete = false;
660  const auto time = GetTime<std::chrono::microseconds>();
661  LOCK(cs_vRecv);
662  nLastRecv = std::chrono::duration_cast<std::chrono::seconds>(time).count();
663  nRecvBytes += nBytes;
664  while (nBytes > 0) {
665  // Absorb network data.
666  int handled = m_deserializer->Read(config, pch, nBytes);
667 
668  if (handled < 0) {
669  return false;
670  }
671 
672  pch += handled;
673  nBytes -= handled;
674 
675  if (m_deserializer->Complete()) {
676  // decompose a transport agnostic CNetMessage from the deserializer
677  CNetMessage msg = m_deserializer->GetMessage(config, time);
678 
679  // Store received bytes per message command to prevent a memory DOS,
680  // only allow valid commands.
681  mapMsgCmdSize::iterator i =
682  mapRecvBytesPerMsgCmd.find(msg.m_command);
683  if (i == mapRecvBytesPerMsgCmd.end()) {
684  i = mapRecvBytesPerMsgCmd.find(NET_MESSAGE_COMMAND_OTHER);
685  }
686 
687  assert(i != mapRecvBytesPerMsgCmd.end());
688  i->second += msg.m_raw_message_size;
689 
690  // push the message to the process queue,
691  vRecvMsg.push_back(std::move(msg));
692 
693  complete = true;
694  }
695  }
696 
697  return true;
698 }
699 
700 int V1TransportDeserializer::readHeader(const Config &config, const char *pch,
701  uint32_t nBytes) {
702  // copy data to temporary parsing buffer
703  uint32_t nRemaining = CMessageHeader::HEADER_SIZE - nHdrPos;
704  uint32_t nCopy = std::min(nRemaining, nBytes);
705 
706  memcpy(&hdrbuf[nHdrPos], pch, nCopy);
707  nHdrPos += nCopy;
708 
709  // if header incomplete, exit
711  return nCopy;
712  }
713 
714  // deserialize to CMessageHeader
715  try {
716  hdrbuf >> hdr;
717  } catch (const std::exception &) {
718  return -1;
719  }
720 
721  // Reject oversized messages
722  if (hdr.IsOversized(config)) {
723  LogPrint(BCLog::NET, "Oversized header detected\n");
724  return -1;
725  }
726 
727  // switch state to reading message data
728  in_data = true;
729 
730  return nCopy;
731 }
732 
733 int V1TransportDeserializer::readData(const char *pch, uint32_t nBytes) {
734  unsigned int nRemaining = hdr.nMessageSize - nDataPos;
735  unsigned int nCopy = std::min(nRemaining, nBytes);
736 
737  if (vRecv.size() < nDataPos + nCopy) {
738  // Allocate up to 256 KiB ahead, but never more than the total message
739  // size.
740  vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024));
741  }
742 
743  hasher.Write({(const uint8_t *)pch, nCopy});
744  memcpy(&vRecv[nDataPos], pch, nCopy);
745  nDataPos += nCopy;
746 
747  return nCopy;
748 }
749 
751  assert(Complete());
752  if (data_hash.IsNull()) {
754  }
755  return data_hash;
756 }
757 
760  const std::chrono::microseconds time) {
761  // decompose a single CNetMessage from the TransportDeserializer
762  CNetMessage msg(std::move(vRecv));
763 
764  // store state about valid header, netmagic and checksum
765  msg.m_valid_header = hdr.IsValid(config);
766  // FIXME Split CheckHeaderMagicAndCommand() into CheckHeaderMagic() and
767  // CheckCommand() to prevent the net magic check code duplication.
768  msg.m_valid_netmagic =
769  (memcmp(std::begin(hdr.pchMessageStart),
770  std::begin(config.GetChainParams().NetMagic()),
772  uint256 hash = GetMessageHash();
773 
774  // store command string, payload size
775  msg.m_command = hdr.GetCommand();
778 
779  // We just received a message off the wire, harvest entropy from the time
780  // (and the message checksum)
781  RandAddEvent(ReadLE32(hash.begin()));
782 
783  msg.m_valid_checksum = (memcmp(hash.begin(), hdr.pchChecksum,
785 
786  if (!msg.m_valid_checksum) {
787  LogPrint(
788  BCLog::NET, "CHECKSUM ERROR (%s, %u bytes), expected %s was %s\n",
790  HexStr(Span<uint8_t>(hash.begin(),
793  }
794 
795  // store receive time
796  msg.m_time = time;
797 
798  // reset the network deserializer (prepare for the next message)
799  Reset();
800  return msg;
801 }
802 
804  CSerializedNetMsg &msg,
805  std::vector<uint8_t> &header) {
806  // create dbl-sha256 checksum
807  uint256 hash = Hash(msg.data);
808 
809  // create header
810  CMessageHeader hdr(config.GetChainParams().NetMagic(), msg.m_type.c_str(),
811  msg.data.size());
812  memcpy(hdr.pchChecksum, hash.begin(), CMessageHeader::CHECKSUM_SIZE);
813 
814  // serialize header
815  header.reserve(CMessageHeader::HEADER_SIZE);
816  CVectorWriter{SER_NETWORK, INIT_PROTO_VERSION, header, 0, hdr};
817 }
818 
819 size_t CConnman::SocketSendData(CNode *pnode) const
820  EXCLUSIVE_LOCKS_REQUIRED(pnode->cs_vSend) {
821  size_t nSentSize = 0;
822  size_t nMsgCount = 0;
823 
824  for (const auto &data : pnode->vSendMsg) {
825  assert(data.size() > pnode->nSendOffset);
826  int nBytes = 0;
827 
828  {
829  LOCK(pnode->cs_hSocket);
830  if (pnode->hSocket == INVALID_SOCKET) {
831  break;
832  }
833 
834  nBytes = send(pnode->hSocket,
835  reinterpret_cast<const char *>(data.data()) +
836  pnode->nSendOffset,
837  data.size() - pnode->nSendOffset,
839  }
840 
841  if (nBytes == 0) {
842  // couldn't send anything at all
843  break;
844  }
845 
846  if (nBytes < 0) {
847  // error
848  int nErr = WSAGetLastError();
849  if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE &&
850  nErr != WSAEINTR && nErr != WSAEINPROGRESS) {
851  LogPrintf("socket send error %s\n", NetworkErrorString(nErr));
852  pnode->CloseSocketDisconnect();
853  }
854 
855  break;
856  }
857 
858  assert(nBytes > 0);
859  pnode->nLastSend = GetSystemTimeInSeconds();
860  pnode->nSendBytes += nBytes;
861  pnode->nSendOffset += nBytes;
862  nSentSize += nBytes;
863  if (pnode->nSendOffset != data.size()) {
864  // could not send full message; stop sending more
865  break;
866  }
867 
868  pnode->nSendOffset = 0;
869  pnode->nSendSize -= data.size();
870  pnode->fPauseSend = pnode->nSendSize > nSendBufferMaxSize;
871  nMsgCount++;
872  }
873 
874  pnode->vSendMsg.erase(pnode->vSendMsg.begin(),
875  pnode->vSendMsg.begin() + nMsgCount);
876 
877  if (pnode->vSendMsg.empty()) {
878  assert(pnode->nSendOffset == 0);
879  assert(pnode->nSendSize == 0);
880  }
881 
882  return nSentSize;
883 }
884 
886  const NodeEvictionCandidate &b) {
887  return a.nMinPingUsecTime > b.nMinPingUsecTime;
888 }
889 
891  const NodeEvictionCandidate &b) {
892  return a.nTimeConnected > b.nTimeConnected;
893 }
894 
896  const NodeEvictionCandidate &b) {
897  if (a.m_is_local != b.m_is_local) {
898  return b.m_is_local;
899  }
900 
901  return a.nTimeConnected > b.nTimeConnected;
902 }
903 
905  const NodeEvictionCandidate &b) {
906  return a.nKeyedNetGroup < b.nKeyedNetGroup;
907 }
908 
910  const NodeEvictionCandidate &b) {
911  // There is a fall-through here because it is common for a node to have many
912  // peers which have not yet relayed a block.
913  if (a.nLastBlockTime != b.nLastBlockTime) {
914  return a.nLastBlockTime < b.nLastBlockTime;
915  }
916 
918  return b.fRelevantServices;
919  }
920 
921  return a.nTimeConnected > b.nTimeConnected;
922 }
923 
925  const NodeEvictionCandidate &b) {
926  // There is a fall-through here because it is common for a node to have more
927  // than a few peers that have not yet relayed txn.
928  if (a.nLastTXTime != b.nLastTXTime) {
929  return a.nLastTXTime < b.nLastTXTime;
930  }
931 
932  if (a.fRelayTxes != b.fRelayTxes) {
933  return b.fRelayTxes;
934  }
935 
936  if (a.fBloomFilter != b.fBloomFilter) {
937  return a.fBloomFilter;
938  }
939 
940  return a.nTimeConnected > b.nTimeConnected;
941 }
942 
944  const NodeEvictionCandidate &b) {
945  // There is a fall-through here because it is common for a node to have more
946  // than a few peers that have not yet relayed proofs. This fallback is also
947  // used in the case avalanche is not enabled.
948  if (a.nLastProofTime != b.nLastProofTime) {
949  return a.nLastProofTime < b.nLastProofTime;
950  }
951 
952  return a.nTimeConnected > b.nTimeConnected;
953 }
954 
955 // Pick out the potential block-relay only peers, and sort them by last block
956 // time.
958  const NodeEvictionCandidate &b) {
959  if (a.fRelayTxes != b.fRelayTxes) {
960  return a.fRelayTxes;
961  }
962 
963  if (a.nLastBlockTime != b.nLastBlockTime) {
964  return a.nLastBlockTime < b.nLastBlockTime;
965  }
966 
968  return b.fRelevantServices;
969  }
970 
971  return a.nTimeConnected > b.nTimeConnected;
972 }
973 
975  const NodeEvictionCandidate &b) {
976  // Equality can happen if the nodes have no score or it has not been
977  // computed yet.
980  }
981 
982  return a.nTimeConnected > b.nTimeConnected;
983 }
984 
986 template <typename T, typename Comparator>
987 static void EraseLastKElements(std::vector<T> &elements, Comparator comparator,
988  size_t k) {
989  std::sort(elements.begin(), elements.end(), comparator);
990  size_t eraseSize = std::min(k, elements.size());
991  elements.erase(elements.end() - eraseSize, elements.end());
992 }
993 
996 template <typename T, typename Comparator, typename Condition>
997 static void EraseLastKElementsIf(std::vector<T> &elements,
998  Comparator comparator, size_t k,
999  Condition cond) {
1000  std::sort(elements.begin(), elements.end(), comparator);
1001  size_t eraseSize = std::min(k, elements.size());
1002  elements.erase(
1003  std::remove_if(elements.end() - eraseSize, elements.end(), cond),
1004  elements.end());
1005 }
1006 
1007 [[nodiscard]] std::optional<NodeId>
1008 SelectNodeToEvict(std::vector<NodeEvictionCandidate> &&vEvictionCandidates) {
1009  // Protect connections with certain characteristics
1010 
1011  // Deterministically select 4 peers to protect by netgroup.
1012  // An attacker cannot predict which netgroups will be protected
1013  EraseLastKElements(vEvictionCandidates, CompareNetGroupKeyed, 4);
1014  // Protect the 8 nodes with the lowest minimum ping time.
1015  // An attacker cannot manipulate this metric without physically moving nodes
1016  // closer to the target.
1017  EraseLastKElements(vEvictionCandidates, ReverseCompareNodeMinPingTime, 8);
1018  // Protect 4 nodes that most recently sent us novel transactions accepted
1019  // into our mempool. An attacker cannot manipulate this metric without
1020  // performing useful work.
1021  EraseLastKElements(vEvictionCandidates, CompareNodeTXTime, 4);
1022  // Protect 4 nodes that most recently sent us novel proofs accepted
1023  // into our proof pool. An attacker cannot manipulate this metric without
1024  // performing useful work.
1025  // TODO this filter must happen before the last tx time once avalanche is
1026  // enabled for pre-consensus.
1027  EraseLastKElements(vEvictionCandidates, CompareNodeProofTime, 4);
1028  // Protect up to 8 non-tx-relay peers that have sent us novel blocks.
1029  EraseLastKElementsIf(vEvictionCandidates, CompareNodeBlockRelayOnlyTime, 8,
1030  [](NodeEvictionCandidate const &n) {
1031  return !n.fRelayTxes && n.fRelevantServices;
1032  });
1033 
1034  // Protect 4 nodes that most recently sent us novel blocks.
1035  // An attacker cannot manipulate this metric without performing useful work.
1036  EraseLastKElements(vEvictionCandidates, CompareNodeBlockTime, 4);
1037 
1038  // Protect up to 128 nodes that have the highest avalanche availability
1039  // score.
1040  EraseLastKElementsIf(vEvictionCandidates, CompareNodeAvailabilityScore, 128,
1041  [](NodeEvictionCandidate const &n) {
1042  return n.availabilityScore > 0.;
1043  });
1044 
1045  // Protect the half of the remaining nodes which have been connected the
1046  // longest. This replicates the non-eviction implicit behavior, and
1047  // precludes attacks that start later.
1048  // Reserve half of these protected spots for localhost peers, even if
1049  // they're not longest-uptime overall. This helps protect tor peers, which
1050  // tend to be otherwise disadvantaged under our eviction criteria.
1051  size_t initial_size = vEvictionCandidates.size();
1052  size_t total_protect_size = initial_size / 2;
1053 
1054  // Pick out up to 1/4 peers that are localhost, sorted by longest uptime.
1056  vEvictionCandidates, CompareLocalHostTimeConnected,
1057  total_protect_size / 2,
1058  [](NodeEvictionCandidate const &n) { return n.m_is_local; });
1059  // Calculate how many we removed, and update our total number of peers that
1060  // we want to protect based on uptime accordingly.
1061  total_protect_size -= initial_size - vEvictionCandidates.size();
1063  total_protect_size);
1064 
1065  if (vEvictionCandidates.empty()) {
1066  return std::nullopt;
1067  }
1068 
1069  // If any remaining peers are preferred for eviction consider only them.
1070  // This happens after the other preferences since if a peer is really the
1071  // best by other criteria (esp relaying blocks)
1072  // then we probably don't want to evict it no matter what.
1073  if (std::any_of(
1074  vEvictionCandidates.begin(), vEvictionCandidates.end(),
1075  [](NodeEvictionCandidate const &n) { return n.prefer_evict; })) {
1076  vEvictionCandidates.erase(
1077  std::remove_if(
1078  vEvictionCandidates.begin(), vEvictionCandidates.end(),
1079  [](NodeEvictionCandidate const &n) { return !n.prefer_evict; }),
1080  vEvictionCandidates.end());
1081  }
1082 
1083  // Identify the network group with the most connections and youngest member.
1084  // (vEvictionCandidates is already sorted by reverse connect time)
1085  uint64_t naMostConnections;
1086  unsigned int nMostConnections = 0;
1087  int64_t nMostConnectionsTime = 0;
1088  std::map<uint64_t, std::vector<NodeEvictionCandidate>> mapNetGroupNodes;
1089  for (const NodeEvictionCandidate &node : vEvictionCandidates) {
1090  std::vector<NodeEvictionCandidate> &group =
1091  mapNetGroupNodes[node.nKeyedNetGroup];
1092  group.push_back(node);
1093  int64_t grouptime = group[0].nTimeConnected;
1094  size_t group_size = group.size();
1095  if (group_size > nMostConnections ||
1096  (group_size == nMostConnections &&
1097  grouptime > nMostConnectionsTime)) {
1098  nMostConnections = group_size;
1099  nMostConnectionsTime = grouptime;
1100  naMostConnections = node.nKeyedNetGroup;
1101  }
1102  }
1103 
1104  // Reduce to the network group with the most connections
1105  vEvictionCandidates = std::move(mapNetGroupNodes[naMostConnections]);
1106 
1107  // Disconnect from the network group with the most connections
1108  return vEvictionCandidates.front().id;
1109 }
1110 
1120  std::vector<NodeEvictionCandidate> vEvictionCandidates;
1121  {
1122  LOCK(cs_vNodes);
1123  for (const CNode *node : vNodes) {
1124  if (node->HasPermission(PF_NOBAN)) {
1125  continue;
1126  }
1127  if (!node->IsInboundConn()) {
1128  continue;
1129  }
1130  if (node->fDisconnect) {
1131  continue;
1132  }
1133  bool peer_relay_txes = false;
1134  bool peer_filter_not_null = false;
1135  if (node->m_tx_relay != nullptr) {
1136  LOCK(node->m_tx_relay->cs_filter);
1137  peer_relay_txes = node->m_tx_relay->fRelayTxes;
1138  peer_filter_not_null = node->m_tx_relay->pfilter != nullptr;
1139  }
1140 
1141  NodeEvictionCandidate candidate = {
1142  node->GetId(),
1143  node->nTimeConnected,
1144  node->nMinPingUsecTime,
1145  node->nLastBlockTime,
1146  node->nLastProofTime,
1147  node->nLastTXTime,
1148  HasAllDesirableServiceFlags(node->nServices),
1149  peer_relay_txes,
1150  peer_filter_not_null,
1151  node->nKeyedNetGroup,
1152  node->m_prefer_evict,
1153  node->addr.IsLocal(),
1154  node->m_avalanche_state
1155  ? node->m_avalanche_state->getAvailabilityScore()
1156  : -std::numeric_limits<double>::infinity()};
1157  vEvictionCandidates.push_back(candidate);
1158  }
1159  }
1160  const std::optional<NodeId> node_id_to_evict =
1161  SelectNodeToEvict(std::move(vEvictionCandidates));
1162  if (!node_id_to_evict) {
1163  return false;
1164  }
1165  LOCK(cs_vNodes);
1166  for (CNode *pnode : vNodes) {
1167  if (pnode->GetId() == *node_id_to_evict) {
1168  pnode->fDisconnect = true;
1169  return true;
1170  }
1171  }
1172  return false;
1173 }
1174 
1175 void CConnman::AcceptConnection(const ListenSocket &hListenSocket) {
1176  struct sockaddr_storage sockaddr;
1177  socklen_t len = sizeof(sockaddr);
1178  SOCKET hSocket =
1179  accept(hListenSocket.socket, (struct sockaddr *)&sockaddr, &len);
1180  CAddress addr;
1181  int nInbound = 0;
1182  int nMaxInbound = nMaxConnections - m_max_outbound;
1183 
1184  if (hSocket != INVALID_SOCKET) {
1185  if (!addr.SetSockAddr((const struct sockaddr *)&sockaddr)) {
1186  LogPrintf("Warning: Unknown socket family\n");
1187  }
1188  }
1189 
1191  hListenSocket.AddSocketPermissionFlags(permissionFlags);
1192  AddWhitelistPermissionFlags(permissionFlags, addr);
1193  bool legacyWhitelisted = false;
1194  if (NetPermissions::HasFlag(permissionFlags,
1196  NetPermissions::ClearFlag(permissionFlags, PF_ISIMPLICIT);
1197  if (gArgs.GetBoolArg("-whitelistforcerelay",
1199  NetPermissions::AddFlag(permissionFlags, PF_FORCERELAY);
1200  }
1201  if (gArgs.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY)) {
1202  NetPermissions::AddFlag(permissionFlags, PF_RELAY);
1203  }
1204  NetPermissions::AddFlag(permissionFlags, PF_MEMPOOL);
1205  NetPermissions::AddFlag(permissionFlags, PF_NOBAN);
1206  legacyWhitelisted = true;
1207  }
1208 
1209  {
1210  LOCK(cs_vNodes);
1211  for (const CNode *pnode : vNodes) {
1212  if (pnode->IsInboundConn()) {
1213  nInbound++;
1214  }
1215  }
1216  }
1217 
1218  if (hSocket == INVALID_SOCKET) {
1219  int nErr = WSAGetLastError();
1220  if (nErr != WSAEWOULDBLOCK) {
1221  LogPrintf("socket error accept failed: %s\n",
1222  NetworkErrorString(nErr));
1223  }
1224  return;
1225  }
1226 
1227  if (!fNetworkActive) {
1228  LogPrintf("connection from %s dropped: not accepting new connections\n",
1229  addr.ToString());
1230  CloseSocket(hSocket);
1231  return;
1232  }
1233 
1234  if (!IsSelectableSocket(hSocket)) {
1235  LogPrintf("connection from %s dropped: non-selectable socket\n",
1236  addr.ToString());
1237  CloseSocket(hSocket);
1238  return;
1239  }
1240 
1241  // According to the internet TCP_NODELAY is not carried into accepted
1242  // sockets on all platforms. Set it again here just to be sure.
1243  SetSocketNoDelay(hSocket);
1244 
1245  // Don't accept connections from banned peers.
1246  bool banned = m_banman && m_banman->IsBanned(addr);
1247  if (!NetPermissions::HasFlag(permissionFlags,
1249  banned) {
1250  LogPrint(BCLog::NET, "connection from %s dropped (banned)\n",
1251  addr.ToString());
1252  CloseSocket(hSocket);
1253  return;
1254  }
1255 
1256  // Only accept connections from discouraged peers if our inbound slots
1257  // aren't (almost) full.
1258  bool discouraged = m_banman && m_banman->IsDiscouraged(addr);
1259  if (!NetPermissions::HasFlag(permissionFlags,
1261  nInbound + 1 >= nMaxInbound && discouraged) {
1262  LogPrint(BCLog::NET, "connection from %s dropped (discouraged)\n",
1263  addr.ToString());
1264  CloseSocket(hSocket);
1265  return;
1266  }
1267 
1268  if (nInbound >= nMaxInbound) {
1269  if (!AttemptToEvictConnection()) {
1270  // No connection to evict, disconnect the new connection
1271  LogPrint(BCLog::NET, "failed to find an eviction candidate - "
1272  "connection dropped (full)\n");
1273  CloseSocket(hSocket);
1274  return;
1275  }
1276  }
1277 
1278  NodeId id = GetNewNodeId();
1280  .Write(id)
1281  .Finalize();
1282  uint64_t extra_entropy =
1284  .Write(id)
1285  .Finalize();
1286  CAddress addr_bind = GetBindAddress(hSocket);
1287 
1288  ServiceFlags nodeServices = nLocalServices;
1289  if (NetPermissions::HasFlag(permissionFlags, PF_BLOOMFILTER)) {
1290  nodeServices = static_cast<ServiceFlags>(nodeServices | NODE_BLOOM);
1291  }
1292 
1293  const bool inbound_onion =
1294  std::find(m_onion_binds.begin(), m_onion_binds.end(), addr_bind) !=
1295  m_onion_binds.end();
1296  CNode *pnode =
1297  new CNode(id, nodeServices, GetBestHeight(), hSocket, addr,
1298  CalculateKeyedNetGroup(addr), nonce, extra_entropy, addr_bind,
1299  "", ConnectionType::INBOUND, inbound_onion);
1300  pnode->AddRef();
1301  pnode->m_permissionFlags = permissionFlags;
1302  // If this flag is present, the user probably expect that RPC and QT report
1303  // it as whitelisted (backward compatibility)
1304  pnode->m_legacyWhitelisted = legacyWhitelisted;
1305  pnode->m_prefer_evict = discouraged;
1306  m_msgproc->InitializeNode(*config, pnode);
1307 
1308  LogPrint(BCLog::NET, "connection from %s accepted\n", addr.ToString());
1309 
1310  {
1311  LOCK(cs_vNodes);
1312  vNodes.push_back(pnode);
1313  }
1314 
1315  // We received a new connection, harvest entropy from the time (and our peer
1316  // count)
1317  RandAddEvent(uint32_t(id));
1318 }
1319 
1321  {
1322  LOCK(cs_vNodes);
1323 
1324  if (!fNetworkActive) {
1325  // Disconnect any connected nodes
1326  for (CNode *pnode : vNodes) {
1327  if (!pnode->fDisconnect) {
1329  "Network not active, dropping peer=%d\n",
1330  pnode->GetId());
1331  pnode->fDisconnect = true;
1332  }
1333  }
1334  }
1335 
1336  // Disconnect unused nodes
1337  std::vector<CNode *> vNodesCopy = vNodes;
1338  for (CNode *pnode : vNodesCopy) {
1339  if (pnode->fDisconnect) {
1340  // remove from vNodes
1341  vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode),
1342  vNodes.end());
1343 
1344  // release outbound grant (if any)
1345  pnode->grantOutbound.Release();
1346 
1347  // close socket and cleanup
1348  pnode->CloseSocketDisconnect();
1349 
1350  // hold in disconnected pool until all refs are released
1351  pnode->Release();
1352  vNodesDisconnected.push_back(pnode);
1353  }
1354  }
1355  }
1356  {
1357  // Delete disconnected nodes
1358  std::list<CNode *> vNodesDisconnectedCopy = vNodesDisconnected;
1359  for (CNode *pnode : vNodesDisconnectedCopy) {
1360  // wait until threads are done using it
1361  if (pnode->GetRefCount() <= 0) {
1362  bool fDelete = false;
1363  {
1364  TRY_LOCK(pnode->cs_vSend, lockSend);
1365  if (lockSend) {
1366  fDelete = true;
1367  }
1368  }
1369  if (fDelete) {
1370  vNodesDisconnected.remove(pnode);
1371  DeleteNode(pnode);
1372  }
1373  }
1374  }
1375  }
1376 }
1377 
1379  size_t vNodesSize;
1380  {
1381  LOCK(cs_vNodes);
1382  vNodesSize = vNodes.size();
1383  }
1384  if (vNodesSize != nPrevNodeCount) {
1385  nPrevNodeCount = vNodesSize;
1386  if (clientInterface) {
1387  clientInterface->NotifyNumConnectionsChanged(vNodesSize);
1388  }
1389  }
1390 }
1391 
1393  int64_t nTime = GetSystemTimeInSeconds();
1394  if (nTime - pnode->nTimeConnected > m_peer_connect_timeout) {
1395  if (pnode->nLastRecv == 0 || pnode->nLastSend == 0) {
1397  "socket no message in first %i seconds, %d %d from %d\n",
1398  m_peer_connect_timeout, pnode->nLastRecv != 0,
1399  pnode->nLastSend != 0, pnode->GetId());
1400  pnode->fDisconnect = true;
1401  } else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL) {
1402  LogPrintf("socket sending timeout: %is\n",
1403  nTime - pnode->nLastSend);
1404  pnode->fDisconnect = true;
1405  } else if (nTime - pnode->nLastRecv >
1406  (pnode->GetCommonVersion() > BIP0031_VERSION
1408  : 90 * 60)) {
1409  LogPrintf("socket receive timeout: %is\n",
1410  nTime - pnode->nLastRecv);
1411  pnode->fDisconnect = true;
1412  } else if (pnode->nPingNonceSent &&
1413  pnode->m_ping_start.load() +
1414  std::chrono::seconds{TIMEOUT_INTERVAL} <
1415  GetTime<std::chrono::microseconds>()) {
1416  LogPrintf("ping timeout: %fs\n",
1417  0.000001 * count_microseconds(
1418  GetTime<std::chrono::microseconds>() -
1419  pnode->m_ping_start.load()));
1420  pnode->fDisconnect = true;
1421  } else if (!pnode->fSuccessfullyConnected) {
1422  LogPrint(BCLog::NET, "version handshake timeout from %d\n",
1423  pnode->GetId());
1424  pnode->fDisconnect = true;
1425  }
1426  }
1427 }
1428 
1429 bool CConnman::GenerateSelectSet(std::set<SOCKET> &recv_set,
1430  std::set<SOCKET> &send_set,
1431  std::set<SOCKET> &error_set) {
1432  for (const ListenSocket &hListenSocket : vhListenSocket) {
1433  recv_set.insert(hListenSocket.socket);
1434  }
1435 
1436  {
1437  LOCK(cs_vNodes);
1438  for (CNode *pnode : vNodes) {
1439  // Implement the following logic:
1440  // * If there is data to send, select() for sending data. As this
1441  // only happens when optimistic write failed, we choose to first
1442  // drain the write buffer in this case before receiving more. This
1443  // avoids needlessly queueing received data, if the remote peer is
1444  // not themselves receiving data. This means properly utilizing
1445  // TCP flow control signalling.
1446  // * Otherwise, if there is space left in the receive buffer,
1447  // select() for receiving data.
1448  // * Hand off all complete messages to the processor, to be handled
1449  // without blocking here.
1450 
1451  bool select_recv = !pnode->fPauseRecv;
1452  bool select_send;
1453  {
1454  LOCK(pnode->cs_vSend);
1455  select_send = !pnode->vSendMsg.empty();
1456  }
1457 
1458  LOCK(pnode->cs_hSocket);
1459  if (pnode->hSocket == INVALID_SOCKET) {
1460  continue;
1461  }
1462 
1463  error_set.insert(pnode->hSocket);
1464  if (select_send) {
1465  send_set.insert(pnode->hSocket);
1466  continue;
1467  }
1468  if (select_recv) {
1469  recv_set.insert(pnode->hSocket);
1470  }
1471  }
1472  }
1473 
1474  return !recv_set.empty() || !send_set.empty() || !error_set.empty();
1475 }
1476 
1477 #ifdef USE_POLL
1478 void CConnman::SocketEvents(std::set<SOCKET> &recv_set,
1479  std::set<SOCKET> &send_set,
1480  std::set<SOCKET> &error_set) {
1481  std::set<SOCKET> recv_select_set, send_select_set, error_select_set;
1482  if (!GenerateSelectSet(recv_select_set, send_select_set,
1483  error_select_set)) {
1485  std::chrono::milliseconds(SELECT_TIMEOUT_MILLISECONDS));
1486  return;
1487  }
1488 
1489  std::unordered_map<SOCKET, struct pollfd> pollfds;
1490  for (SOCKET socket_id : recv_select_set) {
1491  pollfds[socket_id].fd = socket_id;
1492  pollfds[socket_id].events |= POLLIN;
1493  }
1494 
1495  for (SOCKET socket_id : send_select_set) {
1496  pollfds[socket_id].fd = socket_id;
1497  pollfds[socket_id].events |= POLLOUT;
1498  }
1499 
1500  for (SOCKET socket_id : error_select_set) {
1501  pollfds[socket_id].fd = socket_id;
1502  // These flags are ignored, but we set them for clarity
1503  pollfds[socket_id].events |= POLLERR | POLLHUP;
1504  }
1505 
1506  std::vector<struct pollfd> vpollfds;
1507  vpollfds.reserve(pollfds.size());
1508  for (auto it : pollfds) {
1509  vpollfds.push_back(std::move(it.second));
1510  }
1511 
1512  if (poll(vpollfds.data(), vpollfds.size(), SELECT_TIMEOUT_MILLISECONDS) <
1513  0) {
1514  return;
1515  }
1516 
1517  if (interruptNet) {
1518  return;
1519  }
1520 
1521  for (struct pollfd pollfd_entry : vpollfds) {
1522  if (pollfd_entry.revents & POLLIN) {
1523  recv_set.insert(pollfd_entry.fd);
1524  }
1525  if (pollfd_entry.revents & POLLOUT) {
1526  send_set.insert(pollfd_entry.fd);
1527  }
1528  if (pollfd_entry.revents & (POLLERR | POLLHUP)) {
1529  error_set.insert(pollfd_entry.fd);
1530  }
1531  }
1532 }
1533 #else
1534 void CConnman::SocketEvents(std::set<SOCKET> &recv_set,
1535  std::set<SOCKET> &send_set,
1536  std::set<SOCKET> &error_set) {
1537  std::set<SOCKET> recv_select_set, send_select_set, error_select_set;
1538  if (!GenerateSelectSet(recv_select_set, send_select_set,
1539  error_select_set)) {
1541  std::chrono::milliseconds(SELECT_TIMEOUT_MILLISECONDS));
1542  return;
1543  }
1544 
1545  //
1546  // Find which sockets have data to receive
1547  //
1548  struct timeval timeout;
1549  timeout.tv_sec = 0;
1550  // frequency to poll pnode->vSend
1551  timeout.tv_usec = SELECT_TIMEOUT_MILLISECONDS * 1000;
1552 
1553  fd_set fdsetRecv;
1554  fd_set fdsetSend;
1555  fd_set fdsetError;
1556  FD_ZERO(&fdsetRecv);
1557  FD_ZERO(&fdsetSend);
1558  FD_ZERO(&fdsetError);
1559  SOCKET hSocketMax = 0;
1560 
1561  for (SOCKET hSocket : recv_select_set) {
1562  FD_SET(hSocket, &fdsetRecv);
1563  hSocketMax = std::max(hSocketMax, hSocket);
1564  }
1565 
1566  for (SOCKET hSocket : send_select_set) {
1567  FD_SET(hSocket, &fdsetSend);
1568  hSocketMax = std::max(hSocketMax, hSocket);
1569  }
1570 
1571  for (SOCKET hSocket : error_select_set) {
1572  FD_SET(hSocket, &fdsetError);
1573  hSocketMax = std::max(hSocketMax, hSocket);
1574  }
1575 
1576  int nSelect =
1577  select(hSocketMax + 1, &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
1578 
1579  if (interruptNet) {
1580  return;
1581  }
1582 
1583  if (nSelect == SOCKET_ERROR) {
1584  int nErr = WSAGetLastError();
1585  LogPrintf("socket select error %s\n", NetworkErrorString(nErr));
1586  for (unsigned int i = 0; i <= hSocketMax; i++) {
1587  FD_SET(i, &fdsetRecv);
1588  }
1589  FD_ZERO(&fdsetSend);
1590  FD_ZERO(&fdsetError);
1591  if (!interruptNet.sleep_for(
1592  std::chrono::milliseconds(SELECT_TIMEOUT_MILLISECONDS))) {
1593  return;
1594  }
1595  }
1596 
1597  for (SOCKET hSocket : recv_select_set) {
1598  if (FD_ISSET(hSocket, &fdsetRecv)) {
1599  recv_set.insert(hSocket);
1600  }
1601  }
1602 
1603  for (SOCKET hSocket : send_select_set) {
1604  if (FD_ISSET(hSocket, &fdsetSend)) {
1605  send_set.insert(hSocket);
1606  }
1607  }
1608 
1609  for (SOCKET hSocket : error_select_set) {
1610  if (FD_ISSET(hSocket, &fdsetError)) {
1611  error_set.insert(hSocket);
1612  }
1613  }
1614 }
1615 #endif
1616 
1618  std::set<SOCKET> recv_set, send_set, error_set;
1619  SocketEvents(recv_set, send_set, error_set);
1620 
1621  if (interruptNet) {
1622  return;
1623  }
1624 
1625  //
1626  // Accept new connections
1627  //
1628  for (const ListenSocket &hListenSocket : vhListenSocket) {
1629  if (hListenSocket.socket != INVALID_SOCKET &&
1630  recv_set.count(hListenSocket.socket) > 0) {
1631  AcceptConnection(hListenSocket);
1632  }
1633  }
1634 
1635  //
1636  // Service each socket
1637  //
1638  std::vector<CNode *> vNodesCopy;
1639  {
1640  LOCK(cs_vNodes);
1641  vNodesCopy = vNodes;
1642  for (CNode *pnode : vNodesCopy) {
1643  pnode->AddRef();
1644  }
1645  }
1646  for (CNode *pnode : vNodesCopy) {
1647  if (interruptNet) {
1648  return;
1649  }
1650 
1651  //
1652  // Receive
1653  //
1654  bool recvSet = false;
1655  bool sendSet = false;
1656  bool errorSet = false;
1657  {
1658  LOCK(pnode->cs_hSocket);
1659  if (pnode->hSocket == INVALID_SOCKET) {
1660  continue;
1661  }
1662  recvSet = recv_set.count(pnode->hSocket) > 0;
1663  sendSet = send_set.count(pnode->hSocket) > 0;
1664  errorSet = error_set.count(pnode->hSocket) > 0;
1665  }
1666  if (recvSet || errorSet) {
1667  // typical socket buffer is 8K-64K
1668  char pchBuf[0x10000];
1669  int32_t nBytes = 0;
1670  {
1671  LOCK(pnode->cs_hSocket);
1672  if (pnode->hSocket == INVALID_SOCKET) {
1673  continue;
1674  }
1675  nBytes =
1676  recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
1677  }
1678  if (nBytes > 0) {
1679  bool notify = false;
1680  if (!pnode->ReceiveMsgBytes(*config, pchBuf, nBytes, notify)) {
1681  pnode->CloseSocketDisconnect();
1682  }
1683  RecordBytesRecv(nBytes);
1684  if (notify) {
1685  size_t nSizeAdded = 0;
1686  auto it(pnode->vRecvMsg.begin());
1687  for (; it != pnode->vRecvMsg.end(); ++it) {
1688  // vRecvMsg contains only completed CNetMessage
1689  // the single possible partially deserialized message
1690  // are held by TransportDeserializer
1691  nSizeAdded += it->m_raw_message_size;
1692  }
1693  {
1694  LOCK(pnode->cs_vProcessMsg);
1695  pnode->vProcessMsg.splice(pnode->vProcessMsg.end(),
1696  pnode->vRecvMsg,
1697  pnode->vRecvMsg.begin(), it);
1698  pnode->nProcessQueueSize += nSizeAdded;
1699  pnode->fPauseRecv =
1700  pnode->nProcessQueueSize > nReceiveFloodSize;
1701  }
1703  }
1704  } else if (nBytes == 0) {
1705  // socket closed gracefully
1706  if (!pnode->fDisconnect) {
1707  LogPrint(BCLog::NET, "socket closed for peer=%d\n",
1708  pnode->GetId());
1709  }
1710  pnode->CloseSocketDisconnect();
1711  } else if (nBytes < 0) {
1712  // error
1713  int nErr = WSAGetLastError();
1714  if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE &&
1715  nErr != WSAEINTR && nErr != WSAEINPROGRESS) {
1716  if (!pnode->fDisconnect) {
1718  "socket recv error for peer=%d: %s\n",
1719  pnode->GetId(), NetworkErrorString(nErr));
1720  }
1721  pnode->CloseSocketDisconnect();
1722  }
1723  }
1724  }
1725 
1726  //
1727  // Send
1728  //
1729  if (sendSet) {
1730  LOCK(pnode->cs_vSend);
1731  size_t nBytes = SocketSendData(pnode);
1732  if (nBytes) {
1733  RecordBytesSent(nBytes);
1734  }
1735  }
1736 
1737  InactivityCheck(pnode);
1738  }
1739  {
1740  LOCK(cs_vNodes);
1741  for (CNode *pnode : vNodesCopy) {
1742  pnode->Release();
1743  }
1744  }
1745 }
1746 
1748  while (!interruptNet) {
1749  DisconnectNodes();
1751  SocketHandler();
1752  }
1753 }
1754 
1756  {
1757  LOCK(mutexMsgProc);
1758  fMsgProcWake = true;
1759  }
1760  condMsgProc.notify_one();
1761 }
1762 
1763 #ifdef USE_UPNP
1764 static CThreadInterrupt g_upnp_interrupt;
1765 static std::thread g_upnp_thread;
1766 static void ThreadMapPort() {
1767  std::string port = strprintf("%u", GetListenPort());
1768  const char *multicastif = nullptr;
1769  const char *minissdpdpath = nullptr;
1770  struct UPNPDev *devlist = nullptr;
1771  char lanaddr[64];
1772 
1773  int error = 0;
1774 #if MINIUPNPC_API_VERSION < 14
1775  devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
1776 #else
1777  devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, 2, &error);
1778 #endif
1779 
1780  struct UPNPUrls urls;
1781  struct IGDdatas data;
1782  int r;
1783 
1784  r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
1785  if (r == 1) {
1786  if (fDiscover) {
1787  char externalIPAddress[40];
1788  r = UPNP_GetExternalIPAddress(
1789  urls.controlURL, data.first.servicetype, externalIPAddress);
1790  if (r != UPNPCOMMAND_SUCCESS) {
1791  LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r);
1792  } else {
1793  if (externalIPAddress[0]) {
1794  CNetAddr resolved;
1795  if (LookupHost(externalIPAddress, resolved, false)) {
1796  LogPrintf("UPnP: ExternalIPAddress = %s\n",
1797  resolved.ToString());
1798  AddLocal(resolved, LOCAL_UPNP);
1799  }
1800  } else {
1801  LogPrintf("UPnP: GetExternalIPAddress failed.\n");
1802  }
1803  }
1804  }
1805 
1806  std::string strDesc = PACKAGE_NAME " " + FormatFullVersion();
1807 
1808  do {
1809  r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1810  port.c_str(), port.c_str(), lanaddr,
1811  strDesc.c_str(), "TCP", 0, "0");
1812 
1813  if (r != UPNPCOMMAND_SUCCESS) {
1814  LogPrintf(
1815  "AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
1816  port, port, lanaddr, r, strupnperror(r));
1817  } else {
1818  LogPrintf("UPnP Port Mapping successful.\n");
1819  }
1820  } while (g_upnp_interrupt.sleep_for(std::chrono::minutes(20)));
1821 
1822  r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype,
1823  port.c_str(), "TCP", 0);
1824  LogPrintf("UPNP_DeletePortMapping() returned: %d\n", r);
1825  freeUPNPDevlist(devlist);
1826  devlist = nullptr;
1827  FreeUPNPUrls(&urls);
1828  } else {
1829  LogPrintf("No valid UPnP IGDs found\n");
1830  freeUPNPDevlist(devlist);
1831  devlist = nullptr;
1832  if (r != 0) {
1833  FreeUPNPUrls(&urls);
1834  }
1835  }
1836 }
1837 
1838 void StartMapPort() {
1839  if (!g_upnp_thread.joinable()) {
1840  assert(!g_upnp_interrupt);
1841  g_upnp_thread = std::thread(
1842  (std::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort)));
1843  }
1844 }
1845 
1846 void InterruptMapPort() {
1847  if (g_upnp_thread.joinable()) {
1848  g_upnp_interrupt();
1849  }
1850 }
1851 
1852 void StopMapPort() {
1853  if (g_upnp_thread.joinable()) {
1854  g_upnp_thread.join();
1855  g_upnp_interrupt.reset();
1856  }
1857 }
1858 
1859 #else
1861  // Intentionally left blank.
1862 }
1864  // Intentionally left blank.
1865 }
1866 void StopMapPort() {
1867  // Intentionally left blank.
1868 }
1869 #endif
1870 
1872  FastRandomContext rng;
1873  std::vector<std::string> seeds =
1875  // Number of seeds left before testing if we have enough connections
1876  int seeds_right_now = 0;
1877  int found = 0;
1878 
1879  if (gArgs.GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED)) {
1880  // When -forcednsseed is provided, query all.
1881  seeds_right_now = seeds.size();
1882  } else if (addrman.size() == 0) {
1883  // If we have no known peers, query all.
1884  // This will occur on the first run, or if peers.dat has been
1885  // deleted.
1886  seeds_right_now = seeds.size();
1887  }
1888 
1889  // goal: only query DNS seed if address need is acute
1890  // * If we have a reasonable number of peers in addrman, spend
1891  // some time trying them first. This improves user privacy by
1892  // creating fewer identifying DNS requests, reduces trust by
1893  // giving seeds less influence on the network topology, and
1894  // reduces traffic to the seeds.
1895  // * When querying DNS seeds query a few at once, this ensures
1896  // that we don't give DNS seeds the ability to eclipse nodes
1897  // that query them.
1898  // * If we continue having problems, eventually query all the
1899  // DNS seeds, and if that fails too, also try the fixed seeds.
1900  // (done in ThreadOpenConnections)
1901  const std::chrono::seconds seeds_wait_time =
1905 
1906  for (const std::string &seed : seeds) {
1907  if (seeds_right_now == 0) {
1908  seeds_right_now += DNSSEEDS_TO_QUERY_AT_ONCE;
1909 
1910  if (addrman.size() > 0) {
1911  LogPrintf("Waiting %d seconds before querying DNS seeds.\n",
1912  seeds_wait_time.count());
1913  std::chrono::seconds to_wait = seeds_wait_time;
1914  while (to_wait.count() > 0) {
1915  // if sleeping for the MANY_PEERS interval, wake up
1916  // early to see if we have enough peers and can stop
1917  // this thread entirely freeing up its resources
1918  std::chrono::seconds w =
1919  std::min(DNSSEEDS_DELAY_FEW_PEERS, to_wait);
1920  if (!interruptNet.sleep_for(w)) {
1921  return;
1922  }
1923  to_wait -= w;
1924 
1925  int nRelevant = 0;
1926  {
1927  LOCK(cs_vNodes);
1928  for (const CNode *pnode : vNodes) {
1929  if (pnode->fSuccessfullyConnected &&
1930  pnode->IsOutboundOrBlockRelayConn()) {
1931  ++nRelevant;
1932  }
1933  }
1934  }
1935  if (nRelevant >= 2) {
1936  if (found > 0) {
1937  LogPrintf("%d addresses found from DNS seeds\n",
1938  found);
1939  LogPrintf(
1940  "P2P peers available. Finished DNS seeding.\n");
1941  } else {
1942  LogPrintf(
1943  "P2P peers available. Skipped DNS seeding.\n");
1944  }
1945  return;
1946  }
1947  }
1948  }
1949  }
1950 
1951  if (interruptNet) {
1952  return;
1953  }
1954 
1955  // hold off on querying seeds if P2P network deactivated
1956  if (!fNetworkActive) {
1957  LogPrintf("Waiting for network to be reactivated before querying "
1958  "DNS seeds.\n");
1959  do {
1960  if (!interruptNet.sleep_for(std::chrono::seconds{1})) {
1961  return;
1962  }
1963  } while (!fNetworkActive);
1964  }
1965 
1966  LogPrintf("Loading addresses from DNS seed %s\n", seed);
1967  if (HaveNameProxy()) {
1968  AddAddrFetch(seed);
1969  } else {
1970  std::vector<CNetAddr> vIPs;
1971  std::vector<CAddress> vAdd;
1972  ServiceFlags requiredServiceBits =
1974  std::string host = strprintf("x%x.%s", requiredServiceBits, seed);
1975  CNetAddr resolveSource;
1976  if (!resolveSource.SetInternal(host)) {
1977  continue;
1978  }
1979 
1980  // Limits number of IPs learned from a DNS seed
1981  unsigned int nMaxIPs = 256;
1982  if (LookupHost(host, vIPs, nMaxIPs, true)) {
1983  for (const CNetAddr &ip : vIPs) {
1984  int nOneDay = 24 * 3600;
1985  CAddress addr = CAddress(
1987  requiredServiceBits);
1988  // Use a random age between 3 and 7 days old.
1989  addr.nTime =
1990  GetTime() - 3 * nOneDay - rng.randrange(4 * nOneDay);
1991  vAdd.push_back(addr);
1992  found++;
1993  }
1994  addrman.Add(vAdd, resolveSource);
1995  } else {
1996  // We now avoid directly using results from DNS Seeds which do
1997  // not support service bit filtering, instead using them as a
1998  // addrfetch to get nodes with our desired service bits.
1999  AddAddrFetch(seed);
2000  }
2001  }
2002  --seeds_right_now;
2003  }
2004  LogPrintf("%d addresses found from DNS seeds\n", found);
2005 }
2006 
2008  int64_t nStart = GetTimeMillis();
2009 
2010  CAddrDB adb(config->GetChainParams());
2011  adb.Write(addrman);
2012 
2013  LogPrint(BCLog::NET, "Flushed %d addresses to peers.dat %dms\n",
2014  addrman.size(), GetTimeMillis() - nStart);
2015 }
2016 
2018  std::string strDest;
2019  {
2021  if (m_addr_fetches.empty()) {
2022  return;
2023  }
2024  strDest = m_addr_fetches.front();
2025  m_addr_fetches.pop_front();
2026  }
2027  CAddress addr;
2028  CSemaphoreGrant grant(*semOutbound, true);
2029  if (grant) {
2030  OpenNetworkConnection(addr, false, &grant, strDest.c_str(),
2032  }
2033 }
2034 
2037 }
2038 
2041  LogPrint(BCLog::NET, "net: setting try another outbound peer=%s\n",
2042  flag ? "true" : "false");
2043 }
2044 
2045 // Return the number of peers we have over our outbound connection limit.
2046 // Exclude peers that are marked for disconnect, or are going to be disconnected
2047 // soon (eg ADDR_FETCH and FEELER).
2048 // Also exclude peers that haven't finished initial connection handshake yet (so
2049 // that we don't decide we're over our desired connection limit, and then evict
2050 // some peer that has finished the handshake).
2052  int nOutbound = 0;
2053  {
2054  LOCK(cs_vNodes);
2055  for (const CNode *pnode : vNodes) {
2056  if (pnode->fSuccessfullyConnected && !pnode->fDisconnect &&
2057  pnode->IsOutboundOrBlockRelayConn()) {
2058  ++nOutbound;
2059  }
2060  }
2061  }
2062  return std::max(
2064 }
2065 
2066 void CConnman::ThreadOpenConnections(const std::vector<std::string> connect) {
2067  // Connect to specific addresses
2068  if (!connect.empty()) {
2069  for (int64_t nLoop = 0;; nLoop++) {
2070  ProcessAddrFetch();
2071  for (const std::string &strAddr : connect) {
2072  CAddress addr(CService(), NODE_NONE);
2073  OpenNetworkConnection(addr, false, nullptr, strAddr.c_str(),
2075  for (int i = 0; i < 10 && i < nLoop; i++) {
2076  if (!interruptNet.sleep_for(
2077  std::chrono::milliseconds(500))) {
2078  return;
2079  }
2080  }
2081  }
2082  if (!interruptNet.sleep_for(std::chrono::milliseconds(500))) {
2083  return;
2084  }
2085  }
2086  }
2087 
2088  // Initiate network connections
2089  int64_t nStart = GetTime();
2090 
2091  // Minimum time before next feeler connection (in microseconds).
2092  int64_t nNextFeeler =
2093  PoissonNextSend(nStart * 1000 * 1000, FEELER_INTERVAL);
2094  while (!interruptNet) {
2095  ProcessAddrFetch();
2096 
2097  if (!interruptNet.sleep_for(std::chrono::milliseconds(500))) {
2098  return;
2099  }
2100 
2101  CSemaphoreGrant grant(*semOutbound);
2102  if (interruptNet) {
2103  return;
2104  }
2105 
2106  // Add seed nodes if DNS seeds are all down (an infrastructure attack?).
2107  // Note that we only do this if we started with an empty peers.dat,
2108  // (in which case we will query DNS seeds immediately) *and* the DNS
2109  // seeds have not returned any results.
2110  if (addrman.size() == 0 && (GetTime() - nStart > 60)) {
2111  static bool done = false;
2112  if (!done) {
2113  LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be "
2114  "available.\n");
2115  CNetAddr local;
2116  local.SetInternal("fixedseeds");
2118  local);
2119  done = true;
2120  }
2121  }
2122 
2123  //
2124  // Choose an address to connect to based on most recently seen
2125  //
2126  CAddress addrConnect;
2127 
2128  // Only connect out to one peer per network group (/16 for IPv4).
2129  int nOutboundFullRelay = 0;
2130  int nOutboundBlockRelay = 0;
2131  std::set<std::vector<uint8_t>> setConnected;
2132 
2133  {
2134  LOCK(cs_vNodes);
2135  for (const CNode *pnode : vNodes) {
2136  if (pnode->IsFullOutboundConn()) {
2137  nOutboundFullRelay++;
2138  }
2139  if (pnode->IsBlockOnlyConn()) {
2140  nOutboundBlockRelay++;
2141  }
2142 
2143  // Netgroups for inbound and manual peers are not excluded
2144  // because our goal here is to not use multiple of our
2145  // limited outbound slots on a single netgroup but inbound
2146  // and manual peers do not use our outbound slots. Inbound
2147  // peers also have the added issue that they could be attacker
2148  // controlled and could be used to prevent us from connecting
2149  // to particular hosts if we used them here.
2150  switch (pnode->m_conn_type) {
2153  break;
2158  setConnected.insert(
2159  pnode->addr.GetGroup(addrman.m_asmap));
2160  } // no default case, so the compiler can warn about missing
2161  // cases
2162  }
2163  }
2164 
2166  int64_t nTime = GetTimeMicros();
2167  bool anchor = false;
2168  bool fFeeler = false;
2169 
2170  // Determine what type of connection to open. Opening
2171  // BLOCK_RELAY connections to addresses from anchors.dat gets the
2172  // highest priority. Then we open OUTBOUND_FULL_RELAY priority until we
2173  // meet our full-relay capacity. Then we open BLOCK_RELAY connection
2174  // until we hit our block-relay-only peer limit.
2175  // GetTryNewOutboundPeer() gets set when a stale tip is detected, so we
2176  // try opening an additional OUTBOUND_FULL_RELAY connection. If none of
2177  // these conditions are met, check the nNextFeeler timer to decide if
2178  // we should open a FEELER.
2179 
2180  if (!m_anchors.empty() &&
2181  (nOutboundBlockRelay < m_max_outbound_block_relay)) {
2182  conn_type = ConnectionType::BLOCK_RELAY;
2183  anchor = true;
2184  } else if (nOutboundFullRelay < m_max_outbound_full_relay) {
2185  // OUTBOUND_FULL_RELAY
2186  } else if (nOutboundBlockRelay < m_max_outbound_block_relay) {
2187  conn_type = ConnectionType::BLOCK_RELAY;
2188  } else if (GetTryNewOutboundPeer()) {
2189  // OUTBOUND_FULL_RELAY
2190  } else if (nTime > nNextFeeler) {
2191  nNextFeeler = PoissonNextSend(nTime, FEELER_INTERVAL);
2192  conn_type = ConnectionType::FEELER;
2193  fFeeler = true;
2194  } else {
2195  // skip to next iteration of while loop
2196  continue;
2197  }
2198 
2200 
2201  int64_t nANow = GetAdjustedTime();
2202  int nTries = 0;
2203  while (!interruptNet) {
2204  if (anchor && !m_anchors.empty()) {
2205  const CAddress addr = m_anchors.back();
2206  m_anchors.pop_back();
2207  if (!addr.IsValid() || IsLocal(addr) || !IsReachable(addr) ||
2209  setConnected.count(addr.GetGroup(addrman.m_asmap))) {
2210  continue;
2211  }
2212  addrConnect = addr;
2214  "Trying to make an anchor connection to %s\n",
2215  addrConnect.ToString());
2216  break;
2217  }
2218  // If we didn't find an appropriate destination after trying 100
2219  // addresses fetched from addrman, stop this loop, and let the outer
2220  // loop run again (which sleeps, adds seed nodes, recalculates
2221  // already-connected network ranges, ...) before trying new addrman
2222  // addresses.
2223  nTries++;
2224  if (nTries > 100) {
2225  break;
2226  }
2227 
2229 
2230  // SelectTriedCollision returns an invalid address if it is empty.
2231  if (!fFeeler || !addr.IsValid()) {
2232  addr = addrman.Select(fFeeler);
2233  }
2234 
2235  // Require outbound connections, other than feelers, to be to
2236  // distinct network groups
2237  if (!fFeeler &&
2238  setConnected.count(addr.GetGroup(addrman.m_asmap))) {
2239  break;
2240  }
2241 
2242  // if we selected an invalid or local address, restart
2243  if (!addr.IsValid() || IsLocal(addr)) {
2244  break;
2245  }
2246 
2247  if (!IsReachable(addr)) {
2248  continue;
2249  }
2250 
2251  // only consider very recently tried nodes after 30 failed attempts
2252  if (nANow - addr.nLastTry < 600 && nTries < 30) {
2253  continue;
2254  }
2255 
2256  // for non-feelers, require all the services we'll want,
2257  // for feelers, only require they be a full node (only because most
2258  // SPV clients don't have a good address DB available)
2259  if (!fFeeler && !HasAllDesirableServiceFlags(addr.nServices)) {
2260  continue;
2261  }
2262 
2263  if (fFeeler && !MayHaveUsefulAddressDB(addr.nServices)) {
2264  continue;
2265  }
2266 
2267  // do not allow non-default ports, unless after 50 invalid addresses
2268  // selected already.
2269  if (addr.GetPort() != config->GetChainParams().GetDefaultPort() &&
2270  nTries < 50) {
2271  continue;
2272  }
2273 
2274  addrConnect = addr;
2275  break;
2276  }
2277 
2278  if (addrConnect.IsValid()) {
2279  if (fFeeler) {
2280  // Add small amount of random noise before connection to avoid
2281  // synchronization.
2282  int randsleep = GetRandInt(FEELER_SLEEP_WINDOW * 1000);
2283  if (!interruptNet.sleep_for(
2284  std::chrono::milliseconds(randsleep))) {
2285  return;
2286  }
2287  LogPrint(BCLog::NET, "Making feeler connection to %s\n",
2288  addrConnect.ToString());
2289  }
2290 
2291  OpenNetworkConnection(addrConnect,
2292  int(setConnected.size()) >=
2293  std::min(nMaxConnections - 1, 2),
2294  &grant, nullptr, conn_type);
2295  }
2296  }
2297 }
2298 
2299 std::vector<CAddress> CConnman::GetCurrentBlockRelayOnlyConns() const {
2300  std::vector<CAddress> ret;
2301  LOCK(cs_vNodes);
2302  for (const CNode *pnode : vNodes) {
2303  if (pnode->IsBlockOnlyConn()) {
2304  ret.push_back(pnode->addr);
2305  }
2306  }
2307 
2308  return ret;
2309 }
2310 
2311 std::vector<AddedNodeInfo> CConnman::GetAddedNodeInfo() {
2312  std::vector<AddedNodeInfo> ret;
2313 
2314  std::list<std::string> lAddresses(0);
2315  {
2317  ret.reserve(vAddedNodes.size());
2318  std::copy(vAddedNodes.cbegin(), vAddedNodes.cend(),
2319  std::back_inserter(lAddresses));
2320  }
2321 
2322  // Build a map of all already connected addresses (by IP:port and by name)
2323  // to inbound/outbound and resolved CService
2324  std::map<CService, bool> mapConnected;
2325  std::map<std::string, std::pair<bool, CService>> mapConnectedByName;
2326  {
2327  LOCK(cs_vNodes);
2328  for (const CNode *pnode : vNodes) {
2329  if (pnode->addr.IsValid()) {
2330  mapConnected[pnode->addr] = pnode->IsInboundConn();
2331  }
2332  std::string addrName = pnode->GetAddrName();
2333  if (!addrName.empty()) {
2334  mapConnectedByName[std::move(addrName)] =
2335  std::make_pair(pnode->IsInboundConn(),
2336  static_cast<const CService &>(pnode->addr));
2337  }
2338  }
2339  }
2340 
2341  for (const std::string &strAddNode : lAddresses) {
2342  CService service(LookupNumeric(strAddNode, Params().GetDefaultPort()));
2343  AddedNodeInfo addedNode{strAddNode, CService(), false, false};
2344  if (service.IsValid()) {
2345  // strAddNode is an IP:port
2346  auto it = mapConnected.find(service);
2347  if (it != mapConnected.end()) {
2348  addedNode.resolvedAddress = service;
2349  addedNode.fConnected = true;
2350  addedNode.fInbound = it->second;
2351  }
2352  } else {
2353  // strAddNode is a name
2354  auto it = mapConnectedByName.find(strAddNode);
2355  if (it != mapConnectedByName.end()) {
2356  addedNode.resolvedAddress = it->second.second;
2357  addedNode.fConnected = true;
2358  addedNode.fInbound = it->second.first;
2359  }
2360  }
2361  ret.emplace_back(std::move(addedNode));
2362  }
2363 
2364  return ret;
2365 }
2366 
2368  while (true) {
2369  CSemaphoreGrant grant(*semAddnode);
2370  std::vector<AddedNodeInfo> vInfo = GetAddedNodeInfo();
2371  bool tried = false;
2372  for (const AddedNodeInfo &info : vInfo) {
2373  if (!info.fConnected) {
2374  if (!grant.TryAcquire()) {
2375  // If we've used up our semaphore and need a new one, let's
2376  // not wait here since while we are waiting the
2377  // addednodeinfo state might change.
2378  break;
2379  }
2380  tried = true;
2381  CAddress addr(CService(), NODE_NONE);
2382  OpenNetworkConnection(addr, false, &grant,
2383  info.strAddedNode.c_str(),
2385  if (!interruptNet.sleep_for(std::chrono::milliseconds(500))) {
2386  return;
2387  }
2388  }
2389  }
2390  // Retry every 60 seconds if a connection was attempted, otherwise two
2391  // seconds.
2392  if (!interruptNet.sleep_for(std::chrono::seconds(tried ? 60 : 2))) {
2393  return;
2394  }
2395  }
2396 }
2397 
2398 // If successful, this moves the passed grant to the constructed node.
2400  bool fCountFailure,
2401  CSemaphoreGrant *grantOutbound,
2402  const char *pszDest,
2403  ConnectionType conn_type) {
2404  assert(conn_type != ConnectionType::INBOUND);
2405 
2406  //
2407  // Initiate outbound network connection
2408  //
2409  if (interruptNet) {
2410  return;
2411  }
2412  if (!fNetworkActive) {
2413  return;
2414  }
2415  if (!pszDest) {
2416  bool banned_or_discouraged =
2417  m_banman && (m_banman->IsDiscouraged(addrConnect) ||
2418  m_banman->IsBanned(addrConnect));
2419  if (IsLocal(addrConnect) ||
2420  FindNode(static_cast<CNetAddr>(addrConnect)) ||
2421  banned_or_discouraged || FindNode(addrConnect.ToStringIPPort())) {
2422  return;
2423  }
2424  } else if (FindNode(std::string(pszDest))) {
2425  return;
2426  }
2427 
2428  CNode *pnode = ConnectNode(addrConnect, pszDest, fCountFailure, conn_type);
2429 
2430  if (!pnode) {
2431  return;
2432  }
2433  if (grantOutbound) {
2434  grantOutbound->MoveTo(pnode->grantOutbound);
2435  }
2436 
2437  m_msgproc->InitializeNode(*config, pnode);
2438  {
2439  LOCK(cs_vNodes);
2440  vNodes.push_back(pnode);
2441  }
2442 }
2443 
2445  while (!flagInterruptMsgProc) {
2446  std::vector<CNode *> vNodesCopy;
2447  {
2448  LOCK(cs_vNodes);
2449  vNodesCopy = vNodes;
2450  for (CNode *pnode : vNodesCopy) {
2451  pnode->AddRef();
2452  }
2453  }
2454 
2455  bool fMoreWork = false;
2456 
2457  for (CNode *pnode : vNodesCopy) {
2458  if (pnode->fDisconnect) {
2459  continue;
2460  }
2461 
2462  // Receive messages
2463  bool fMoreNodeWork = m_msgproc->ProcessMessages(
2464  *config, pnode, flagInterruptMsgProc);
2465  fMoreWork |= (fMoreNodeWork && !pnode->fPauseSend);
2466  if (flagInterruptMsgProc) {
2467  return;
2468  }
2469 
2470  // Send messages
2471  {
2472  LOCK(pnode->cs_sendProcessing);
2474  }
2475 
2476  if (flagInterruptMsgProc) {
2477  return;
2478  }
2479  }
2480 
2481  {
2482  LOCK(cs_vNodes);
2483  for (CNode *pnode : vNodesCopy) {
2484  pnode->Release();
2485  }
2486  }
2487 
2488  WAIT_LOCK(mutexMsgProc, lock);
2489  if (!fMoreWork) {
2490  condMsgProc.wait_until(lock,
2491  std::chrono::steady_clock::now() +
2492  std::chrono::milliseconds(100),
2493  [this]() EXCLUSIVE_LOCKS_REQUIRED(
2494  mutexMsgProc) { return fMsgProcWake; });
2495  }
2496  fMsgProcWake = false;
2497  }
2498 }
2499 
2500 bool CConnman::BindListenPort(const CService &addrBind, bilingual_str &strError,
2501  NetPermissionFlags permissions) {
2502  int nOne = 1;
2503 
2504  // Create socket for listening for incoming connections
2505  struct sockaddr_storage sockaddr;
2506  socklen_t len = sizeof(sockaddr);
2507  if (!addrBind.GetSockAddr((struct sockaddr *)&sockaddr, &len)) {
2508  strError = strprintf(
2509  Untranslated("Error: Bind address family for %s not supported"),
2510  addrBind.ToString());
2511  LogPrintf("%s\n", strError.original);
2512  return false;
2513  }
2514 
2515  SOCKET hListenSocket = CreateSocket(addrBind);
2516  if (hListenSocket == INVALID_SOCKET) {
2517  strError =
2518  strprintf(Untranslated("Error: Couldn't open socket for incoming "
2519  "connections (socket returned error %s)"),
2521  LogPrintf("%s\n", strError.original);
2522  return false;
2523  }
2524 
2525  // Allow binding if the port is still in TIME_WAIT state after
2526  // the program was closed and restarted.
2527  setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (sockopt_arg_type)&nOne,
2528  sizeof(int));
2529 
2530  // Some systems don't have IPV6_V6ONLY but are always v6only; others do have
2531  // the option and enable it by default or not. Try to enable it, if
2532  // possible.
2533  if (addrBind.IsIPv6()) {
2534 #ifdef IPV6_V6ONLY
2535  setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY,
2536  (sockopt_arg_type)&nOne, sizeof(int));
2537 #endif
2538 #ifdef WIN32
2539  int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED;
2540  setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL,
2541  (sockopt_arg_type)&nProtLevel, sizeof(int));
2542 #endif
2543  }
2544 
2545  if (::bind(hListenSocket, (struct sockaddr *)&sockaddr, len) ==
2546  SOCKET_ERROR) {
2547  int nErr = WSAGetLastError();
2548  if (nErr == WSAEADDRINUSE) {
2549  strError = strprintf(_("Unable to bind to %s on this computer. %s "
2550  "is probably already running."),
2551  addrBind.ToString(), PACKAGE_NAME);
2552  } else {
2553  strError = strprintf(_("Unable to bind to %s on this computer "
2554  "(bind returned error %s)"),
2555  addrBind.ToString(), NetworkErrorString(nErr));
2556  }
2557  LogPrintf("%s\n", strError.original);
2558  CloseSocket(hListenSocket);
2559  return false;
2560  }
2561  LogPrintf("Bound to %s\n", addrBind.ToString());
2562 
2563  // Listen for incoming connections
2564  if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR) {
2565  strError = strprintf(_("Error: Listening for incoming connections "
2566  "failed (listen returned error %s)"),
2568  LogPrintf("%s\n", strError.original);
2569  CloseSocket(hListenSocket);
2570  return false;
2571  }
2572 
2573  vhListenSocket.push_back(ListenSocket(hListenSocket, permissions));
2574  return true;
2575 }
2576 
2577 void Discover() {
2578  if (!fDiscover) {
2579  return;
2580  }
2581 
2582 #ifdef WIN32
2583  // Get local host IP
2584  char pszHostName[256] = "";
2585  if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) {
2586  std::vector<CNetAddr> vaddr;
2587  if (LookupHost(pszHostName, vaddr, 0, true)) {
2588  for (const CNetAddr &addr : vaddr) {
2589  if (AddLocal(addr, LOCAL_IF)) {
2590  LogPrintf("%s: %s - %s\n", __func__, pszHostName,
2591  addr.ToString());
2592  }
2593  }
2594  }
2595  }
2596 #elif (HAVE_DECL_GETIFADDRS && HAVE_DECL_FREEIFADDRS)
2597  // Get local host ip
2598  struct ifaddrs *myaddrs;
2599  if (getifaddrs(&myaddrs) == 0) {
2600  for (struct ifaddrs *ifa = myaddrs; ifa != nullptr;
2601  ifa = ifa->ifa_next) {
2602  if (ifa->ifa_addr == nullptr || (ifa->ifa_flags & IFF_UP) == 0 ||
2603  strcmp(ifa->ifa_name, "lo") == 0 ||
2604  strcmp(ifa->ifa_name, "lo0") == 0) {
2605  continue;
2606  }
2607  if (ifa->ifa_addr->sa_family == AF_INET) {
2608  struct sockaddr_in *s4 =
2609  reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
2610  CNetAddr addr(s4->sin_addr);
2611  if (AddLocal(addr, LOCAL_IF)) {
2612  LogPrintf("%s: IPv4 %s: %s\n", __func__, ifa->ifa_name,
2613  addr.ToString());
2614  }
2615  } else if (ifa->ifa_addr->sa_family == AF_INET6) {
2616  struct sockaddr_in6 *s6 =
2617  reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
2618  CNetAddr addr(s6->sin6_addr);
2619  if (AddLocal(addr, LOCAL_IF)) {
2620  LogPrintf("%s: IPv6 %s: %s\n", __func__, ifa->ifa_name,
2621  addr.ToString());
2622  }
2623  }
2624  }
2625  freeifaddrs(myaddrs);
2626  }
2627 #endif
2628 }
2629 
2630 void CConnman::SetNetworkActive(bool active) {
2631  LogPrintf("%s: %s\n", __func__, active);
2632 
2633  if (fNetworkActive == active) {
2634  return;
2635  }
2636 
2637  fNetworkActive = active;
2638  uiInterface.NotifyNetworkActiveChanged(fNetworkActive);
2639 }
2640 
2641 CConnman::CConnman(const Config &configIn, uint64_t nSeed0In, uint64_t nSeed1In,
2642  bool network_active)
2643  : config(&configIn), nSeed0(nSeed0In), nSeed1(nSeed1In) {
2644  SetTryNewOutboundPeer(false);
2645 
2646  Options connOptions;
2647  Init(connOptions);
2648  SetNetworkActive(network_active);
2649 }
2650 
2652  return nLastNodeId.fetch_add(1);
2653 }
2654 
2655 bool CConnman::Bind(const CService &addr, unsigned int flags,
2656  NetPermissionFlags permissions) {
2657  if (!(flags & BF_EXPLICIT) && !IsReachable(addr)) {
2658  return false;
2659  }
2660  bilingual_str strError;
2661  if (!BindListenPort(addr, strError, permissions)) {
2662  if ((flags & BF_REPORT_ERROR) && clientInterface) {
2663  clientInterface->ThreadSafeMessageBox(
2664  strError, "", CClientUIInterface::MSG_ERROR);
2665  }
2666  return false;
2667  }
2668 
2669  if (addr.IsRoutable() && fDiscover && !(flags & BF_DONT_ADVERTISE) &&
2670  !(permissions & PF_NOBAN)) {
2671  AddLocal(addr, LOCAL_BIND);
2672  }
2673 
2674  return true;
2675 }
2676 
2677 bool CConnman::InitBinds(const std::vector<CService> &binds,
2678  const std::vector<NetWhitebindPermissions> &whiteBinds,
2679  const std::vector<CService> &onion_binds) {
2680  bool fBound = false;
2681  for (const auto &addrBind : binds) {
2682  fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR),
2684  }
2685  for (const auto &addrBind : whiteBinds) {
2686  fBound |= Bind(addrBind.m_service, (BF_EXPLICIT | BF_REPORT_ERROR),
2687  addrBind.m_flags);
2688  }
2689  if (binds.empty() && whiteBinds.empty()) {
2690  struct in_addr inaddr_any;
2691  inaddr_any.s_addr = htonl(INADDR_ANY);
2692  struct in6_addr inaddr6_any = IN6ADDR_ANY_INIT;
2693  fBound |= Bind(CService(inaddr6_any, GetListenPort()), BF_NONE,
2695  fBound |= Bind(CService(inaddr_any, GetListenPort()),
2696  !fBound ? BF_REPORT_ERROR : BF_NONE,
2698  }
2699 
2700  for (const auto &addr_bind : onion_binds) {
2701  fBound |= Bind(addr_bind, BF_EXPLICIT | BF_DONT_ADVERTISE,
2703  }
2704 
2705  return fBound;
2706 }
2707 
2708 bool CConnman::Start(CScheduler &scheduler, const Options &connOptions) {
2709  Init(connOptions);
2710 
2711  {
2713  nTotalBytesRecv = 0;
2714  }
2715  {
2717  nTotalBytesSent = 0;
2718  nMaxOutboundTotalBytesSentInCycle = 0;
2719  nMaxOutboundCycleStartTime = 0;
2720  }
2721 
2722  if (fListen && !InitBinds(connOptions.vBinds, connOptions.vWhiteBinds,
2723  connOptions.onion_binds)) {
2724  if (clientInterface) {
2725  clientInterface->ThreadSafeMessageBox(
2726  _("Failed to listen on any port. Use -listen=0 if you want "
2727  "this."),
2729  }
2730  return false;
2731  }
2732 
2733  for (const auto &strDest : connOptions.vSeedNodes) {
2734  AddAddrFetch(strDest);
2735  }
2736 
2737  if (clientInterface) {
2738  clientInterface->InitMessage(_("Loading P2P addresses...").translated);
2739  }
2740  // Load addresses from peers.dat
2741  int64_t nStart = GetTimeMillis();
2742  {
2743  CAddrDB adb(config->GetChainParams());
2744  if (adb.Read(addrman)) {
2745  LogPrintf("Loaded %i addresses from peers.dat %dms\n",
2746  addrman.size(), GetTimeMillis() - nStart);
2747  } else {
2748  // Addrman can be in an inconsistent state after failure, reset it
2749  addrman.Clear();
2750  LogPrintf("Invalid or missing peers.dat; recreating\n");
2751  DumpAddresses();
2752  }
2753  }
2754 
2755  if (m_use_addrman_outgoing) {
2756  // Load addresses from anchors.dat
2759  if (m_anchors.size() > MAX_BLOCK_RELAY_ONLY_ANCHORS) {
2761  }
2762  LogPrintf(
2763  "%i block-relay-only anchors will be tried for connections.\n",
2764  m_anchors.size());
2765  }
2766 
2767  uiInterface.InitMessage(_("Starting network threads...").translated);
2768 
2769  fAddressesInitialized = true;
2770 
2771  if (semOutbound == nullptr) {
2772  // initialize semaphore
2773  semOutbound = std::make_unique<CSemaphore>(
2774  std::min(m_max_outbound, nMaxConnections));
2775  }
2776  if (semAddnode == nullptr) {
2777  // initialize semaphore
2778  semAddnode = std::make_unique<CSemaphore>(nMaxAddnode);
2779  }
2780 
2781  //
2782  // Start threads
2783  //
2784  assert(m_msgproc);
2785  InterruptSocks5(false);
2786  interruptNet.reset();
2787  flagInterruptMsgProc = false;
2788 
2789  {
2790  LOCK(mutexMsgProc);
2791  fMsgProcWake = false;
2792  }
2793 
2794  // Send and receive from sockets, accept connections
2795  threadSocketHandler = std::thread(
2796  &TraceThread<std::function<void()>>, "net",
2797  std::function<void()>(std::bind(&CConnman::ThreadSocketHandler, this)));
2798 
2799  if (!gArgs.GetBoolArg("-dnsseed", true)) {
2800  LogPrintf("DNS seeding disabled\n");
2801  } else {
2803  std::thread(&TraceThread<std::function<void()>>, "dnsseed",
2804  std::function<void()>(
2805  std::bind(&CConnman::ThreadDNSAddressSeed, this)));
2806  }
2807 
2808  // Initiate manual connections
2810  std::thread(&TraceThread<std::function<void()>>, "addcon",
2811  std::function<void()>(std::bind(
2813 
2814  if (connOptions.m_use_addrman_outgoing &&
2815  !connOptions.m_specified_outgoing.empty()) {
2816  if (clientInterface) {
2817  clientInterface->ThreadSafeMessageBox(
2818  _("Cannot provide specific connections and have addrman find "
2819  "outgoing connections at the same."),
2821  }
2822  return false;
2823  }
2824  if (connOptions.m_use_addrman_outgoing ||
2825  !connOptions.m_specified_outgoing.empty()) {
2827  std::thread(&TraceThread<std::function<void()>>, "opencon",
2828  std::function<void()>(
2829  std::bind(&CConnman::ThreadOpenConnections, this,
2830  connOptions.m_specified_outgoing)));
2831  }
2832 
2833  // Process messages
2835  std::thread(&TraceThread<std::function<void()>>, "msghand",
2836  std::function<void()>(
2837  std::bind(&CConnman::ThreadMessageHandler, this)));
2838 
2839  // Dump network addresses
2840  scheduler.scheduleEvery(
2841  [this]() {
2842  this->DumpAddresses();
2843  return true;
2844  },
2846 
2847  return true;
2848 }
2849 
2851 public:
2853 
2855 #ifdef WIN32
2856  // Shutdown Windows Sockets
2857  WSACleanup();
2858 #endif
2859  }
2860 };
2862 
2864  {
2865  LOCK(mutexMsgProc);
2866  flagInterruptMsgProc = true;
2867  }
2868  condMsgProc.notify_all();
2869 
2870  interruptNet();
2871  InterruptSocks5(true);
2872 
2873  if (semOutbound) {
2874  for (int i = 0; i < m_max_outbound; i++) {
2875  semOutbound->post();
2876  }
2877  }
2878 
2879  if (semAddnode) {
2880  for (int i = 0; i < nMaxAddnode; i++) {
2881  semAddnode->post();
2882  }
2883  }
2884 }
2885 
2887  if (threadMessageHandler.joinable()) {
2888  threadMessageHandler.join();
2889  }
2890  if (threadOpenConnections.joinable()) {
2891  threadOpenConnections.join();
2892  }
2893  if (threadOpenAddedConnections.joinable()) {
2895  }
2896  if (threadDNSAddressSeed.joinable()) {
2897  threadDNSAddressSeed.join();
2898  }
2899  if (threadSocketHandler.joinable()) {
2900  threadSocketHandler.join();
2901  }
2902 }
2903 
2905  if (fAddressesInitialized) {
2906  DumpAddresses();
2907  fAddressesInitialized = false;
2908 
2909  if (m_use_addrman_outgoing) {
2910  // Anchor connections are only dumped during clean shutdown.
2911  std::vector<CAddress> anchors_to_dump =
2913  if (anchors_to_dump.size() > MAX_BLOCK_RELAY_ONLY_ANCHORS) {
2914  anchors_to_dump.resize(MAX_BLOCK_RELAY_ONLY_ANCHORS);
2915  }
2918  anchors_to_dump);
2919  }
2920  }
2921 
2922  // Close sockets
2923  LOCK(cs_vNodes);
2924  for (CNode *pnode : vNodes) {
2925  pnode->CloseSocketDisconnect();
2926  }
2927  for (ListenSocket &hListenSocket : vhListenSocket) {
2928  if (hListenSocket.socket != INVALID_SOCKET) {
2929  if (!CloseSocket(hListenSocket.socket)) {
2930  LogPrintf("CloseSocket(hListenSocket) failed with error %s\n",
2932  }
2933  }
2934  }
2935 
2936  // clean up some globals (to help leak detection)
2937  for (CNode *pnode : vNodes) {
2938  DeleteNode(pnode);
2939  }
2940  for (CNode *pnode : vNodesDisconnected) {
2941  DeleteNode(pnode);
2942  }
2943  vNodes.clear();
2944  vNodesDisconnected.clear();
2945  vhListenSocket.clear();
2946  semOutbound.reset();
2947  semAddnode.reset();
2948 }
2949 
2951  assert(pnode);
2952  bool fUpdateConnectionTime = false;
2953  m_msgproc->FinalizeNode(*config, pnode->GetId(), fUpdateConnectionTime);
2954  if (fUpdateConnectionTime) {
2955  addrman.Connected(pnode->addr);
2956  }
2957  delete pnode;
2958 }
2959 
2961  Interrupt();
2962  Stop();
2963 }
2964 
2965 void CConnman::SetServices(const CService &addr, ServiceFlags nServices) {
2966  addrman.SetServices(addr, nServices);
2967 }
2968 
2970  addrman.Good(addr);
2971 }
2972 
2973 bool CConnman::AddNewAddresses(const std::vector<CAddress> &vAddr,
2974  const CAddress &addrFrom, int64_t nTimePenalty) {
2975  return addrman.Add(vAddr, addrFrom, nTimePenalty);
2976 }
2977 
2978 std::vector<CAddress> CConnman::GetAddresses(size_t max_addresses,
2979  size_t max_pct) {
2980  std::vector<CAddress> addresses = addrman.GetAddr(max_addresses, max_pct);
2981  if (m_banman) {
2982  addresses.erase(std::remove_if(addresses.begin(), addresses.end(),
2983  [this](const CAddress &addr) {
2984  return m_banman->IsDiscouraged(
2985  addr) ||
2986  m_banman->IsBanned(addr);
2987  }),
2988  addresses.end());
2989  }
2990  return addresses;
2991 }
2992 
2993 std::vector<CAddress>
2994 CConnman::GetAddresses(CNode &requestor, size_t max_addresses, size_t max_pct) {
2995  SOCKET socket;
2996  WITH_LOCK(requestor.cs_hSocket, socket = requestor.hSocket);
2997  auto local_socket_bytes = GetBindAddress(socket).GetAddrBytes();
2998  uint64_t cache_id =
3000  .Write(requestor.addr.GetNetwork())
3001  .Write(local_socket_bytes.data(), local_socket_bytes.size())
3002  .Finalize();
3003  const auto current_time = GetTime<std::chrono::microseconds>();
3004  auto r = m_addr_response_caches.emplace(cache_id, CachedAddrResponse{});
3005  CachedAddrResponse &cache_entry = r.first->second;
3006  // New CachedAddrResponse have expiration 0.
3007  if (cache_entry.m_cache_entry_expiration < current_time) {
3008  cache_entry.m_addrs_response_cache =
3009  GetAddresses(max_addresses, max_pct);
3010  // Choosing a proper cache lifetime is a trade-off between the privacy
3011  // leak minimization and the usefulness of ADDR responses to honest
3012  // users.
3013  //
3014  // Longer cache lifetime makes it more difficult for an attacker to
3015  // scrape enough AddrMan data to maliciously infer something useful. By
3016  // the time an attacker scraped enough AddrMan records, most of the
3017  // records should be old enough to not leak topology info by e.g.
3018  // analyzing real-time changes in timestamps.
3019  //
3020  // It takes only several hundred requests to scrape everything from an
3021  // AddrMan containing 100,000 nodes, so ~24 hours of cache lifetime
3022  // indeed makes the data less inferable by the time most of it could be
3023  // scraped (considering that timestamps are updated via ADDR
3024  // self-announcements and when nodes communicate). We also should be
3025  // robust to those attacks which may not require scraping *full*
3026  // victim's AddrMan (because even several timestamps of the same handful
3027  // of nodes may leak privacy).
3028  //
3029  // On the other hand, longer cache lifetime makes ADDR responses
3030  // outdated and less useful for an honest requestor, e.g. if most nodes
3031  // in the ADDR response are no longer active.
3032  //
3033  // However, the churn in the network is known to be rather low. Since we
3034  // consider nodes to be "terrible" (see IsTerrible()) if the timestamps
3035  // are older than 30 days, max. 24 hours of "penalty" due to cache
3036  // shouldn't make any meaningful difference in terms of the freshness of
3037  // the response.
3038  cache_entry.m_cache_entry_expiration =
3039  current_time + std::chrono::hours(21) +
3040  GetRandMillis(std::chrono::hours(6));
3041  }
3042  return cache_entry.m_addrs_response_cache;
3043 }
3044 
3045 bool CConnman::AddNode(const std::string &strNode) {
3047  for (const std::string &it : vAddedNodes) {
3048  if (strNode == it) {
3049  return false;
3050  }
3051  }
3052 
3053  vAddedNodes.push_back(strNode);
3054  return true;
3055 }
3056 
3057 bool CConnman::RemoveAddedNode(const std::string &strNode) {
3059  for (std::vector<std::string>::iterator it = vAddedNodes.begin();
3060  it != vAddedNodes.end(); ++it) {
3061  if (strNode == *it) {
3062  vAddedNodes.erase(it);
3063  return true;
3064  }
3065  }
3066  return false;
3067 }
3068 
3070  LOCK(cs_vNodes);
3071  // Shortcut if we want total
3073  return vNodes.size();
3074  }
3075 
3076  int nNum = 0;
3077  for (const auto &pnode : vNodes) {
3078  if (flags &
3079  (pnode->IsInboundConn() ? CONNECTIONS_IN : CONNECTIONS_OUT)) {
3080  nNum++;
3081  }
3082  }
3083 
3084  return nNum;
3085 }
3086 
3087 void CConnman::GetNodeStats(std::vector<CNodeStats> &vstats) {
3088  vstats.clear();
3089  LOCK(cs_vNodes);
3090  vstats.reserve(vNodes.size());
3091  for (CNode *pnode : vNodes) {
3092  vstats.emplace_back();
3093  pnode->copyStats(vstats.back(), addrman.m_asmap);
3094  }
3095 }
3096 
3097 bool CConnman::DisconnectNode(const std::string &strNode) {
3098  LOCK(cs_vNodes);
3099  if (CNode *pnode = FindNode(strNode)) {
3100  pnode->fDisconnect = true;
3101  return true;
3102  }
3103  return false;
3104 }
3105 
3106 bool CConnman::DisconnectNode(const CSubNet &subnet) {
3107  bool disconnected = false;
3108  LOCK(cs_vNodes);
3109  for (CNode *pnode : vNodes) {
3110  if (subnet.Match(pnode->addr)) {
3111  pnode->fDisconnect = true;
3112  disconnected = true;
3113  }
3114  }
3115  return disconnected;
3116 }
3117 
3119  return DisconnectNode(CSubNet(addr));
3120 }
3121 
3123  LOCK(cs_vNodes);
3124  for (CNode *pnode : vNodes) {
3125  if (id == pnode->GetId()) {
3126  pnode->fDisconnect = true;
3127  return true;
3128  }
3129  }
3130  return false;
3131 }
3132 
3133 void CConnman::RecordBytesRecv(uint64_t bytes) {
3135  nTotalBytesRecv += bytes;
3136 }
3137 
3138 void CConnman::RecordBytesSent(uint64_t bytes) {
3140  nTotalBytesSent += bytes;
3141 
3142  uint64_t now = GetTime();
3143  if (nMaxOutboundCycleStartTime + nMaxOutboundTimeframe < now) {
3144  // timeframe expired, reset cycle
3145  nMaxOutboundCycleStartTime = now;
3146  nMaxOutboundTotalBytesSentInCycle = 0;
3147  }
3148 
3149  // TODO, exclude peers with download permission
3150  nMaxOutboundTotalBytesSentInCycle += bytes;
3151 }
3152 
3153 void CConnman::SetMaxOutboundTarget(uint64_t limit) {
3155  nMaxOutboundLimit = limit;
3156 }
3157 
3160  return nMaxOutboundLimit;
3161 }
3162 
3165  return nMaxOutboundTimeframe;
3166 }
3167 
3170  if (nMaxOutboundLimit == 0) {
3171  return 0;
3172  }
3173 
3174  if (nMaxOutboundCycleStartTime == 0) {
3175  return nMaxOutboundTimeframe;
3176  }
3177 
3178  uint64_t cycleEndTime = nMaxOutboundCycleStartTime + nMaxOutboundTimeframe;
3179  uint64_t now = GetTime();
3180  return (cycleEndTime < now) ? 0 : cycleEndTime - GetTime();
3181 }
3182 
3183 void CConnman::SetMaxOutboundTimeframe(uint64_t timeframe) {
3185  if (nMaxOutboundTimeframe != timeframe) {
3186  // reset measure-cycle in case of changing the timeframe.
3187  nMaxOutboundCycleStartTime = GetTime();
3188  }
3189  nMaxOutboundTimeframe = timeframe;
3190 }
3191 
3192 bool CConnman::OutboundTargetReached(bool historicalBlockServingLimit) {
3194  if (nMaxOutboundLimit == 0) {
3195  return false;
3196  }
3197 
3198  if (historicalBlockServingLimit) {
3199  // keep a large enough buffer to at least relay each block once.
3200  uint64_t timeLeftInCycle = GetMaxOutboundTimeLeftInCycle();
3201  uint64_t buffer = timeLeftInCycle / 600 * ONE_MEGABYTE;
3202  if (buffer >= nMaxOutboundLimit ||
3203  nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit - buffer) {
3204  return true;
3205  }
3206  } else if (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit) {
3207  return true;
3208  }
3209 
3210  return false;
3211 }
3212 
3215  if (nMaxOutboundLimit == 0) {
3216  return 0;
3217  }
3218 
3219  return (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit)
3220  ? 0
3221  : nMaxOutboundLimit - nMaxOutboundTotalBytesSentInCycle;
3222 }
3223 
3226  return nTotalBytesRecv;
3227 }
3228 
3231  return nTotalBytesSent;
3232 }
3233 
3235  return nLocalServices;
3236 }
3237 
3238 void CConnman::SetBestHeight(int height) {
3239  nBestHeight.store(height, std::memory_order_release);
3240 }
3241 
3243  return nBestHeight.load(std::memory_order_acquire);
3244 }
3245 
3246 unsigned int CConnman::GetReceiveFloodSize() const {
3247  return nReceiveFloodSize;
3248 }
3249 
3251  invCounters += count;
3252 }
3253 
3255  invCounters += uint64_t(count) << 32;
3256 }
3257 
3259  LOCK(cs_statistics);
3260 
3261  uint64_t windowInvCounters = invCounters.exchange(0);
3262  double previousScore = availabilityScore;
3263 
3264  uint32_t polls = windowInvCounters & std::numeric_limits<uint32_t>::max();
3265  uint32_t votes = windowInvCounters >> 32;
3266 
3267  availabilityScore =
3268  AVALANCHE_STATISTICS_DECAY_FACTOR * (2 * votes - polls) +
3269  (1. - AVALANCHE_STATISTICS_DECAY_FACTOR) * previousScore;
3270 }
3271 
3273  // The score is set atomically so there is no need to lock the statistics
3274  // when reading.
3275  return availabilityScore;
3276 }
3277 
3278 CNode::CNode(NodeId idIn, ServiceFlags nLocalServicesIn,
3279  int nMyStartingHeightIn, SOCKET hSocketIn, const CAddress &addrIn,
3280  uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn,
3281  uint64_t nLocalExtraEntropyIn, const CAddress &addrBindIn,
3282  const std::string &addrNameIn, ConnectionType conn_type_in,
3283  bool inbound_onion)
3285  addrBind(addrBindIn), nKeyedNetGroup(nKeyedNetGroupIn),
3286  // Don't relay addr messages to peers that we connect to as
3287  // block-relay-only peers (to prevent adversaries from inferring these
3288  // links from addr traffic).
3289  id(idIn), nLocalHostNonce(nLocalHostNonceIn),
3290  nLocalExtraEntropy(nLocalExtraEntropyIn), m_conn_type(conn_type_in),
3291  nLocalServices(nLocalServicesIn), nMyStartingHeight(nMyStartingHeightIn),
3292  m_inbound_onion(inbound_onion) {
3293  hSocket = hSocketIn;
3294  addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
3295  hashContinue = BlockHash();
3296  if (conn_type_in != ConnectionType::BLOCK_RELAY) {
3297  m_tx_relay = std::make_unique<TxRelay>();
3298  }
3299 
3300  if (RelayAddrsWithConn()) {
3301  m_addr_known = std::make_unique<CRollingBloomFilter>(5000, 0.001);
3302  }
3303 
3304  // Don't relay proofs if avalanche is disabled
3305  if (isAvalancheEnabled(gArgs)) {
3306  m_proof_relay = std::make_unique<ProofRelay>();
3307  }
3308 
3309  for (const std::string &msg : getAllNetMessageTypes()) {
3310  mapRecvBytesPerMsgCmd[msg] = 0;
3311  }
3312  mapRecvBytesPerMsgCmd[NET_MESSAGE_COMMAND_OTHER] = 0;
3313 
3314  if (fLogIPs) {
3315  LogPrint(BCLog::NET, "Added connection to %s peer=%d\n", addrName, id);
3316  } else {
3317  LogPrint(BCLog::NET, "Added connection peer=%d\n", id);
3318  }
3319 
3320  m_deserializer = std::make_unique<V1TransportDeserializer>(
3321  V1TransportDeserializer(GetConfig().GetChainParams().NetMagic(),
3323  m_serializer =
3324  std::make_unique<V1TransportSerializer>(V1TransportSerializer());
3325 }
3326 
3328  CloseSocket(hSocket);
3329 }
3330 
3332  return pnode && pnode->fSuccessfullyConnected && !pnode->fDisconnect;
3333 }
3334 
3336  size_t nMessageSize = msg.data.size();
3337  LogPrint(BCLog::NET, "sending %s (%d bytes) peer=%d\n",
3338  SanitizeString(msg.m_type), nMessageSize, pnode->GetId());
3339 
3340  // make sure we use the appropriate network transport format
3341  std::vector<uint8_t> serializedHeader;
3342  pnode->m_serializer->prepareForTransport(*config, msg, serializedHeader);
3343  size_t nTotalSize = nMessageSize + serializedHeader.size();
3344 
3345  size_t nBytesSent = 0;
3346  {
3347  LOCK(pnode->cs_vSend);
3348  bool optimisticSend(pnode->vSendMsg.empty());
3349 
3350  // log total amount of bytes per message type
3351  pnode->mapSendBytesPerMsgCmd[msg.m_type] += nTotalSize;
3352  pnode->nSendSize += nTotalSize;
3353 
3354  if (pnode->nSendSize > nSendBufferMaxSize) {
3355  pnode->fPauseSend = true;
3356  }
3357  pnode->vSendMsg.push_back(std::move(serializedHeader));
3358  if (nMessageSize) {
3359  pnode->vSendMsg.push_back(std::move(msg.data));
3360  }
3361 
3362  // If write queue empty, attempt "optimistic write"
3363  if (optimisticSend == true) {
3364  nBytesSent = SocketSendData(pnode);
3365  }
3366  }
3367  if (nBytesSent) {
3368  RecordBytesSent(nBytesSent);
3369  }
3370 }
3371 
3372 bool CConnman::ForNode(NodeId id, std::function<bool(CNode *pnode)> func) {
3373  CNode *found = nullptr;
3374  LOCK(cs_vNodes);
3375  for (auto &&pnode : vNodes) {
3376  if (pnode->GetId() == id) {
3377  found = pnode;
3378  break;
3379  }
3380  }
3381  return found != nullptr && NodeFullyConnected(found) && func(found);
3382 }
3383 
3385  int average_interval_seconds) {
3386  if (m_next_send_inv_to_incoming < now) {
3387  // If this function were called from multiple threads simultaneously
3388  // it would be possible that both update the next send variable, and
3389  // return a different result to their caller. This is not possible in
3390  // practice as only the net processing thread invokes this function.
3392  PoissonNextSend(now, average_interval_seconds);
3393  }
3395 }
3396 
3397 int64_t PoissonNextSend(int64_t now, int average_interval_seconds) {
3398  return now + int64_t(log1p(GetRand(1ULL << 48) *
3399  -0.0000000000000035527136788 /* -1/2^48 */) *
3400  average_interval_seconds * -1000000.0 +
3401  0.5);
3402 }
3403 
3405  return CSipHasher(nSeed0, nSeed1).Write(id);
3406 }
3407 
3408 uint64_t CConnman::CalculateKeyedNetGroup(const CAddress &ad) const {
3409  std::vector<uint8_t> vchNetGroup(ad.GetGroup(addrman.m_asmap));
3410 
3412  .Write(vchNetGroup.data(), vchNetGroup.size())
3413  .Finalize();
3414 }
3415 
3430 std::string getSubVersionEB(uint64_t MaxBlockSize) {
3431  // Prepare EB string we are going to add to SubVer:
3432  // 1) translate from byte to MB and convert to string
3433  // 2) limit the EB string to the first decimal digit (floored)
3434  std::stringstream ebMBs;
3435  ebMBs << (MaxBlockSize / (ONE_MEGABYTE / 10));
3436  std::string eb = ebMBs.str();
3437  eb.insert(eb.size() - 1, ".", 1);
3438  if (eb.substr(0, 1) == ".") {
3439  eb = "0" + eb;
3440  }
3441  return eb;
3442 }
3443 
3444 std::string userAgent(const Config &config) {
3445  // format excessive blocksize value
3446  std::string eb = getSubVersionEB(config.GetMaxBlockSize());
3447  std::vector<std::string> uacomments;
3448  uacomments.push_back("EB" + eb);
3449 
3450  // Comments are checked for char compliance at startup, it is safe to add
3451  // them to the user agent string
3452  for (const std::string &cmt : gArgs.GetArgs("-uacomment")) {
3453  uacomments.push_back(cmt);
3454  }
3455 
3456  const std::string client_name = gArgs.GetArg("-uaclientname", CLIENT_NAME);
3457  const std::string client_version =
3458  gArgs.GetArg("-uaclientversion", FormatVersion(CLIENT_VERSION));
3459 
3460  // Size compliance is checked at startup, it is safe to not check it again
3461  return FormatUserAgent(client_name, client_version, uacomments);
3462 }
CNetAddr::IsIPv6
bool IsIPv6() const
Definition: netaddress.cpp:305
V1TransportSerializer
Definition: net.h:919
CNode::AvalancheState::invCounters
std::atomic< uint64_t > invCounters
The inventories polled and voted couters since last score computation, stored as a pair of uint32_t w...
Definition: net.h:1147
CNode::mapSendBytesPerMsgCmd
mapMsgCmdSize mapSendBytesPerMsgCmd
Definition: net.h:1072
CConnman::SetTryNewOutboundPeer
void SetTryNewOutboundPeer(bool flag)
Definition: net.cpp:2039
CConnman::cs_totalBytesRecv
RecursiveMutex cs_totalBytesRecv
Definition: net.h:528
WSAEADDRINUSE
#define WSAEADDRINUSE
Definition: compat.h:53
Config::GetMaxBlockSize
virtual uint64_t GetMaxBlockSize() const =0
CConnman::DisconnectNode
bool DisconnectNode(const std::string &node)
Definition: net.cpp:3097
ConnectSocketDirectly
bool ConnectSocketDirectly(const CService &addrConnect, const SOCKET &hSocket, int nTimeout, bool manual_connection)
Try to connect to the specified service on the specified socket.
Definition: netbase.cpp:684
CService
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:514
CService::GetSockAddr
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Obtain the IPv4/6 socket address this represents.
Definition: netaddress.cpp:961
CConnman::SocketSendData
size_t SocketSendData(CNode *pnode) const
Definition: net.cpp:819
CConnman::m_max_outbound
int m_max_outbound
Definition: net.h:617
CompareNodeBlockRelayOnlyTime
static bool CompareNodeBlockRelayOnlyTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition: net.cpp:957
CConnman::m_anchors
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
Definition: net.h:632
CNodeStats::nLastSend
int64_t nLastSend
Definition: net.h:761
CConnman::ConnectNode
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type)
Definition: net.cpp:389
CScheduler
Simple class for background tasks that should be run periodically or once "after a while".
Definition: scheduler.h:35
CConnman::Options::vSeedNodes
std::vector< std::string > vSeedNodes
Definition: net.h:246
fLogIPs
bool fLogIPs
Definition: logging.cpp:12
CConnman::vhListenSocket
std::vector< ListenSocket > vhListenSocket
Definition: net.h:549
V1TransportDeserializer::Complete
bool Complete() const override
Definition: net.h:881
ArgsManager::GetBoolArg
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:517
BanMan::IsBanned
bool IsBanned(const CNetAddr &net_addr)
Return whether net_addr is banned.
Definition: banman.cpp:89
CompareNodeAvailabilityScore
static bool CompareNodeAvailabilityScore(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition: net.cpp:974
_
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:55
StopMapPort
void StopMapPort()
Definition: net.cpp:1866
LOCAL_UPNP
@ LOCAL_UPNP
Definition: net.h:706
InterruptMapPort
void InterruptMapPort()
Definition: net.cpp:1863
GetDataDir
const fs::path & GetDataDir(bool fNetSpecific)
Definition: system.cpp:779
SELECT_TIMEOUT_MILLISECONDS
static const uint64_t SELECT_TIMEOUT_MILLISECONDS
Definition: net.cpp:116
StartMapPort
void StartMapPort()
Definition: net.cpp:1860
GetnScore
static int GetnScore(const CService &addr)
Definition: net.cpp:206
NET_UNROUTABLE
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
Definition: netaddress.h:46
CConnman::ThreadMessageHandler
void ThreadMessageHandler()
Definition: net.cpp:2444
count
static int count
Definition: tests.c:41
RemoveLocal
void RemoveLocal(const CService &addr)
Definition: net.cpp:283
RANDOMIZER_ID_EXTRAENTROPY
static const uint64_t RANDOMIZER_ID_EXTRAENTROPY
Definition: net.cpp:125
BanMan::IsDiscouraged
bool IsDiscouraged(const CNetAddr &net_addr)
Return whether net_addr is discouraged.
Definition: banman.cpp:84
CConnman::nSendBufferMaxSize
unsigned int nSendBufferMaxSize
Definition: net.h:546
CConnman::GetOutboundTargetBytesLeft
uint64_t GetOutboundTargetBytesLeft()
response the bytes left in the current max outbound cycle in case of no limit, it will always respons...
Definition: net.cpp:3213
CConnman::m_next_send_inv_to_incoming
std::atomic< int64_t > m_next_send_inv_to_incoming
Definition: net.h:658
CConnman::AttemptToEvictConnection
bool AttemptToEvictConnection()
Try to find a connection to evict when the node is full.
Definition: net.cpp:1119
CNode::cs_vSend
Mutex cs_vSend
Definition: net.h:943
CNode::nLastSend
std::atomic< int64_t > nLastSend
Definition: net.h:955
CConnman::CConnman
CConnman(const Config &configIn, uint64_t seed0, uint64_t seed1, bool network_active=true)
Definition: net.cpp:2641
CConnman::Interrupt
void Interrupt()
Definition: net.cpp:2863
CConnman::GetMaxOutboundTimeframe
uint64_t GetMaxOutboundTimeframe()
Definition: net.cpp:3163
CNode::GetId
NodeId GetId() const
Definition: net.h:1283
CNodeStats::nTimeOffset
int64_t nTimeOffset
Definition: net.h:767
CConnman::condMsgProc
std::condition_variable condMsgProc
Definition: net.h:640
CConnman::nReceiveFloodSize
unsigned int nReceiveFloodSize
Definition: net.h:547
NodeEvictionCandidate::fBloomFilter
bool fBloomFilter
Definition: net.h:1416
PF_FORCERELAY
@ PF_FORCERELAY
Definition: net_permissions.h:27
CNode::ReceiveMsgBytes
bool ReceiveMsgBytes(const Config &config, const char *pch, uint32_t nBytes, bool &complete)
Definition: net.cpp:657
CNode::nMinPingUsecTime
std::atomic< int64_t > nMinPingUsecTime
Definition: net.h:1230
CVectorWriter
Minimal stream for overwriting and/or appending to an existing byte vector.
Definition: streams.h:63
CThreadInterrupt::sleep_for
bool sleep_for(std::chrono::milliseconds rel_time)
Definition: threadinterrupt.cpp:26
CMessageHeader::nMessageSize
uint32_t nMessageSize
Definition: protocol.h:74
flags
int flags
Definition: bitcoin-tx.cpp:532
avalanche.h
CConnman::ThreadDNSAddressSeed
void ThreadDNSAddressSeed()
Definition: net.cpp:1871
CConnman::Options::vBinds
std::vector< CService > vBinds
Definition: net.h:249
WSAEMSGSIZE
#define WSAEMSGSIZE
Definition: compat.h:50
CNode::copyStats
void copyStats(CNodeStats &stats, const std::vector< bool > &m_asmap)
Definition: net.cpp:583
CNetAddr::GetNetClass
Network GetNetClass() const
Definition: netaddress.cpp:670
PF_NONE
@ PF_NONE
Definition: net_permissions.h:18
CConnman::RecordBytesRecv
void RecordBytesRecv(uint64_t bytes)
Definition: net.cpp:3133
CNodeStats::m_legacyWhitelisted
bool m_legacyWhitelisted
Definition: net.h:779
uiInterface
CClientUIInterface uiInterface
Definition: ui_interface.cpp:12
NET_INTERNAL
@ NET_INTERNAL
A set of addresses that represent the hash of a string or FQDN.
Definition: netaddress.h:65
CConnman::WakeMessageHandler
void WakeMessageHandler()
Definition: net.cpp:1755
CNodeStats::nLastBlockTime
int64_t nLastBlockTime
Definition: net.h:765
MSG_NOSIGNAL
#define MSG_NOSIGNAL
Definition: net.cpp:93
CConnman::Bind
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
Definition: net.cpp:2655
CMessageHeader::pchMessageStart
MessageMagic pchMessageStart
Definition: protocol.h:72
NET_MESSAGE_COMMAND_OTHER
const std::string NET_MESSAGE_COMMAND_OTHER
Definition: net.cpp:118
CAddrMan::Add
bool Add(const CAddress &addr, const CNetAddr &source, int64_t nTimePenalty=0)
Add a single address.
Definition: addrman.h:657
CConnman::SocketEvents
void SocketEvents(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set)
Definition: net.cpp:1534
WSAEINPROGRESS
#define WSAEINPROGRESS
Definition: compat.h:52
CConnman::PoissonNextSendInbound
int64_t PoissonNextSendInbound(int64_t now, int average_interval_seconds)
Attempts to obfuscate tx time through exponentially distributed emitting.
Definition: net.cpp:3384
CConnman::m_max_outbound_full_relay
int m_max_outbound_full_relay
Definition: net.h:609
CNodeStats::m_min_ping_usec
int64_t m_min_ping_usec
Definition: net.h:782
elements
static unsigned char elements[DATACOUNT][DATALEN]
Definition: tests_impl.h:36
CNode::nLocalServices
const ServiceFlags nLocalServices
Services offered to this peer.
Definition: net.h:1265
CNode::nLastRecv
std::atomic< int64_t > nLastRecv
Definition: net.h:956
CConnman::OutboundTargetReached
bool OutboundTargetReached(bool historicalBlockServingLimit)
check if the outbound target is reached.
Definition: net.cpp:3192
NetEventsInterface::SendMessages
virtual bool SendMessages(const Config &config, CNode *pnode, std::atomic< bool > &interrupt)=0
CConnman::m_onion_binds
std::vector< CService > m_onion_binds
A vector of -bind=<address>:<port>=onion arguments each of which is an address and port that are desi...
Definition: net.h:664
CNodeStats::nodeid
NodeId nodeid
Definition: net.h:758
bilingual_str
Bilingual messages:
Definition: translation.h:17
PF_RELAY
@ PF_RELAY
Definition: net_permissions.h:24
CNetAddr
Network address.
Definition: netaddress.h:117
CConnman::GetAddresses
std::vector< CAddress > GetAddresses(size_t max_addresses, size_t max_pct)
Definition: net.cpp:2978
g_relay_txes
bool g_relay_txes
Definition: net.cpp:133
NET_MAX
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
Definition: netaddress.h:68
LocalServiceInfo::nPort
int nPort
Definition: net.h:741
CConnman::ProcessAddrFetch
void ProcessAddrFetch()
Definition: net.cpp:2017
FormatVersion
std::string FormatVersion(int nVersion)
Definition: clientversion.cpp:47
NodeEvictionCandidate::fRelayTxes
bool fRelayTxes
Definition: net.h:1415
ConnectionType::OUTBOUND_FULL_RELAY
@ OUTBOUND_FULL_RELAY
These are the default connections that we use to connect with the network.
CNode
Information about a peer.
Definition: net.h:926
CConnman::GetMaxOutboundTarget
uint64_t GetMaxOutboundTarget()
Definition: net.cpp:3158
CConnman::GetTotalBytesRecv
uint64_t GetTotalBytesRecv()
Definition: net.cpp:3224
V1TransportDeserializer::nDataPos
uint32_t nDataPos
Definition: net.h:855
NodeEvictionCandidate::availabilityScore
double availabilityScore
Definition: net.h:1420
nConnectTimeout
int nConnectTimeout
Definition: netbase.cpp:33
CSemaphoreGrant::MoveTo
void MoveTo(CSemaphoreGrant &grant)
Definition: sync.h:341
GetDesirableServiceFlags
ServiceFlags GetDesirableServiceFlags(ServiceFlags services)
Gets the set of service flags which are "desirable" for a given peer.
Definition: protocol.cpp:204
CConnman::cs_vAddedNodes
RecursiveMutex cs_vAddedNodes
Definition: net.h:556
SeenLocal
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:307
CNode::m_serializer
std::unique_ptr< TransportSerializer > m_serializer
Definition: net.h:932
CNetMessage::m_command
std::string m_command
Definition: net.h:814
CompareNodeBlockTime
static bool CompareNodeBlockTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition: net.cpp:909
CConnman::AcceptConnection
void AcceptConnection(const ListenSocket &hListenSocket)
Definition: net.cpp:1175
CConnman::GetAddedNodeInfo
std::vector< AddedNodeInfo > GetAddedNodeInfo()
Definition: net.cpp:2311
GetTime
int64_t GetTime()
DEPRECATED Use either GetSystemTimeInSeconds (not mockable) or GetTime<T> (mockable)
Definition: time.cpp:27
CNode::GetAddrName
std::string GetAddrName() const
Definition: net.cpp:551
GetNameProxy
bool GetNameProxy(proxyType &nameProxyOut)
Definition: netbase.cpp:818
NetPermissions::ClearFlag
static void ClearFlag(NetPermissionFlags &flags, NetPermissionFlags f)
Definition: net_permissions.h:59
CConnman::GetLocalServices
ServiceFlags GetLocalServices() const
Used to convey which local services we are offering peers during node connection.
Definition: net.cpp:3234
CNetAddr::ToString
std::string ToString() const
Definition: netaddress.cpp:597
WITH_LOCK
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:272
FEELER_SLEEP_WINDOW
#define FEELER_SLEEP_WINDOW
Definition: net.cpp:88
CConnman::nBestHeight
std::atomic< int > nBestHeight
Definition: net.h:619
CAddrMan::Select
CAddrInfo Select(bool newOnly=false)
Choose an address to connect to.
Definition: addrman.h:732
CConnman::m_addr_fetches_mutex
RecursiveMutex m_addr_fetches_mutex
Definition: net.h:554
AnnotatedMixin< std::recursive_mutex >
CNetCleanup::~CNetCleanup
~CNetCleanup()
Definition: net.cpp:2854
CConnman::cs_totalBytesSent
RecursiveMutex cs_totalBytesSent
Definition: net.h:529
CHash256::Finalize
void Finalize(Span< uint8_t > output)
Definition: hash.h:29
CSerializedNetMsg::m_type
std::string m_type
Definition: net.h:138
CNetMessage::m_valid_header
bool m_valid_header
Definition: net.h:808
clientversion.h
ServiceFlags
ServiceFlags
nServices flags.
Definition: protocol.h:314
CConnman::CachedAddrResponse::m_addrs_response_cache
std::vector< CAddress > m_addrs_response_cache
Definition: net.h:570
CMessageHeader::GetCommand
std::string GetCommand() const
Definition: protocol.cpp:112
CAddress::nServices
ServiceFlags nServices
Definition: protocol.h:464
ReadLE32
static uint32_t ReadLE32(const uint8_t *ptr)
Definition: common.h:23
TRY_LOCK
#define TRY_LOCK(cs, name)
Definition: sync.h:247
fDiscover
bool fDiscover
Definition: net.cpp:131
MSG_DONTWAIT
#define MSG_DONTWAIT
Definition: net.cpp:99
V1TransportDeserializer::vRecv
CDataStream vRecv
Definition: net.h:853
CConnman::ListenSocket::socket
SOCKET socket
Definition: net.h:456
CNode::m_permissionFlags
NetPermissionFlags m_permissionFlags
Definition: net.h:1268
CNode::nTimeOffset
std::atomic< int64_t > nTimeOffset
Definition: net.h:958
CNodeStats::m_mapped_as
uint32_t m_mapped_as
Definition: net.h:792
CNode::nServices
std::atomic< ServiceFlags > nServices
Definition: net.h:935
WSAGetLastError
#define WSAGetLastError()
Definition: compat.h:46
SplitHostPort
void SplitHostPort(std::string in, int &portOut, std::string &hostOut)
Definition: strencodings.cpp:113
CNetMessage::m_valid_netmagic
bool m_valid_netmagic
Definition: net.h:807
CConnman::Start
bool Start(CScheduler &scheduler, const Options &options)
Definition: net.cpp:2708
CConnman::CalculateKeyedNetGroup
uint64_t CalculateKeyedNetGroup(const CAddress &ad) const
Definition: net.cpp:3408
CAddrDB::Write
bool Write(const CAddrMan &addr)
Definition: addrdb.cpp:141
V1TransportDeserializer::readData
int readData(const char *pch, uint32_t nBytes)
Definition: net.cpp:733
NetworkErrorString
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
Definition: netbase.cpp:941
Network
Network
A network type.
Definition: netaddress.h:43
CChainParams::FixedSeeds
const std::vector< SeedSpec6 > & FixedSeeds() const
Definition: chainparams.h:92
CAddress::nTime
uint32_t nTime
Definition: protocol.h:462
CNode::nMyStartingHeight
const int nMyStartingHeight
Definition: net.h:1267
CConnman::StopThreads
void StopThreads()
Definition: net.cpp:2886
CNode::AvalancheState::invsPolled
void invsPolled(uint32_t count)
The node was polled for count invs.
Definition: net.cpp:3250
MayHaveUsefulAddressDB
static bool MayHaveUsefulAddressDB(ServiceFlags services)
Checks if a peer with the given service flags may be capable of having a robust address-storage DB.
Definition: protocol.h:414
CConnman::NotifyNumConnectionsChanged
void NotifyNumConnectionsChanged()
Definition: net.cpp:1378
HasAllDesirableServiceFlags
static bool HasAllDesirableServiceFlags(ServiceFlags services)
A shortcut for (services & GetDesirableServiceFlags(services)) == GetDesirableServiceFlags(services),...
Definition: protocol.h:406
CNode::fDisconnect
std::atomic_bool fDisconnect
Definition: net.h:994
V1TransportDeserializer::data_hash
uint256 data_hash
Definition: net.h:844
proxyType
Definition: netbase.h:28
GetRand
uint64_t GetRand(uint64_t nMax) noexcept
Generate a uniform random integer in the range [0..range).
Definition: random.cpp:650
CService::ToStringIPPort
std::string ToStringIPPort() const
Definition: netaddress.cpp:1012
CSipHasher
SipHash-2-4.
Definition: siphash.h:13
CNode::AvalancheState::invsVoted
void invsVoted(uint32_t count)
The node voted for count invs.
Definition: net.cpp:3254
CSubNet::Match
bool Match(const CNetAddr &addr) const
Definition: netaddress.cpp:1127
DNSSEEDS_DELAY_PEER_THRESHOLD
static constexpr int DNSSEEDS_DELAY_PEER_THRESHOLD
Definition: net.cpp:84
scheduler.h
CNode::hashContinue
BlockHash hashContinue
Definition: net.h:1076
CConnman::nPrevNodeCount
unsigned int nPrevNodeCount
Definition: net.h:561
CNetAddr::GetGroup
std::vector< uint8_t > GetGroup(const std::vector< bool > &asmap) const
Get the canonical identifier of our network group.
Definition: netaddress.cpp:732
ConnectionType::MANUAL
@ MANUAL
We open manual connections to addresses that users explicitly inputted via the addnode RPC,...
CConnman::AddAddrFetch
void AddAddrFetch(const std::string &strDest)
Definition: net.cpp:138
CNode::AvalancheState::updateAvailabilityScore
void updateAvailabilityScore()
The availability score is calculated using an exponentially weighted average.
Definition: net.cpp:3258
FastRandomContext::randbits
uint64_t randbits(int bits) noexcept
Generate a random (bits)-bit integer.
Definition: random.h:184
CNetAddr::ToStringIP
std::string ToStringIP() const
Definition: netaddress.cpp:537
CNodeStats::mapSendBytesPerMsgCmd
mapMsgCmdSize mapSendBytesPerMsgCmd
Definition: net.h:775
ReverseCompareNodeTimeConnected
static bool ReverseCompareNodeTimeConnected(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition: net.cpp:890
Amount::zero
static constexpr Amount zero()
Definition: amount.h:42
CNode::nLastProofTime
std::atomic< int64_t > nLastProofTime
UNIX epoch time of the last proof received from this peer that we had not yet seen (e....
Definition: net.h:1219
CNode::addr
const CAddress addr
Definition: net.h:960
CNodeStats::nTimeConnected
int64_t nTimeConnected
Definition: net.h:766
CNode::nPingUsecTime
std::atomic< int64_t > nPingUsecTime
Definition: net.h:1228
CConnman::OpenNetworkConnection
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *strDest, ConnectionType conn_type)
Definition: net.cpp:2399
SER_NETWORK
@ SER_NETWORK
Definition: serialize.h:165
CAddrDB
Access to the (IP) address database (peers.dat)
Definition: addrdb.h:49
NodeEvictionCandidate::nKeyedNetGroup
uint64_t nKeyedNetGroup
Definition: net.h:1417
NetPermissions::HasFlag
static bool HasFlag(const NetPermissionFlags &flags, NetPermissionFlags f)
Definition: net_permissions.h:51
CNode::GetLocalServices
ServiceFlags GetLocalServices() const
Definition: net.h:1381
CScheduler::scheduleEvery
void scheduleEvery(Predicate p, std::chrono::milliseconds delta)
Repeat p until it return false.
Definition: scheduler.cpp:112
HaveNameProxy
bool HaveNameProxy()
Definition: netbase.cpp:827
Span
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:83
CAddrInfo
Extended statistics about a CAddress.
Definition: addrman.h:32
CConnman::SetMaxOutboundTarget
void SetMaxOutboundTarget(uint64_t limit)
set the max outbound target in bytes.
Definition: net.cpp:3153
CNode::nTimeConnected
const int64_t nTimeConnected
Definition: net.h:957
CConnman::FindNode
CNode * FindNode(const CNetAddr &ip)
Definition: net.cpp:322
ConnectionType::INBOUND
@ INBOUND
Inbound connections are those initiated by a peer.
V1TransportDeserializer::hdr
CMessageHeader hdr
Definition: net.h:851
strencodings.h
Config
Definition: config.h:17
GUARDED_BY
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(cs_mapLocalHost)
getSubVersionEB
std::string getSubVersionEB(uint64_t MaxBlockSize)
This function convert MaxBlockSize from byte to MB with a decimal precision one digit rounded down E....
Definition: net.cpp:3430
CConnman::m_addr_response_caches
std::map< uint64_t, CachedAddrResponse > m_addr_response_caches
Addr responses stored in different caches per (network, local socket) prevent cross-network node iden...
Definition: net.h:588
CSemaphoreGrant
RAII-style semaphore lock.
Definition: sync.h:312
ReverseCompareNodeMinPingTime
static bool ReverseCompareNodeMinPingTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition: net.cpp:885
protocol.h
CNodeStats::addr
CAddress addr
Definition: net.h:787
CNetAddr::GetNetwork
enum Network GetNetwork() const
Definition: netaddress.cpp:510
Hash
uint256 Hash(const T &in1)
Compute the 256-bit hash of an object.
Definition: hash.h:74
random.h
TraceThread
void TraceThread(const char *name, Callable func)
Definition: system.h:446
banman.h
CService::ToString
std::string ToString() const
Definition: netaddress.cpp:1020
GetRandInt
int GetRandInt(int nMax) noexcept
Definition: random.cpp:654
CNode::m_deserializer
std::unique_ptr< TransportDeserializer > m_deserializer
Definition: net.h:931
CConnman::mutexMsgProc
Mutex mutexMsgProc
Definition: net.h:641
CConnman::nLocalServices
ServiceFlags nLocalServices
Services this instance offers.
Definition: net.h:602
FormatUserAgent
std::string FormatUserAgent(const std::string &name, const std::string &version, const std::vector< std::string > &comments)
Format the subversion field according to BIP 14 spec.
Definition: clientversion.cpp:66
CConnman::ThreadSocketHandler
void ThreadSocketHandler()
Definition: net.cpp:1747
CConnman::ThreadOpenAddedConnections
void ThreadOpenAddedConnections()
Definition: net.cpp:2367
V1TransportDeserializer::in_data
bool in_data
Definition: net.h:847
IsPeerAddrLocalGood
bool IsPeerAddrLocalGood(CNode *pnode)
Definition: net.cpp:215
CNodeStats::nSendBytes
uint64_t nSendBytes
Definition: net.h:774
CNodeStats::nLastRecv
int64_t nLastRecv
Definition: net.h:762
Untranslated
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:36
NodeEvictionCandidate
Definition: net.h:1407
CNode::CNode
CNode(NodeId id, ServiceFlags nLocalServicesIn, int nMyStartingHeightIn, SOCKET hSocketIn, const CAddress &addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, uint64_t nLocalExtraEntropyIn, const CAddress &addrBindIn, const std::string &addrNameIn, ConnectionType conn_type_in, bool inbound_onion=false)
Definition: net.cpp:3278
LOCAL_MANUAL
@ LOCAL_MANUAL
Definition: net.h:708
CNodeStats::fRelayTxes
bool fRelayTxes
Definition: net.h:760
GetLocal
bool GetLocal(CService &addr, const CNetAddr *paddrPeer)
Definition: net.cpp:148
Lookup
bool Lookup(const std::string &name, std::vector< CService > &vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
Resolve a service string to its corresponding service.
Definition: netbase.cpp:220
SelectNodeToEvict
std::optional< NodeId > SelectNodeToEvict(std::vector< NodeEvictionCandidate > &&vEvictionCandidates)
Definition: net.cpp:1008
CNode::ConnectedThroughNetwork
Network ConnectedThroughNetwork() const
Get network the peer connected through.
Definition: net.cpp:579
CompareNodeTXTime
static bool CompareNodeTXTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition: net.cpp:924
INVALID_SOCKET
#define INVALID_SOCKET
Definition: compat.h:55
V1TransportDeserializer::GetMessage
CNetMessage GetMessage(const Config &config, std::chrono::microseconds time) override
Definition: net.cpp:759
CNode::cs_vRecv
Mutex cs_vRecv
Definition: net.h:945
CConnman::DumpAddresses
void DumpAddresses()
Definition: net.cpp:2007
CConnman::vWhitelistedRange
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:544
IsReachable
bool IsReachable(enum Network net)
Definition: net.cpp:297
CNode::GetCommonVersion
int GetCommonVersion() const
Definition: net.h:1302
count_microseconds
int64_t count_microseconds(std::chrono::microseconds t)
Definition: time.h:28
CNode::AddRef
CNode * AddRef()
Definition: net.h:1308
CService::SetSockAddr
bool SetSockAddr(const struct sockaddr *paddr)
Definition: netaddress.cpp:919
CLIENT_NAME
const std::string CLIENT_NAME
EraseLastKElements
static void EraseLastKElements(std::vector< T > &elements, Comparator comparator, size_t k)
Sort an array by the specified comparator, then erase the last K elements.
Definition: net.cpp:987
CConnman::InactivityCheck
void InactivityCheck(CNode *pnode)
Definition: net.cpp:1392
CConnman::NumConnections
NumConnections
Definition: net.h:223
CSipHasher::Finalize
uint64_t Finalize() const
Compute the 64-bit SipHash-2-4 of the data written so far.
Definition: siphash.cpp:82
RandAddEvent
void RandAddEvent(const uint32_t event_info) noexcept
Gathers entropy from the low bits of the time at which events occur.
Definition: random.cpp:644
CConnman::CONNECTIONS_ALL
@ CONNECTIONS_ALL
Definition: net.h:227
IsSelectableSocket
static bool IsSelectableSocket(const SOCKET &s)
Definition: compat.h:97
CConnman::m_banman
BanMan * m_banman
Pointer to this node's banman.
Definition: net.h:626
CNode::m_ping_start
std::atomic< std::chrono::microseconds > m_ping_start
When the last ping was sent, or 0 if no ping was ever sent.
Definition: net.h:1225
cs_mapLocalHost
RecursiveMutex cs_mapLocalHost
Definition: net.cpp:134
NetEventsInterface::FinalizeNode
virtual void FinalizeNode(const Config &config, NodeId id, bool &update_connection_time)=0
NetEventsInterface::InitializeNode
virtual void InitializeNode(const Config &config, CNode *pnode)=0
send
static RPCHelpMan send()
Definition: rpcwallet.cpp:4730
CNetAddr::IsRoutable
bool IsRoutable() const
Definition: netaddress.cpp:473
DNSSEEDS_DELAY_FEW_PEERS
static constexpr std::chrono::seconds DNSSEEDS_DELAY_FEW_PEERS
How long to delay before querying DNS seeds.
Definition: net.cpp:81
CNodeStats::addrName
std::string addrName
Definition: net.h:768
EraseLastKElementsIf
static void EraseLastKElementsIf(std::vector< T > &elements, Comparator comparator, size_t k, Condition cond)
Sort an array by the specified comparator, then erase up to K last elements which verify the conditio...
Definition: net.cpp:997
CConnman::threadOpenConnections
std::thread threadOpenConnections
Definition: net.h:649
CNode::m_tx_relay
std::unique_ptr< TxRelay > m_tx_relay
Definition: net.h:1126
CSemaphoreGrant::TryAcquire
bool TryAcquire()
Definition: sync.h:334
convertSeed6
static std::vector< CAddress > convertSeed6(const std::vector< SeedSpec6 > &vSeedsIn)
Convert the pnSeed6 array into usable address objects.
Definition: net.cpp:173
CNode::m_conn_type
const ConnectionType m_conn_type
Definition: net.h:1247
GetSystemTimeInSeconds
int64_t GetSystemTimeInSeconds()
Returns the system time (not mockable)
Definition: time.cpp:75
CConnman::ForNode
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:3372
CMessageHeader::IsOversized
bool IsOversized(const Config &config) const
Definition: protocol.cpp:188
consensus.h
BF_NONE
@ BF_NONE
Definition: net.cpp:104
CNetMessage::m_time
std::chrono::microseconds m_time
time of message receipt
Definition: net.h:806
CSerializedNetMsg
Definition: net.h:129
NetPermissionFlags
NetPermissionFlags
Definition: net_permissions.h:17
CNode::fSuccessfullyConnected
std::atomic_bool fSuccessfullyConnected
Definition: net.h:991
CConnman::Options::onion_binds
std::vector< CService > onion_binds
Definition: net.h:250
CConnman::CachedAddrResponse
Cache responses to addr requests to minimize privacy leak.
Definition: net.h:569
CNodeStats::m_permissionFlags
NetPermissionFlags m_permissionFlags
Definition: net.h:778
GetRandomizedDNSSeeds
const std::vector< std::string > GetRandomizedDNSSeeds(const CChainParams &params)
Return the list of hostnames to look up for DNS seeds.
Definition: dnsseeds.cpp:11
CConnman::GetNewNodeId
NodeId GetNewNodeId()
Definition: net.cpp:2651
SetReachable
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:289
CConnman::fAddressesInitialized
bool fAddressesInitialized
Definition: net.h:551
CConnman::ListenSocket
Definition: net.h:454
AddedNodeInfo
Definition: net.h:119
CompareNodeProofTime
static bool CompareNodeProofTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition: net.cpp:943
CNetAddr::GetMappedAS
uint32_t GetMappedAS(const std::vector< bool > &asmap) const
Definition: netaddress.cpp:688
ArgsManager::GetArg
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:498
NODE_BLOOM
@ NODE_BLOOM
Definition: protocol.h:331
CConnman::SetBestHeight
void SetBestHeight(int height)
Definition: net.cpp:3238
CConnman::Options::m_use_addrman_outgoing
bool m_use_addrman_outgoing
Definition: net.h:251
CNodeStats::m_ping_usec
int64_t m_ping_usec
Definition: net.h:780
CNetAddr::IsValid
bool IsValid() const
Definition: netaddress.cpp:438
CNetMessage::m_valid_checksum
bool m_valid_checksum
Definition: net.h:809
AVALANCHE_STATISTICS_DECAY_FACTOR
static const double AVALANCHE_STATISTICS_DECAY_FACTOR
Pre-computed decay factor for the avalanche statistics computation.
Definition: net.h:115
fNameLookup
bool fNameLookup
Definition: netbase.cpp:34
CNetAddr::GetAddrBytes
std::vector< uint8_t > GetAddrBytes() const
Definition: netaddress.cpp:787
CNodeStats::m_network
std::string m_network
Definition: net.h:791
CNodeStats::nStartingHeight
int nStartingHeight
Definition: net.h:773
CSubNet
Definition: netaddress.h:465
CConnman::ListenSocket::AddSocketPermissionFlags
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition: net.h:457
V1TransportDeserializer::hasher
CHash256 hasher
Definition: net.h:843
CNetCleanup
Definition: net.cpp:2850
Discover
void Discover()
Definition: net.cpp:2577
CConnman::m_peer_connect_timeout
int64_t m_peer_connect_timeout
Definition: net.h:540
CConnman::CONNECTIONS_IN
@ CONNECTIONS_IN
Definition: net.h:225
CAddrInfo::nLastTry
int64_t nLastTry
last try whatsoever by us (memory only)
Definition: addrman.h:35
CNode::cs_hSocket
Mutex cs_hSocket
Definition: net.h:944
SOCKET_ERROR
#define SOCKET_ERROR
Definition: compat.h:56
CConnman::threadMessageHandler
std::thread threadMessageHandler
Definition: net.h:650
uint256
256-bit opaque blob.
Definition: uint256.h:127
CNodeStats::m_conn_type_string
std::string m_conn_type_string
Definition: net.h:793
CNode::cs_SubVer
RecursiveMutex cs_SubVer
cleanSubVer is a sanitized string of the user agent byte array we read from the wire.
Definition: net.h:972
CNode::m_addr_known
std::unique_ptr< CRollingBloomFilter > m_addr_known
Definition: net.h:1081
CConnman::config
const Config * config
Definition: net.h:525
CConnman::GetMaxOutboundTimeLeftInCycle
uint64_t GetMaxOutboundTimeLeftInCycle()
response the time in second left in the current max outbound cycle in case of no limit,...
Definition: net.cpp:3168
LogPrint
#define LogPrint(category,...)
Definition: logging.h:193
CConnman::SetMaxOutboundTimeframe
void SetMaxOutboundTimeframe(uint64_t timeframe)
set the timeframe for the max outbound target.
Definition: net.cpp:3183
CConnman::nSeed0
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition: net.h:635
CNode::AvalancheState::getAvailabilityScore
double getAvailabilityScore() const
Definition: net.cpp:3272
ConnectThroughProxy
bool ConnectThroughProxy(const proxyType &proxy, const std::string &strDest, int port, const SOCKET &hSocket, int nTimeout, bool &outProxyConnectionFailed)
Connect to a specified destination service through a SOCKS5 proxy by first connecting to the SOCKS5 p...
Definition: netbase.cpp:857
NodeEvictionCandidate::nLastProofTime
int64_t nLastProofTime
Definition: net.h:1412
ConnectionType::FEELER
@ FEELER
Feeler connections are short-lived connections made to check that a node is alive.
AdvertiseLocal
void AdvertiseLocal(CNode *pnode)
Definition: net.cpp:222
CMessageHeader::MESSAGE_START_SIZE
static constexpr size_t MESSAGE_START_SIZE
Definition: protocol.h:39
CNodeStats::addrBind
CAddress addrBind
Definition: net.h:789
WSAEWOULDBLOCK
#define WSAEWOULDBLOCK
Definition: compat.h:49
CConnman::~CConnman
~CConnman()
Definition: net.cpp:2960
base_blob::begin
uint8_t * begin()
Definition: uint256.h:83
CConnman::Options
Definition: net.h:230
CConnman::GetReceiveFloodSize
unsigned int GetReceiveFloodSize() const
Definition: net.cpp:3246
ONE_MEGABYTE
static const uint64_t ONE_MEGABYTE
1MB
Definition: consensus.h:12
CNode::PushAddress
void PushAddress(const CAddress &_addr, FastRandomContext &insecure_rand)
Definition: net.h:1320
CNode::grantOutbound
CSemaphoreGrant grantOutbound
Definition: net.h:996
CNode::nStartingHeight
std::atomic< int > nStartingHeight
Definition: net.h:1077
CDataStream::size
size_type size() const
Definition: streams.h:280
CService::GetPort
uint16_t GetPort() const
Definition: netaddress.cpp:934
NodeEvictionCandidate::m_is_local
bool m_is_local
Definition: net.h:1419
bilingual_str::original
std::string original
Definition: translation.h:18
BlockHash
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
CNodeStats::addrLocal
std::string addrLocal
Definition: net.h:785
NODE_NONE
@ NODE_NONE
Definition: protocol.h:317
CMessageHeader::CHECKSUM_SIZE
static constexpr size_t CHECKSUM_SIZE
Definition: protocol.h:42
CChainParams::GetDefaultPort
int GetDefaultPort() const
Definition: chainparams.h:62
NodeEvictionCandidate::nTimeConnected
int64_t nTimeConnected
Definition: net.h:1409
CNode::nKeyedNetGroup
const uint64_t nKeyedNetGroup
Definition: net.h:999
CConnman::nLastNodeId
std::atomic< NodeId > nLastNodeId
Definition: net.h:560
ui_interface.h
CNode::nLastTXTime
std::atomic< int64_t > nLastTXTime
UNIX epoch time of the last transaction received from this peer that we had not yet seen (e....
Definition: net.h:1211
CConnman::RemoveAddedNode
bool RemoveAddedNode(const std::string &node)
Definition: net.cpp:3057
CConnman::GetNodeCount
size_t GetNodeCount(NumConnections num)
Definition: net.cpp:3069
V1TransportDeserializer::hdrbuf
CDataStream hdrbuf
Definition: net.h:849
sha256.h
CNode::IsManualConn
bool IsManualConn() const
Definition: net.h:1022
CMessageHeader::IsValid
bool IsValid(const Config &config) const
Definition: protocol.cpp:147
InterruptSocks5
void InterruptSocks5(bool interrupt)
Definition: netbase.cpp:1013
CLIENT_VERSION
static constexpr int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
Definition: clientversion.h:44
CConnman::GetCurrentBlockRelayOnlyConns
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const
Return vector of current BLOCK_RELAY peers.
Definition: net.cpp:2299
V1TransportDeserializer::readHeader
int readHeader(const Config &config, const char *pch, uint32_t nBytes)
Definition: net.cpp:700
strprintf
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1201
CClientUIInterface::MSG_ERROR
@ MSG_ERROR
Definition: ui_interface.h:73
ANCHORS_DATABASE_FILENAME
const char *const ANCHORS_DATABASE_FILENAME
Anchor IP address database file name.
Definition: net.cpp:61
CConnman::nSeed1
const uint64_t nSeed1
Definition: net.h:635
CAddrMan::m_asmap
std::vector< bool > m_asmap
Definition: addrman.h:341
V1TransportDeserializer::Reset
void Reset()
Definition: net.h:861
CNode::id
const NodeId id
Definition: net.h:1244
CConnman::CONNECTIONS_OUT
@ CONNECTIONS_OUT
Definition: net.h:226
CConnman::StopNodes
void StopNodes()
Definition: net.cpp:2904
ReadAnchors
std::vector< CAddress > ReadAnchors(const CChainParams &chainParams, const fs::path &anchors_db_path)
Read the anchor IP address database (anchors.dat)
Definition: addrdb.cpp:167
CConnman::m_try_another_outbound_peer
std::atomic_bool m_try_another_outbound_peer
flag for deciding to connect to an extra outbound peer, in excess of m_max_outbound_full_relay.
Definition: net.h:656
GetAdjustedTime
int64_t GetAdjustedTime()
Definition: timedata.cpp:34
SanitizeString
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
Definition: strencodings.cpp:31
CConnman::addrman
CAddrMan addrman
Definition: net.h:552
V1TransportDeserializer::GetMessageHash
const uint256 & GetMessageHash() const
Definition: net.cpp:750
base_blob::IsNull
bool IsNull() const
Definition: uint256.h:30
LocalServiceInfo::nScore
int nScore
Definition: net.h:740
CAddress
A CService with information about it as peer.
Definition: protocol.h:421
MAX_BLOCK_RELAY_ONLY_CONNECTIONS
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:77
LookupHost
bool LookupHost(const std::string &name, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
Resolve a host string to its corresponding network addresses.
Definition: netbase.cpp:165
CMessageHeader
Message header.
Definition: protocol.h:37
CConnman::SetNetworkActive
void SetNetworkActive(bool active)
Definition: net.cpp:2630
CNode::nLocalHostNonce
const uint64_t nLocalHostNonce
Definition: net.h:1245
instance_of_cnetcleanup
static CNetCleanup instance_of_cnetcleanup
Definition: net.cpp:2861
CConnman::NodeFullyConnected
static bool NodeFullyConnected(const CNode *pnode)
Definition: net.cpp:3331
PF_BLOOMFILTER
@ PF_BLOOMFILTER
Definition: net_permissions.h:20
DEFAULT_WHITELISTRELAY
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
Definition: net.h:51
LocalServiceInfo
Definition: net.h:739
CAddrMan::SelectTriedCollision
CAddrInfo SelectTriedCollision()
Randomly select an address in tried that another address is attempting to evict.
Definition: addrman.h:718
CNode::cs_addrName
RecursiveMutex cs_addrName
Definition: net.h:1272
NetPermissions::AddFlag
static void AddFlag(NetPermissionFlags &flags, NetPermissionFlags f)
Definition: net_permissions.h:55
CConnman::GetNodeStats
void GetNodeStats(std::vector< CNodeStats > &vstats)
Definition: net.cpp:3087
translation.h
SetSocketNoDelay
bool SetSocketNoDelay(const SOCKET &hSocket)
Set the TCP_NODELAY flag on a socket.
Definition: netbase.cpp:1006
CNetMessage::m_message_size
uint32_t m_message_size
size of the payload
Definition: net.h:811
CNode::m_inbound_onion
const bool m_inbound_onion
Whether this peer connected via our Tor onion service.
Definition: net.h:1280
CNetCleanup::CNetCleanup
CNetCleanup()
Definition: net.cpp:2852
RANDOMIZER_ID_NETGROUP
static const uint64_t RANDOMIZER_ID_NETGROUP
Definition: net.cpp:121
EXCLUSIVE_LOCKS_REQUIRED
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
Config::GetChainParams
virtual const CChainParams & GetChainParams() const =0
CConnman::cs_vNodes
RecursiveMutex cs_vNodes
Definition: net.h:559
LOCK
#define LOCK(cs)
Definition: sync.h:241
CNode::m_prefer_evict
bool m_prefer_evict
Definition: net.h:975
PF_MEMPOOL
@ PF_MEMPOOL
Definition: net_permissions.h:34
CNodeStats::nServices
ServiceFlags nServices
Definition: net.h:759
ConnectionType::ADDR_FETCH
@ ADDR_FETCH
AddrFetch connections are short lived connections used to solicit addresses from peers.
gArgs
ArgsManager gArgs
Definition: system.cpp:75
GetDefaultPort
static uint16_t GetDefaultPort()
Definition: bitcoin.h:16
NET_ONION
@ NET_ONION
TOR (v2 or v3)
Definition: netaddress.h:55
CNode::CloseSocketDisconnect
void CloseSocketDisconnect()
Definition: net.cpp:514
CAddrMan::Connected
void Connected(const CService &addr, int64_t nTime=GetAdjustedTime())
Mark an entry as currently-connected-to.
Definition: addrman.h:756
CNodeStats::nVersion
int nVersion
Definition: net.h:769
CNode::ConnectionTypeAsString
std::string ConnectionTypeAsString() const
Definition: net.cpp:532
V1TransportDeserializer
Definition: net.h:841
CConnman::SetServices
void SetServices(const CService &addr, ServiceFlags nServices)
Definition: net.cpp:2965
CreateSocket
SOCKET CreateSocket(const CService &addrConnect)
Try to create a socket file descriptor with specific properties in the communications domain (address...
Definition: netbase.cpp:614
CNetMessage
Transport protocol agnostic message container.
Definition: net.h:801
BIP0031_VERSION
static const int BIP0031_VERSION
BIP 0031, pong message, is enabled for all versions AFTER this one.
Definition: version.h:20
LOCAL_IF
@ LOCAL_IF
Definition: net.h:702
DumpAnchors
void DumpAnchors(const CChainParams &chainParams, const fs::path &anchors_db_path, const std::vector< CAddress > &anchors)
Dump the anchor IP address database (anchors.dat)
Definition: addrdb.cpp:158
RANDOMIZER_ID_ADDRCACHE
static const uint64_t RANDOMIZER_ID_ADDRCACHE
Definition: net.cpp:127
CompareLocalHostTimeConnected
static bool CompareLocalHostTimeConnected(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition: net.cpp:895
CNode::cs_addrLocal
RecursiveMutex cs_addrLocal
Definition: net.h:1277
CConnman::SocketHandler
void SocketHandler()
Definition: net.cpp:1617
CompareNetGroupKeyed
static bool CompareNetGroupKeyed(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition: net.cpp:904
CNode::GetAddrLocal
CService GetAddrLocal() const
Definition: net.cpp:563
CConnman::DisconnectNodes
void DisconnectNodes()
Definition: net.cpp:1320
V1TransportSerializer::prepareForTransport
void prepareForTransport(const Config &config, CSerializedNetMsg &msg, std::vector< uint8_t > &header) override
Definition: net.cpp:803
CDataStream::resize
void resize(size_type n, value_type c=0)
Definition: streams.h:282
CAddrMan::Clear
void Clear()
Definition: addrman.h:608
PoissonNextSend
int64_t PoissonNextSend(int64_t now, int average_interval_seconds)
Return a timestamp in the future (in microseconds) for exponentially distributed events.
Definition: net.cpp:3397
CNodeStats
POD that contains various stats about a node.
Definition: net.h:757
Params
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:506
CMessageHeader::HEADER_SIZE
static constexpr size_t HEADER_SIZE
Definition: protocol.h:47
CNodeStats::cleanSubVer
std::string cleanSubVer
Definition: net.h:770
MAX_BLOCK_RELAY_ONLY_ANCHORS
static constexpr size_t MAX_BLOCK_RELAY_ONLY_ANCHORS
Maximum number of block-relay-only anchor connections.
Definition: net.cpp:55
CNode::nLocalExtraEntropy
const uint64_t nLocalExtraEntropy
Definition: net.h:1246
CNodeStats::nLastTXTime
int64_t nLastTXTime
Definition: net.h:763
FastRandomContext::randrange
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
Definition: random.h:204
CAddrDB::Read
bool Read(CAddrMan &addr)
Definition: addrdb.cpp:145
WSAEINTR
#define WSAEINTR
Definition: compat.h:51
CThreadInterrupt::reset
void reset()
Definition: threadinterrupt.cpp:14
CNode::nLastBlockTime
std::atomic< int64_t > nLastBlockTime
UNIX epoch time of the last block received from this peer that we had not yet seen (e....
Definition: net.h:1203
CAddrMan::Good
void Good(const CService &addr, bool test_before_evict=true, int64_t nTime=GetAdjustedTime())
Mark an entry as accessible.
Definition: addrman.h:690
GetProxy
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
Definition: netbase.cpp:783
getAllNetMessageTypes
const std::vector< std::string > & getAllNetMessageTypes()
Get a vector of all valid message types (see above)
Definition: protocol.cpp:243
CConnman::Options::m_specified_outgoing
std::vector< std::string > m_specified_outgoing
Definition: net.h:252
CConnman::Stop
void Stop()
Definition: net.h:302
CConnman::AddNode
bool AddNode(const std::string &node)
Definition: net.cpp:3045
CNode::IsInboundConn
bool IsInboundConn() const
Definition: net.h:1034
CNode::vRecvMsg
std::list< CNetMessage > vRecvMsg
Definition: net.h:1270
CAddrMan::SetServices
void SetServices(const CService &addr, ServiceFlags nServices)
Definition: addrman.h:763
CNode::RelayAddrsWithConn
bool RelayAddrsWithConn() const
Definition: net.h:1039
NetEventsInterface::ProcessMessages
virtual bool ProcessMessages(const Config &config, CNode *pnode, std::atomic< bool > &interrupt)=0
CConnman::GetExtraOutboundCount
int GetExtraOutboundCount()
Definition: net.cpp:2051
sockopt_arg_type
void * sockopt_arg_type
Definition: compat.h:82
config.h
CSerializedNetMsg::data
std::vector< uint8_t > data
Definition: net.h:137
BF_DONT_ADVERTISE
@ BF_DONT_ADVERTISE
Do not call AddLocal() for our special addresses, e.g., for incoming Tor connections,...
Definition: net.cpp:111
RANDOMIZER_ID_LOCALHOSTNONCE
static const uint64_t RANDOMIZER_ID_LOCALHOSTNONCE
Definition: net.cpp:123
LookupNumeric
CService LookupNumeric(const std::string &name, int portDefault)
Resolve a service string with a numeric IP to its first corresponding service.
Definition: netbase.cpp:271
CConnman::threadOpenAddedConnections
std::thread threadOpenAddedConnections
Definition: net.h:648
NodeId
int64_t NodeId
Definition: nodeid.h:10
GetTimeMicros
int64_t GetTimeMicros()
Returns the system time (not mockable)
Definition: time.cpp:67
FEELER_INTERVAL
static const int FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes or 120 seconds.
Definition: net.h:61
CConnman::CachedAddrResponse::m_cache_entry_expiration
std::chrono::microseconds m_cache_entry_expiration
Definition: net.h:571
CNetAddr::SetInternal
bool SetInternal(const std::string &name)
Create an "internal" address that represents a name or FQDN.
Definition: netaddress.cpp:188
CNode::SetAddrLocal
void SetAddrLocal(const CService &addrLocalIn)
May not be called more than once.
Definition: net.cpp:568
CAddrMan::size
size_t size() const
Return the number of (unique) addresses in all tables.
Definition: addrman.h:637
NodeEvictionCandidate::nMinPingUsecTime
int64_t nMinPingUsecTime
Definition: net.h:1410
ConnectionType::BLOCK_RELAY
@ BLOCK_RELAY
We use block-relay-only connections to help prevent against partition attacks.
netbase.h
GetNetworkName
std::string GetNetworkName(enum Network net)
Definition: netbase.cpp:60
CAddrMan::GetAddr
std::vector< CAddress > GetAddr(size_t max_addresses, size_t max_pct)
Return a bunch of addresses, selected at random.
Definition: addrman.h:744
dnsseeds.h
CConnman::GetTryNewOutboundPeer
bool GetTryNewOutboundPeer()
Definition: net.cpp:2035
CNode::m_legacyWhitelisted
bool m_legacyWhitelisted
Definition: net.h:981
ArgsManager::GetArgs
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: system.cpp:391
FormatFullVersion
std::string FormatFullVersion()
Definition: clientversion.cpp:58
GetBindAddress
static CAddress GetBindAddress(SOCKET sock)
Get the bind address for a socket as CAddress.
Definition: net.cpp:374
DEFAULT_WHITELISTFORCERELAY
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
Definition: net.h:53
error
bool error(const char *fmt, const Args &... args)
Definition: system.h:48
CNode::MaybeSetAddrName
void MaybeSetAddrName(const std::string &addrNameIn)
Sets the addrName only if it was not previously set.
Definition: net.cpp:556
CConnman::ThreadOpenConnections
void ThreadOpenConnections(std::vector< std::string > connect)
Definition: net.cpp:2066
BF_REPORT_ERROR
@ BF_REPORT_ERROR
Definition: net.cpp:106
CConnman::semOutbound
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:604
PF_NOBAN
@ PF_NOBAN
Definition: net_permissions.h:32
CNode::nVersion
std::atomic< int > nVersion
Definition: net.h:963
V1TransportDeserializer::nHdrPos
uint32_t nHdrPos
Definition: net.h:854
BCLog::NET
@ NET
Definition: logging.h:38
CConnman::semAddnode
std::unique_ptr< CSemaphore > semAddnode
Definition: net.h:605
CNodeStats::nRecvBytes
uint64_t nRecvBytes
Definition: net.h:776
CConnman::flagInterruptMsgProc
std::atomic< bool > flagInterruptMsgProc
Definition: net.h:642
fListen
bool fListen
Definition: net.cpp:132
PF_ISIMPLICIT
@ PF_ISIMPLICIT
Definition: net_permissions.h:42
DEFAULT_BLOCKSONLY
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:99
CConnman::m_msgproc
NetEventsInterface * m_msgproc
Definition: net.h:621
CMessageHeader::pchChecksum
uint8_t pchChecksum[CHECKSUM_SIZE]
Definition: protocol.h:75
CConnman::threadDNSAddressSeed
std::thread threadDNSAddressSeed
Definition: net.h:646
CHash256::Write
CHash256 & Write(Span< const uint8_t > input)
Definition: hash.h:36
CConnman::GetTotalBytesSent
uint64_t GetTotalBytesSent()
Definition: net.cpp:3229
CConnman::Init
void Init(const Options &connOptions)
Definition: net.h:257
CConnman::GenerateSelectSet
bool GenerateSelectSet(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set)
Definition: net.cpp:1429
LOCAL_BIND
@ LOCAL_BIND
Definition: net.h:704
CChainParams::NetMagic
const CMessageHeader::MessageMagic & NetMagic() const
Definition: chainparams.h:61
net.h
userAgent
std::string userAgent(const Config &config)
Definition: net.cpp:3444
CConnman::vNodesDisconnected
std::list< CNode * > vNodesDisconnected
Definition: net.h:558
GetListenPort
uint16_t GetListenPort()
Definition: net.cpp:143
HexStr
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: strencodings.cpp:656
CNode::nPingNonceSent
std::atomic< uint64_t > nPingNonceSent
Definition: net.h:1223
CNode::nSendSize
size_t nSendSize
Definition: net.h:938
CConnman::threadSocketHandler
std::thread threadSocketHandler
Definition: net.h:647
CConnman::CheckIncomingNonce
bool CheckIncomingNonce(uint64_t nonce)
Definition: net.cpp:362
CConnman::m_max_outbound_block_relay
int m_max_outbound_block_relay
Definition: net.h:613
IsLocal
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:317
CThreadInterrupt
A helper class for interruptible sleeps.
Definition: threadinterrupt.h:19
ConnectionType
ConnectionType
Different types of connections to a peer.
Definition: net.h:154
DUMP_PEERS_INTERVAL
static constexpr std::chrono::minutes DUMP_PEERS_INTERVAL
Definition: net.cpp:64
GetConfig
const Config & GetConfig()
Definition: config.cpp:34
CNode::fPauseSend
std::atomic_bool fPauseSend
Definition: net.h:1001
CNodeStats::fInbound
bool fInbound
Definition: net.h:771
CAddrMan::Attempt
void Attempt(const CService &addr, bool fCountFailure, int64_t nTime=GetAdjustedTime())
Mark an entry as connection attempted to.
Definition: addrman.h:699
CConnman::m_use_addrman_outgoing
bool m_use_addrman_outgoing
Definition: net.h:618
CConnman::AddWhitelistPermissionFlags
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, const CNetAddr &addr) const
Definition: net.cpp:523
CConnman::clientInterface
CClientUIInterface * clientInterface
Definition: net.h:620
CConnman::Options::vWhiteBinds
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:248
CConnman::fNetworkActive
std::atomic< bool > fNetworkActive
Definition: net.h:550
CConnman::interruptNet
CThreadInterrupt interruptNet
Definition: net.h:644
LogPrintf
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:175
CConnman::GetBestHeight
int GetBestHeight() const
Definition: net.cpp:3242
BF_EXPLICIT
@ BF_EXPLICIT
Definition: net.cpp:105
CConnman::GetDeterministicRandomizer
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition: net.cpp:3404
CConnman::AddNewAddresses
bool AddNewAddresses(const std::vector< CAddress > &vAddr, const CAddress &addrFrom, int64_t nTimePenalty=0)
Definition: net.cpp:2973
DNSSEEDS_DELAY_MANY_PEERS
static constexpr std::chrono::minutes DNSSEEDS_DELAY_MANY_PEERS
Definition: net.cpp:82
CNetAddr::SetIP
void SetIP(const CNetAddr &ip)
Definition: netaddress.cpp:125
CConnman::nMaxAddnode
int nMaxAddnode
Definition: net.h:615
CConnman::InitBinds
bool InitBinds(const std::vector< CService > &binds, const std::vector< NetWhitebindPermissions > &whiteBinds, const std::vector< CService > &onion_binds)
Definition: net.cpp:2677
CNodeStats::m_ping_wait_usec
int64_t m_ping_wait_usec
Definition: net.h:781
GetRandMillis
constexpr auto GetRandMillis
Definition: random.h:93
CConnman::nMaxConnections
int nMaxConnections
Definition: net.h:606
GetLocalAddress
CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
Definition: net.cpp:195
CAddrMan::ResolveCollisions
void ResolveCollisions()
See if any to-be-evicted tried table entries have been tested and if so resolve the collisions.
Definition: addrman.h:709
FastRandomContext
Fast randomness source.
Definition: random.h:129
GetTimeMillis
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:59
CConnman::PushMessage
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
Definition: net.cpp:3335
BindFlags
BindFlags
Used to pass flags to the Bind() function.
Definition: net.cpp:103
CNode::~CNode
~CNode()
Definition: net.cpp:3327
CConnman::BindListenPort
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
Definition: net.cpp:2500
CNodeStats::nLastProofTime
int64_t nLastProofTime
Definition: net.h:764
WAIT_LOCK
#define WAIT_LOCK(cs, name)
Definition: sync.h:249
CNetMessage::m_raw_message_size
uint32_t m_raw_message_size
used wire size of the message (including header/checksum)
Definition: net.h:813
TIMEOUT_INTERVAL
static const int TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:59
proxyType::proxy
CService proxy
Definition: netbase.h:37
CNodeStats::minFeeFilter
Amount minFeeFilter
Definition: net.h:783
CNode::m_proof_relay
std::unique_ptr< ProofRelay > m_proof_relay
Definition: net.h:1139
INIT_PROTO_VERSION
static const int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
Definition: version.h:14
CConnman::RecordBytesSent
void RecordBytesSent(uint64_t bytes)
Definition: net.cpp:3138
DEFAULT_FORCEDNSSEED
static const bool DEFAULT_FORCEDNSSEED
Definition: net.h:103
SOCKET
unsigned int SOCKET
Definition: compat.h:44
DNSSEEDS_TO_QUERY_AT_ONCE
static constexpr int DNSSEEDS_TO_QUERY_AT_ONCE
Number of DNS seeds to query when the number of connections is low.
Definition: net.cpp:69
CNodeStats::m_manual_connection
bool m_manual_connection
Definition: net.h:772
CSipHasher::Write
CSipHasher & Write(uint64_t data)
Hash a 64-bit integer worth of data.
Definition: siphash.cpp:36
CConnman::MarkAddressGood
void MarkAddressGood(const CAddress &addr)
Definition: net.cpp:2969
NodeEvictionCandidate::nLastBlockTime
int64_t nLastBlockTime
Definition: net.h:1411
NodeEvictionCandidate::nLastTXTime
int64_t nLastTXTime
Definition: net.h:1413
CConnman::DeleteNode
void DeleteNode(CNode *pnode)
Definition: net.cpp:2950
AddLocal
bool AddLocal(const CService &addr, int nScore)
Definition: net.cpp:251
isAvalancheEnabled
bool isAvalancheEnabled(const ArgsManager &argsman)
Definition: avalanche.cpp:9
CNodeStats::mapRecvBytesPerMsgCmd
mapMsgCmdSize mapRecvBytesPerMsgCmd
Definition: net.h:777
CloseSocket
bool CloseSocket(SOCKET &hSocket)
Close socket and set hSocket to INVALID_SOCKET.
Definition: netbase.cpp:963
CNode::addrBind
const CAddress addrBind
Definition: net.h:962
NodeEvictionCandidate::fRelevantServices
bool fRelevantServices
Definition: net.h:1414