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