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