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