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