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