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