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