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