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