Dash Core Source Documentation (0.16.0.1)

Find detailed information regarding the Dash Core source code.

net.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 The Bitcoin Core developers
3 // Copyright (c) 2014-2020 The Dash Core developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #if defined(HAVE_CONFIG_H)
8 #include <config/dash-config.h>
9 #endif
10 
11 #include <net.h>
12 #include <netmessagemaker.h>
13 
14 #include <chainparams.h>
15 #include <clientversion.h>
16 #include <consensus/consensus.h>
17 #include <crypto/common.h>
18 #include <crypto/sha256.h>
19 #include <primitives/transaction.h>
20 #include <netbase.h>
21 #include <scheduler.h>
22 #include <ui_interface.h>
23 #include <utilstrencodings.h>
24 #include <validation.h>
25 
29 #include <evo/deterministicmns.h>
30 
31 #include <memory>
32 #ifdef WIN32
33 #include <string.h>
34 #else
35 #include <fcntl.h>
36 #endif
37 
38 #ifdef USE_POLL
39 #include <poll.h>
40 #endif
41 
42 #ifdef USE_EPOLL
43 #include <sys/epoll.h>
44 #endif
45 
46 #ifdef USE_UPNP
47 #include <miniupnpc/miniupnpc.h>
48 #include <miniupnpc/miniwget.h>
49 #include <miniupnpc/upnpcommands.h>
50 #include <miniupnpc/upnperrors.h>
51 #endif
52 
53 #include <unordered_map>
54 
55 #include <math.h>
56 
57 // Dump addresses to peers.dat and banlist.dat every 15 minutes (900s)
58 #define DUMP_ADDRESSES_INTERVAL 900
59 
60 // We add a random period time (0 to 1 seconds) to feeler connections to prevent synchronization.
61 #define FEELER_SLEEP_WINDOW 1
62 
63 #if !defined(HAVE_MSG_NOSIGNAL)
64 #define MSG_NOSIGNAL 0
65 #endif
66 
67 // MSG_DONTWAIT is not available on some platforms, if it doesn't exist define it as 0
68 #if !defined(HAVE_MSG_DONTWAIT)
69 #define MSG_DONTWAIT 0
70 #endif
71 
72 // Fix for ancient MinGW versions, that don't have defined these in ws2tcpip.h.
73 // Todo: Can be removed when our pull-tester is upgraded to a modern MinGW version.
74 #ifdef WIN32
75 #ifndef PROTECTION_LEVEL_UNRESTRICTED
76 #define PROTECTION_LEVEL_UNRESTRICTED 10
77 #endif
78 #ifndef IPV6_PROTECTION_LEVEL
79 #define IPV6_PROTECTION_LEVEL 23
80 #endif
81 #endif
82 
84 enum BindFlags {
85  BF_NONE = 0,
86  BF_EXPLICIT = (1U << 0),
87  BF_REPORT_ERROR = (1U << 1),
88  BF_WHITELIST = (1U << 2),
89 };
90 
91 #ifndef USE_WAKEUP_PIPE
92 // The set of sockets cannot be modified while waiting
93 // The sleep time needs to be small to avoid new sockets stalling
94 static const uint64_t SELECT_TIMEOUT_MILLISECONDS = 50;
95 #else
96 // select() is woken up through the wakeup pipe whenever a new node is added, so we can wait much longer.
97 // We are however still somewhat limited in how long we can sleep as there is periodic work (cleanup) to be done in
98 // the socket handler thread
99 static const uint64_t SELECT_TIMEOUT_MILLISECONDS = 500;
100 #endif
101 
102 const static std::string NET_MESSAGE_COMMAND_OTHER = "*other*";
103 
106 
107 static const uint64_t RANDOMIZER_ID_NETGROUP = 0x6c0edd8036ef4036ULL; // SHA256("netgroup")[0:8]
108 static const uint64_t RANDOMIZER_ID_LOCALHOSTNONCE = 0xd93e69e2bbfa5735ULL; // SHA256("localhostnonce")[0:8]
109 //
110 // Global state variables
111 //
112 bool fDiscover = true;
113 bool fListen = true;
114 bool fRelayTxes = true;
116 std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(cs_mapLocalHost);
117 static bool vfLimited[NET_MAX] GUARDED_BY(cs_mapLocalHost) = {};
118 std::string strSubVersion;
119 
120 void CConnman::AddOneShot(const std::string& strDest)
121 {
123  vOneShots.push_back(strDest);
124 }
125 
126 unsigned short GetListenPort()
127 {
128  return (unsigned short)(gArgs.GetArg("-port", Params().GetDefaultPort()));
129 }
130 
131 // find 'best' local address for a particular peer
132 bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
133 {
134  if (!fListen)
135  return false;
136 
137  int nBestScore = -1;
138  int nBestReachability = -1;
139  {
141  for (const auto& entry : mapLocalHost)
142  {
143  int nScore = entry.second.nScore;
144  int nReachability = entry.first.GetReachabilityFrom(paddrPeer);
145  if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
146  {
147  addr = CService(entry.first, entry.second.nPort);
148  nBestReachability = nReachability;
149  nBestScore = nScore;
150  }
151  }
152  }
153  return nBestScore >= 0;
154 }
155 
157 static std::vector<CAddress> convertSeed6(const std::vector<SeedSpec6> &vSeedsIn)
158 {
159  // It'll only connect to one or two seed nodes because once it connects,
160  // it'll get a pile of addresses with newer timestamps.
161  // Seed nodes are given a random 'last seen time' of between one and two
162  // weeks ago.
163  const int64_t nOneWeek = 7*24*60*60;
164  std::vector<CAddress> vSeedsOut;
165  vSeedsOut.reserve(vSeedsIn.size());
166  for (const auto& seed_in : vSeedsIn) {
167  struct in6_addr ip;
168  memcpy(&ip, seed_in.addr, sizeof(ip));
169  CAddress addr(CService(ip, seed_in.port), GetDesirableServiceFlags(NODE_NONE));
170  addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
171  vSeedsOut.push_back(addr);
172  }
173  return vSeedsOut;
174 }
175 
176 // get best local address for a particular peer as a CAddress
177 // Otherwise, return the unroutable 0.0.0.0 but filled in with
178 // the normal parameters, since the IP may be changed to a useful
179 // one by discovery.
180 CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
181 {
182  CAddress ret(CService(CNetAddr(),GetListenPort()), nLocalServices);
183  CService addr;
184  if (GetLocal(addr, paddrPeer))
185  {
186  ret = CAddress(addr, nLocalServices);
187  }
188  ret.nTime = GetAdjustedTime();
189  return ret;
190 }
191 
192 int GetnScore(const CService& addr)
193 {
195  if (mapLocalHost.count(addr) == LOCAL_NONE)
196  return 0;
197  return mapLocalHost[addr].nScore;
198 }
199 
200 // Is our peer's addrLocal potentially useful as an external IP source?
202 {
203  CService addrLocal = pnode->GetAddrLocal();
204  return fDiscover && pnode->addr.IsRoutable() && addrLocal.IsRoutable() &&
205  !IsLimited(addrLocal.GetNetwork());
206 }
207 
208 // pushes our own address to a peer
209 void AdvertiseLocal(CNode *pnode)
210 {
211  if (fListen && pnode->fSuccessfullyConnected)
212  {
213  CAddress addrLocal = GetLocalAddress(&pnode->addr, pnode->GetLocalServices());
214  if (gArgs.GetBoolArg("-addrmantest", false)) {
215  // use IPv4 loopback during addrmantest
216  addrLocal = CAddress(CService(LookupNumeric("127.0.0.1", GetListenPort())), pnode->GetLocalServices());
217  }
218  // If discovery is enabled, sometimes give our peer the address it
219  // tells us that it sees us as in case it has a better idea of our
220  // address than we do.
221  if (IsPeerAddrLocalGood(pnode) && (!addrLocal.IsRoutable() ||
222  GetRand((GetnScore(addrLocal) > LOCAL_MANUAL) ? 8:2) == 0))
223  {
224  addrLocal.SetIP(pnode->GetAddrLocal());
225  }
226  if (addrLocal.IsRoutable() || gArgs.GetBoolArg("-addrmantest", false))
227  {
228  LogPrint(BCLog::NET, "AdvertiseLocal: advertising address %s\n", addrLocal.ToString());
229  FastRandomContext insecure_rand;
230  pnode->PushAddress(addrLocal, insecure_rand);
231  }
232  }
233 }
234 
235 // learn a new local address
236 bool AddLocal(const CService& addr, int nScore)
237 {
238  if (!addr.IsRoutable() && Params().RequireRoutableExternalIP())
239  return false;
240 
241  if (!fDiscover && nScore < LOCAL_MANUAL)
242  return false;
243 
244  if (IsLimited(addr))
245  return false;
246 
247  LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore);
248 
249  {
251  bool fAlready = mapLocalHost.count(addr) > 0;
252  LocalServiceInfo &info = mapLocalHost[addr];
253  if (!fAlready || nScore >= info.nScore) {
254  info.nScore = nScore + (fAlready ? 1 : 0);
255  info.nPort = addr.GetPort();
256  }
257  }
258 
259  return true;
260 }
261 
262 bool AddLocal(const CNetAddr &addr, int nScore)
263 {
264  return AddLocal(CService(addr, GetListenPort()), nScore);
265 }
266 
267 bool RemoveLocal(const CService& addr)
268 {
270  LogPrintf("RemoveLocal(%s)\n", addr.ToString());
271  mapLocalHost.erase(addr);
272  return true;
273 }
274 
276 void SetLimited(enum Network net, bool fLimited)
277 {
278  if (net == NET_UNROUTABLE || net == NET_INTERNAL)
279  return;
281  vfLimited[net] = fLimited;
282 }
283 
284 bool IsLimited(enum Network net)
285 {
287  return vfLimited[net];
288 }
289 
290 bool IsLimited(const CNetAddr &addr)
291 {
292  return IsLimited(addr.GetNetwork());
293 }
294 
296 bool SeenLocal(const CService& addr)
297 {
298  {
300  if (mapLocalHost.count(addr) == 0)
301  return false;
302  mapLocalHost[addr].nScore++;
303  }
304  return true;
305 }
306 
307 
309 bool IsLocal(const CService& addr)
310 {
312  return mapLocalHost.count(addr) > 0;
313 }
314 
316 bool IsReachable(enum Network net)
317 {
319  return !vfLimited[net];
320 }
321 
323 bool IsReachable(const CNetAddr& addr)
324 {
325  enum Network net = addr.GetNetwork();
326  return IsReachable(net);
327 }
328 
329 
330 CNode* CConnman::FindNode(const CNetAddr& ip, bool fExcludeDisconnecting)
331 {
332  LOCK(cs_vNodes);
333  for (CNode* pnode : vNodes) {
334  if (fExcludeDisconnecting && pnode->fDisconnect) {
335  continue;
336  }
337  if ((CNetAddr)pnode->addr == ip) {
338  return pnode;
339  }
340  }
341  return nullptr;
342 }
343 
344 CNode* CConnman::FindNode(const CSubNet& subNet, bool fExcludeDisconnecting)
345 {
346  LOCK(cs_vNodes);
347  for (CNode* pnode : vNodes) {
348  if (fExcludeDisconnecting && pnode->fDisconnect) {
349  continue;
350  }
351  if (subNet.Match((CNetAddr)pnode->addr)) {
352  return pnode;
353  }
354  }
355  return nullptr;
356 }
357 
358 CNode* CConnman::FindNode(const std::string& addrName, bool fExcludeDisconnecting)
359 {
360  LOCK(cs_vNodes);
361  for (CNode* pnode : vNodes) {
362  if (fExcludeDisconnecting && pnode->fDisconnect) {
363  continue;
364  }
365  if (pnode->GetAddrName() == addrName) {
366  return pnode;
367  }
368  }
369  return nullptr;
370 }
371 
372 CNode* CConnman::FindNode(const CService& addr, bool fExcludeDisconnecting)
373 {
374  LOCK(cs_vNodes);
375  for (CNode* pnode : vNodes) {
376  if (fExcludeDisconnecting && pnode->fDisconnect) {
377  continue;
378  }
379  if ((CService)pnode->addr == addr) {
380  return pnode;
381  }
382  }
383  return nullptr;
384 }
385 
386 bool CConnman::CheckIncomingNonce(uint64_t nonce)
387 {
388  LOCK(cs_vNodes);
389  for (CNode* pnode : vNodes) {
390  if (!pnode->fSuccessfullyConnected && !pnode->fInbound && pnode->GetLocalNonce() == nonce)
391  return false;
392  }
393  return true;
394 }
395 
398 {
399  CAddress addr_bind;
400  struct sockaddr_storage sockaddr_bind;
401  socklen_t sockaddr_bind_len = sizeof(sockaddr_bind);
402  if (sock != INVALID_SOCKET) {
403  if (!getsockname(sock, (struct sockaddr*)&sockaddr_bind, &sockaddr_bind_len)) {
404  addr_bind.SetSockAddr((const struct sockaddr*)&sockaddr_bind);
405  } else {
406  LogPrint(BCLog::NET, "Warning: getsockname failed\n");
407  }
408  }
409  return addr_bind;
410 }
411 
412 CNode* CConnman::ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure)
413 {
414  if (pszDest == nullptr) {
415  bool fAllowLocal = Params().AllowMultiplePorts() && addrConnect.GetPort() != GetListenPort();
416  if (!fAllowLocal && IsLocal(addrConnect)) {
417  return nullptr;
418  }
419 
420  // Look for an existing connection
421  CNode* pnode = FindNode((CService)addrConnect);
422  if (pnode)
423  {
424  LogPrintf("Failed to open new connection, already connected\n");
425  return nullptr;
426  }
427  }
428 
430  if (fLogIPs) {
431  LogPrint(BCLog::NET, "trying connection %s lastseen=%.1fhrs\n",
432  pszDest ? pszDest : addrConnect.ToString(),
433  pszDest ? 0.0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
434  } else {
435  LogPrint(BCLog::NET, "trying connection lastseen=%.1fhrs\n",
436  pszDest ? 0.0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
437  }
438 
439  // Resolve
440  const int default_port = Params().GetDefaultPort();
441  if (pszDest) {
442  std::vector<CService> resolved;
443  if (Lookup(pszDest, resolved, default_port, fNameLookup && !HaveNameProxy(), 256) && !resolved.empty()) {
444  addrConnect = CAddress(resolved[GetRand(resolved.size())], NODE_NONE);
445  if (!addrConnect.IsValid()) {
446  LogPrint(BCLog::NET, "Resolver returned invalid address %s for %s", addrConnect.ToString(), pszDest);
447  return nullptr;
448  }
449  // It is possible that we already have a connection to the IP/port pszDest resolved to.
450  // In that case, drop the connection that was just created, and return the existing CNode instead.
451  // Also store the name we used to connect in that CNode, so that future FindNode() calls to that
452  // name catch this early.
453  LOCK(cs_vNodes);
454  CNode* pnode = FindNode((CService)addrConnect);
455  if (pnode)
456  {
457  pnode->MaybeSetAddrName(std::string(pszDest));
458  LogPrintf("Failed to open new connection, already connected\n");
459  return nullptr;
460  }
461  }
462  }
463 
464  // Connect
465  bool connected = false;
466  SOCKET hSocket = INVALID_SOCKET;
467  proxyType proxy;
468  if (addrConnect.IsValid()) {
469  bool proxyConnectionFailed = false;
470 
471  if (GetProxy(addrConnect.GetNetwork(), proxy)) {
472  hSocket = CreateSocket(proxy.proxy);
473  if (hSocket == INVALID_SOCKET) {
474  return nullptr;
475  }
476  connected = ConnectThroughProxy(proxy, addrConnect.ToStringIP(), addrConnect.GetPort(), hSocket, nConnectTimeout, &proxyConnectionFailed);
477  } else {
478  // no proxy needed (none set for target network)
479  hSocket = CreateSocket(addrConnect);
480  if (hSocket == INVALID_SOCKET) {
481  return nullptr;
482  }
483  connected = ConnectSocketDirectly(addrConnect, hSocket, nConnectTimeout);
484  }
485  if (!proxyConnectionFailed) {
486  // If a connection to the node was attempted, and failure (if any) is not caused by a problem connecting to
487  // the proxy, mark this as an attempt.
488  addrman.Attempt(addrConnect, fCountFailure);
489  }
490  } else if (pszDest && GetNameProxy(proxy)) {
491  hSocket = CreateSocket(proxy.proxy);
492  if (hSocket == INVALID_SOCKET) {
493  return nullptr;
494  }
495  std::string host;
496  int port = default_port;
497  SplitHostPort(std::string(pszDest), port, host);
498  connected = ConnectThroughProxy(proxy, host, port, hSocket, nConnectTimeout, nullptr);
499  }
500  if (!connected) {
501  CloseSocket(hSocket);
502  return nullptr;
503  }
504 
505  // Add node
506  NodeId id = GetNewNodeId();
508  CAddress addr_bind = GetBindAddress(hSocket);
509  CNode* pnode = new CNode(id, nLocalServices, GetBestHeight(), hSocket, addrConnect, CalculateKeyedNetGroup(addrConnect), nonce, addr_bind, pszDest ? pszDest : "", false);
510  pnode->AddRef();
511 
512  return pnode;
513 }
514 
516 {
517  SweepBanned(); // clean unused entries (if bantime has expired)
518 
519  if (!BannedSetIsDirty())
520  return;
521 
522  int64_t nStart = GetTimeMillis();
523 
524  CBanDB bandb;
525  banmap_t banmap;
526  GetBanned(banmap);
527  if (bandb.Write(banmap)) {
528  SetBannedSetDirty(false);
529  }
530 
531  LogPrint(BCLog::NET, "Flushed %d banned node ips/subnets to banlist.dat %dms\n",
532  banmap.size(), GetTimeMillis() - nStart);
533 }
534 
536 {
537  AssertLockHeld(connman->cs_vNodes);
538 
539  fDisconnect = true;
540  LOCK(cs_hSocket);
541  if (hSocket == INVALID_SOCKET) {
542  return;
543  }
544 
545  fHasRecvData = false;
546  fCanSendData = false;
547 
548  connman->mapSocketToNode.erase(hSocket);
549  connman->mapReceivableNodes.erase(GetId());
550  connman->mapSendableNodes.erase(GetId());
551  {
553  if (connman->mapNodesWithDataToSend.erase(GetId()) != 0) {
554  // See comment in PushMessage
555  Release();
556  }
557  }
558 
559  connman->UnregisterEvents(this);
560 
561  LogPrint(BCLog::NET, "disconnecting peer=%d\n", id);
562  CloseSocket(hSocket);
563 }
564 
566 {
567  {
569  setBanned.clear();
570  setBannedIsDirty = true;
571  }
572  DumpBanlist(); //store banlist to disk
573  if(clientInterface)
575 }
576 
578 {
580  for (const auto& it : setBanned) {
581  CSubNet subNet = it.first;
582  CBanEntry banEntry = it.second;
583 
584  if (subNet.Match(ip) && GetTime() < banEntry.nBanUntil) {
585  return true;
586  }
587  }
588  return false;
589 }
590 
592 {
594  banmap_t::iterator i = setBanned.find(subnet);
595  if (i != setBanned.end())
596  {
597  CBanEntry banEntry = (*i).second;
598  if (GetTime() < banEntry.nBanUntil) {
599  return true;
600  }
601  }
602  return false;
603 }
604 
605 void CConnman::Ban(const CNetAddr& addr, const BanReason &banReason, int64_t bantimeoffset, bool sinceUnixEpoch) {
606  CSubNet subNet(addr);
607  Ban(subNet, banReason, bantimeoffset, sinceUnixEpoch);
608 }
609 
610 void CConnman::Ban(const CSubNet& subNet, const BanReason &banReason, int64_t bantimeoffset, bool sinceUnixEpoch) {
611  CBanEntry banEntry(GetTime());
612  banEntry.banReason = banReason;
613  if (bantimeoffset <= 0)
614  {
615  bantimeoffset = gArgs.GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME);
616  sinceUnixEpoch = false;
617  }
618  banEntry.nBanUntil = (sinceUnixEpoch ? 0 : GetTime() )+bantimeoffset;
619 
620  {
622  if (setBanned[subNet].nBanUntil < banEntry.nBanUntil) {
623  setBanned[subNet] = banEntry;
624  setBannedIsDirty = true;
625  }
626  else
627  return;
628  }
629  if(clientInterface)
631  {
632  LOCK(cs_vNodes);
633  for (CNode* pnode : vNodes) {
634  if (subNet.Match((CNetAddr)pnode->addr))
635  pnode->fDisconnect = true;
636  }
637  }
638  if(banReason == BanReasonManuallyAdded)
639  DumpBanlist(); //store banlist to disk immediately if user requested ban
640 }
641 
642 bool CConnman::Unban(const CNetAddr &addr) {
643  CSubNet subNet(addr);
644  return Unban(subNet);
645 }
646 
647 bool CConnman::Unban(const CSubNet &subNet) {
648  {
650  if (!setBanned.erase(subNet))
651  return false;
652  setBannedIsDirty = true;
653  }
654  if(clientInterface)
656  DumpBanlist(); //store banlist to disk immediately
657  return true;
658 }
659 
661 {
663  // Sweep the banlist so expired bans are not returned
664  SweepBanned();
665  banMap = setBanned; //create a thread safe copy
666 }
667 
668 void CConnman::SetBanned(const banmap_t &banMap)
669 {
671  setBanned = banMap;
672  setBannedIsDirty = true;
673 }
674 
676 {
677  int64_t now = GetTime();
678  bool notifyUI = false;
679  {
681  banmap_t::iterator it = setBanned.begin();
682  while(it != setBanned.end())
683  {
684  CSubNet subNet = (*it).first;
685  CBanEntry banEntry = (*it).second;
686  if(now > banEntry.nBanUntil)
687  {
688  setBanned.erase(it++);
689  setBannedIsDirty = true;
690  notifyUI = true;
691  LogPrint(BCLog::NET, "%s: Removed banned node ip/subnet from banlist.dat: %s\n", __func__, subNet.ToString());
692  }
693  else
694  ++it;
695  }
696  }
697  // update UI
698  if(notifyUI && clientInterface) {
700  }
701 }
702 
704 {
706  return setBannedIsDirty;
707 }
708 
710 {
711  LOCK(cs_setBanned); //reuse setBanned lock for the isDirty flag
712  setBannedIsDirty = dirty;
713 }
714 
715 
717  for (const CSubNet& subnet : vWhitelistedRange) {
718  if (subnet.Match(addr))
719  return true;
720  }
721  return false;
722 }
723 
724 std::string CNode::GetAddrName() const {
725  LOCK(cs_addrName);
726  return addrName;
727 }
728 
729 void CNode::MaybeSetAddrName(const std::string& addrNameIn) {
730  LOCK(cs_addrName);
731  if (addrName.empty()) {
732  addrName = addrNameIn;
733  }
734 }
735 
738  return addrLocal;
739 }
740 
741 void CNode::SetAddrLocal(const CService& addrLocalIn) {
743  if (addrLocal.IsValid()) {
744  error("Addr local already set for node: %i. Refusing to change from %s to %s", id, addrLocal.ToString(), addrLocalIn.ToString());
745  } else {
746  addrLocal = addrLocalIn;
747  }
748 }
749 
750 std::string CNode::GetLogString() const
751 {
752  return fLogIPs ? addr.ToString() : strprintf("%d", id);
753 }
754 
755 #undef X
756 #define X(name) stats.name = name
758 {
759  stats.nodeid = this->GetId();
760  X(nServices);
761  X(addr);
762  X(addrBind);
763  {
764  LOCK(cs_filter);
765  X(fRelayTxes);
766  }
767  X(nLastSend);
768  X(nLastRecv);
769  X(nTimeConnected);
770  X(nTimeOffset);
771  stats.addrName = GetAddrName();
772  X(nVersion);
773  {
774  LOCK(cs_SubVer);
775  X(cleanSubVer);
776  }
777  X(fInbound);
780  {
781  LOCK(cs_vSend);
783  X(nSendBytes);
784  }
785  {
786  LOCK(cs_vRecv);
787  X(mapRecvBytesPerMsgCmd);
788  X(nRecvBytes);
789  }
790  X(fWhitelisted);
791 
792  // It is common for nodes with good ping times to suddenly become lagged,
793  // due to a new block arriving or other large transfer.
794  // Merely reporting pingtime might fool the caller into thinking the node was still responsive,
795  // since pingtime does not update until the ping is complete, which might take a while.
796  // So, if a ping is taking an unusually long time in flight,
797  // the caller can immediately detect that this is happening.
798  int64_t nPingUsecWait = 0;
799  if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) {
800  nPingUsecWait = GetTimeMicros() - nPingUsecStart;
801  }
802 
803  // Raw ping time is in microseconds, but show it to user as whole seconds (Dash users should be well used to small numbers with many decimal places by now :)
804  stats.dPingTime = (((double)nPingUsecTime) / 1e6);
805  stats.dMinPing = (((double)nMinPingUsecTime) / 1e6);
806  stats.dPingWait = (((double)nPingUsecWait) / 1e6);
807 
808  // Leave string empty if addrLocal invalid (not filled in yet)
809  CService addrLocalUnlocked = GetAddrLocal();
810  stats.addrLocal = addrLocalUnlocked.IsValid() ? addrLocalUnlocked.ToString() : "";
811 
812  {
813  LOCK(cs_mnauth);
815  }
816  X(fMasternode);
817 }
818 #undef X
819 
820 bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool& complete)
821 {
822  complete = false;
823  int64_t nTimeMicros = GetTimeMicros();
824  LOCK(cs_vRecv);
825  nLastRecv = nTimeMicros / 1000000;
826  nRecvBytes += nBytes;
827  while (nBytes > 0) {
828 
829  // get current incomplete message, or create a new one
830  if (vRecvMsg.empty() ||
831  vRecvMsg.back().complete())
832  vRecvMsg.push_back(CNetMessage(Params().MessageStart(), SER_NETWORK, INIT_PROTO_VERSION));
833 
834  CNetMessage& msg = vRecvMsg.back();
835 
836  // absorb network data
837  int handled;
838  if (!msg.in_data) {
839  handled = msg.readHeader(pch, nBytes);
840  } else {
841  handled = msg.readData(pch, nBytes);
842  }
843 
844  if (handled < 0)
845  return false;
846 
848  LogPrint(BCLog::NET, "Oversized message from peer=%i, disconnecting\n", GetId());
849  return false;
850  }
851 
852  pch += handled;
853  nBytes -= handled;
854 
855  if (msg.complete()) {
856 
857  //store received bytes per message command
858  //to prevent a memory DOS, only allow valid commands
859  mapMsgCmdSize::iterator i = mapRecvBytesPerMsgCmd.find(msg.hdr.pchCommand);
860  if (i == mapRecvBytesPerMsgCmd.end())
861  i = mapRecvBytesPerMsgCmd.find(NET_MESSAGE_COMMAND_OTHER);
862  assert(i != mapRecvBytesPerMsgCmd.end());
863  i->second += msg.hdr.nMessageSize + CMessageHeader::HEADER_SIZE;
864 
865  msg.nTime = nTimeMicros;
866  complete = true;
867  }
868  }
869 
870  return true;
871 }
872 
873 void CNode::SetSendVersion(int nVersionIn)
874 {
875  // Send version may only be changed in the version message, and
876  // only one version message is allowed per session. We can therefore
877  // treat this value as const and even atomic as long as it's only used
878  // once a version message has been successfully processed. Any attempt to
879  // set this twice is an error.
880  if (nSendVersion != 0) {
881  error("Send version already set for node: %i. Refusing to change from %i to %i", id, nSendVersion, nVersionIn);
882  } else {
883  nSendVersion = nVersionIn;
884  }
885 }
886 
888 {
889  // The send version should always be explicitly set to
890  // INIT_PROTO_VERSION rather than using this value until SetSendVersion
891  // has been called.
892  if (nSendVersion == 0) {
893  error("Requesting unset send version for node: %i. Using %i", id, INIT_PROTO_VERSION);
894  return INIT_PROTO_VERSION;
895  }
896  return nSendVersion;
897 }
898 
899 
900 int CNetMessage::readHeader(const char *pch, unsigned int nBytes)
901 {
902  // copy data to temporary parsing buffer
903  unsigned int nRemaining = 24 - nHdrPos;
904  unsigned int nCopy = std::min(nRemaining, nBytes);
905 
906  memcpy(&hdrbuf[nHdrPos], pch, nCopy);
907  nHdrPos += nCopy;
908 
909  // if header incomplete, exit
910  if (nHdrPos < 24)
911  return nCopy;
912 
913  // deserialize to CMessageHeader
914  try {
915  hdrbuf >> hdr;
916  }
917  catch (const std::exception&) {
918  return -1;
919  }
920 
921  // reject messages larger than MAX_SIZE
922  if (hdr.nMessageSize > MAX_SIZE)
923  return -1;
924 
925  // switch state to reading message data
926  in_data = true;
927 
928  return nCopy;
929 }
930 
931 int CNetMessage::readData(const char *pch, unsigned int nBytes)
932 {
933  unsigned int nRemaining = hdr.nMessageSize - nDataPos;
934  unsigned int nCopy = std::min(nRemaining, nBytes);
935 
936  if (vRecv.size() < nDataPos + nCopy) {
937  // Allocate up to 256 KiB ahead, but never more than the total message size.
938  vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024));
939  }
940 
941  hasher.Write((const unsigned char*)pch, nCopy);
942  memcpy(&vRecv[nDataPos], pch, nCopy);
943  nDataPos += nCopy;
944 
945  return nCopy;
946 }
947 
949 {
950  assert(complete());
951  if (data_hash.IsNull())
953  return data_hash;
954 }
955 
957 {
958  auto it = pnode->vSendMsg.begin();
959  size_t nSentSize = 0;
960 
961  while (it != pnode->vSendMsg.end()) {
962  const auto &data = *it;
963  assert(data.size() > pnode->nSendOffset);
964  int nBytes = 0;
965  {
966  LOCK(pnode->cs_hSocket);
967  if (pnode->hSocket == INVALID_SOCKET)
968  break;
969  nBytes = send(pnode->hSocket, reinterpret_cast<const char*>(data.data()) + pnode->nSendOffset, data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT);
970  }
971  if (nBytes > 0) {
972  pnode->nLastSend = GetSystemTimeInSeconds();
973  pnode->nSendBytes += nBytes;
974  pnode->nSendOffset += nBytes;
975  nSentSize += nBytes;
976  if (pnode->nSendOffset == data.size()) {
977  pnode->nSendOffset = 0;
978  pnode->nSendSize -= data.size();
979  pnode->fPauseSend = pnode->nSendSize > nSendBufferMaxSize;
980  it++;
981  } else {
982  // could not send full message; stop sending more
983  pnode->fCanSendData = false;
984  break;
985  }
986  } else {
987  if (nBytes < 0) {
988  // error
989  int nErr = WSAGetLastError();
990  if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
991  {
992  LogPrintf("socket send error %s (peer=%d)\n", NetworkErrorString(nErr), pnode->GetId());
993  pnode->fDisconnect = true;
994  }
995  }
996  // couldn't send anything at all
997  pnode->fCanSendData = false;
998  break;
999  }
1000  }
1001 
1002  if (it == pnode->vSendMsg.end()) {
1003  assert(pnode->nSendOffset == 0);
1004  assert(pnode->nSendSize == 0);
1005  }
1006  pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it);
1007  pnode->nSendMsgSize = pnode->vSendMsg.size();
1008  return nSentSize;
1009 }
1010 
1012 {
1017  int64_t nLastTXTime;
1021  uint64_t nKeyedNetGroup;
1022 };
1023 
1025 {
1026  return a.nMinPingUsecTime > b.nMinPingUsecTime;
1027 }
1028 
1030 {
1031  return a.nTimeConnected > b.nTimeConnected;
1032 }
1033 
1035  return a.nKeyedNetGroup < b.nKeyedNetGroup;
1036 }
1037 
1039 {
1040  // There is a fall-through here because it is common for a node to have many peers which have not yet relayed a block.
1043  return a.nTimeConnected > b.nTimeConnected;
1044 }
1045 
1047 {
1048  // 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.
1049  if (a.nLastTXTime != b.nLastTXTime) return a.nLastTXTime < b.nLastTXTime;
1050  if (a.fRelayTxes != b.fRelayTxes) return b.fRelayTxes;
1051  if (a.fBloomFilter != b.fBloomFilter) return a.fBloomFilter;
1052  return a.nTimeConnected > b.nTimeConnected;
1053 }
1054 
1055 
1057 template<typename T, typename Comparator>
1058 static void EraseLastKElements(std::vector<T> &elements, Comparator comparator, size_t k)
1059 {
1060  std::sort(elements.begin(), elements.end(), comparator);
1061  size_t eraseSize = std::min(k, elements.size());
1062  elements.erase(elements.end() - eraseSize, elements.end());
1063 }
1064 
1074 {
1075  std::vector<NodeEvictionCandidate> vEvictionCandidates;
1076  {
1077  LOCK(cs_vNodes);
1078 
1079  for (const CNode* node : vNodes) {
1080  if (node->fWhitelisted)
1081  continue;
1082  if (!node->fInbound)
1083  continue;
1084  if (node->fDisconnect)
1085  continue;
1086 
1087  if (fMasternodeMode) {
1088  // This handles eviction protected nodes. Nodes are always protected for a short time after the connection
1089  // was accepted. This short time is meant for the VERSION/VERACK exchange and the possible MNAUTH that might
1090  // follow when the incoming connection is from another masternode. When a message other than MNAUTH
1091  // is received after VERSION/VERACK, the protection is lifted immediately.
1092  bool isProtected = GetSystemTimeInSeconds() - node->nTimeConnected < INBOUND_EVICTION_PROTECTION_TIME;
1093  if (node->nTimeFirstMessageReceived != 0 && !node->fFirstMessageIsMNAUTH) {
1094  isProtected = false;
1095  }
1096  // if MNAUTH was valid, the node is always protected (and at the same time not accounted when
1097  // checking incoming connection limits)
1098  if (!node->verifiedProRegTxHash.IsNull()) {
1099  isProtected = true;
1100  }
1101  if (isProtected) {
1102  continue;
1103  }
1104  }
1105 
1106  NodeEvictionCandidate candidate = {node->GetId(), node->nTimeConnected, node->nMinPingUsecTime,
1107  node->nLastBlockTime, node->nLastTXTime,
1108  HasAllDesirableServiceFlags(node->nServices),
1109  node->fRelayTxes, node->pfilter != nullptr, node->nKeyedNetGroup};
1110  vEvictionCandidates.push_back(candidate);
1111  }
1112  }
1113 
1114  // Protect connections with certain characteristics
1115 
1116  // Deterministically select 4 peers to protect by netgroup.
1117  // An attacker cannot predict which netgroups will be protected
1118  EraseLastKElements(vEvictionCandidates, CompareNetGroupKeyed, 4);
1119  // Protect the 8 nodes with the lowest minimum ping time.
1120  // An attacker cannot manipulate this metric without physically moving nodes closer to the target.
1121  EraseLastKElements(vEvictionCandidates, ReverseCompareNodeMinPingTime, 8);
1122  // Protect 4 nodes that most recently sent us transactions.
1123  // An attacker cannot manipulate this metric without performing useful work.
1124  EraseLastKElements(vEvictionCandidates, CompareNodeTXTime, 4);
1125  // Protect 4 nodes that most recently sent us blocks.
1126  // An attacker cannot manipulate this metric without performing useful work.
1127  EraseLastKElements(vEvictionCandidates, CompareNodeBlockTime, 4);
1128  // Protect the half of the remaining nodes which have been connected the longest.
1129  // This replicates the non-eviction implicit behavior, and precludes attacks that start later.
1130  EraseLastKElements(vEvictionCandidates, ReverseCompareNodeTimeConnected, vEvictionCandidates.size() / 2);
1131 
1132  if (vEvictionCandidates.empty()) return false;
1133 
1134  // Identify the network group with the most connections and youngest member.
1135  // (vEvictionCandidates is already sorted by reverse connect time)
1136  uint64_t naMostConnections;
1137  unsigned int nMostConnections = 0;
1138  int64_t nMostConnectionsTime = 0;
1139  std::map<uint64_t, std::vector<NodeEvictionCandidate> > mapNetGroupNodes;
1140  for (const NodeEvictionCandidate &node : vEvictionCandidates) {
1141  std::vector<NodeEvictionCandidate> &group = mapNetGroupNodes[node.nKeyedNetGroup];
1142  group.push_back(node);
1143  int64_t grouptime = group[0].nTimeConnected;
1144 
1145  if (group.size() > nMostConnections || (group.size() == nMostConnections && grouptime > nMostConnectionsTime)) {
1146  nMostConnections = group.size();
1147  nMostConnectionsTime = grouptime;
1148  naMostConnections = node.nKeyedNetGroup;
1149  }
1150  }
1151 
1152  // Reduce to the network group with the most connections
1153  vEvictionCandidates = std::move(mapNetGroupNodes[naMostConnections]);
1154 
1155  // Disconnect from the network group with the most connections
1156  NodeId evicted = vEvictionCandidates.front().id;
1157  LOCK(cs_vNodes);
1158  for (CNode* pnode : vNodes) {
1159  if (pnode->GetId() == evicted) {
1160  pnode->fDisconnect = true;
1161  return true;
1162  }
1163  }
1164  return false;
1165 }
1166 
1167 void CConnman::AcceptConnection(const ListenSocket& hListenSocket) {
1168  struct sockaddr_storage sockaddr;
1169  socklen_t len = sizeof(sockaddr);
1170  SOCKET hSocket = accept(hListenSocket.socket, (struct sockaddr*)&sockaddr, &len);
1171  CAddress addr;
1172  int nInbound = 0;
1173  int nVerifiedInboundMasternodes = 0;
1174  int nMaxInbound = nMaxConnections - (nMaxOutbound + nMaxFeeler);
1175 
1176  if (hSocket != INVALID_SOCKET) {
1177  if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr)) {
1178  LogPrintf("Warning: Unknown socket family\n");
1179  }
1180  }
1181 
1182  bool whitelisted = hListenSocket.whitelisted || IsWhitelistedRange(addr);
1183  {
1184  LOCK(cs_vNodes);
1185  for (const CNode* pnode : vNodes) {
1186  if (pnode->fInbound) {
1187  nInbound++;
1188  if (!pnode->verifiedProRegTxHash.IsNull()) {
1189  nVerifiedInboundMasternodes++;
1190  }
1191  }
1192  }
1193 
1194  }
1195 
1196  if (hSocket == INVALID_SOCKET)
1197  {
1198  int nErr = WSAGetLastError();
1199  if (nErr != WSAEWOULDBLOCK)
1200  LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr));
1201  return;
1202  }
1203 
1204  std::string strDropped;
1205  if (fLogIPs) {
1206  strDropped = strprintf("connection from %s dropped", addr.ToString());
1207  } else {
1208  strDropped = "connection dropped";
1209  }
1210 
1211  if (!fNetworkActive) {
1212  LogPrintf("%s: not accepting new connections\n", strDropped);
1213  CloseSocket(hSocket);
1214  return;
1215  }
1216 
1217  if (!IsSelectableSocket(hSocket))
1218  {
1219  LogPrintf("%s: non-selectable socket\n", strDropped);
1220  CloseSocket(hSocket);
1221  return;
1222  }
1223 
1224  // According to the internet TCP_NODELAY is not carried into accepted sockets
1225  // on all platforms. Set it again here just to be sure.
1226  SetSocketNoDelay(hSocket);
1227 
1228  if (IsBanned(addr) && !whitelisted)
1229  {
1230  LogPrint(BCLog::NET, "%s (banned)\n", strDropped);
1231  CloseSocket(hSocket);
1232  return;
1233  }
1234 
1235  // Evict connections until we are below nMaxInbound. In case eviction protection resulted in nodes to not be evicted
1236  // before, they might get evicted in batches now (after the protection timeout).
1237  // We don't evict verified MN connections and also don't take them into account when checking limits. We can do this
1238  // because we know that such connections are naturally limited by the total number of MNs, so this is not usable
1239  // for attacks.
1240  while (nInbound - nVerifiedInboundMasternodes >= nMaxInbound)
1241  {
1242  if (!AttemptToEvictConnection()) {
1243  // No connection to evict, disconnect the new connection
1244  LogPrint(BCLog::NET, "failed to find an eviction candidate - connection dropped (full)\n");
1245  CloseSocket(hSocket);
1246  return;
1247  }
1248  nInbound--;
1249  }
1250 
1251  // don't accept incoming connections until fully synced
1253  LogPrint(BCLog::NET, "AcceptConnection -- masternode is not synced yet, skipping inbound connection attempt\n");
1254  CloseSocket(hSocket);
1255  return;
1256  }
1257 
1258  NodeId id = GetNewNodeId();
1260  CAddress addr_bind = GetBindAddress(hSocket);
1261 
1262  CNode* pnode = new CNode(id, nLocalServices, GetBestHeight(), hSocket, addr, CalculateKeyedNetGroup(addr), nonce, addr_bind, "", true);
1263  pnode->AddRef();
1264  pnode->fWhitelisted = whitelisted;
1265  m_msgproc->InitializeNode(pnode);
1266 
1267  if (fLogIPs) {
1268  LogPrint(BCLog::NET_NETCONN, "connection from %s accepted, sock=%d, peer=%d\n", addr.ToString(), pnode->hSocket, pnode->GetId());
1269  } else {
1270  LogPrint(BCLog::NET_NETCONN, "connection accepted, sock=%d, peer=%d\n", pnode->hSocket, pnode->GetId());
1271  }
1272 
1273  {
1274  LOCK(cs_vNodes);
1275  vNodes.push_back(pnode);
1276  mapSocketToNode.emplace(pnode->hSocket, pnode);
1277  RegisterEvents(pnode);
1278  WakeSelect();
1279  }
1280 }
1281 
1283 {
1284  {
1285  LOCK(cs_vNodes);
1286 
1287  if (!fNetworkActive) {
1288  // Disconnect any connected nodes
1289  for (CNode* pnode : vNodes) {
1290  if (!pnode->fDisconnect) {
1291  LogPrint(BCLog::NET, "Network not active, dropping peer=%d\n", pnode->GetId());
1292  pnode->fDisconnect = true;
1293  }
1294  }
1295  }
1296 
1297  // Disconnect unused nodes
1298  for (auto it = vNodes.begin(); it != vNodes.end(); )
1299  {
1300  CNode* pnode = *it;
1301  if (pnode->fDisconnect)
1302  {
1303  // If we were the ones who initiated the disconnect, we must assume that the other side wants to see
1304  // pending messages. If the other side initiated the disconnect (or disconnected after we've shutdown
1305  // the socket), we can be pretty sure that they are not interested in any pending messages anymore and
1306  // thus can immediately close the socket.
1307  if (!pnode->fOtherSideDisconnected) {
1308  if (pnode->nDisconnectLingerTime == 0) {
1309  // let's not immediately close the socket but instead wait for at least 100ms so that there is a
1310  // chance to flush all/some pending data. Otherwise the other side might not receive REJECT messages
1311  // that were pushed right before setting fDisconnect=true
1312  // Flushing must happen in two places to ensure data can be received by the other side:
1313  // 1. vSendMsg must be empty and all messages sent via send(). This is ensured by SocketHandler()
1314  // being called before DisconnectNodes and also by the linger time
1315  // 2. Internal socket send buffers must be flushed. This is ensured solely by the linger time
1316  pnode->nDisconnectLingerTime = GetTimeMillis() + 100;
1317  }
1318  if (GetTimeMillis() < pnode->nDisconnectLingerTime) {
1319  // everything flushed to the kernel?
1320  if (!pnode->fSocketShutdown && pnode->nSendMsgSize == 0) {
1321  LOCK(pnode->cs_hSocket);
1322  if (pnode->hSocket != INVALID_SOCKET) {
1323  // Give the other side a chance to detect the disconnect as early as possible (recv() will return 0)
1324  ::shutdown(pnode->hSocket, SD_SEND);
1325  }
1326  pnode->fSocketShutdown = true;
1327  }
1328  ++it;
1329  continue;
1330  }
1331  }
1332 
1333  if (fLogIPs) {
1334  LogPrintf("ThreadSocketHandler -- removing node: peer=%d addr=%s nRefCount=%d fInbound=%d fMasternode=%d\n",
1335  pnode->GetId(), pnode->addr.ToString(), pnode->GetRefCount(), pnode->fInbound, pnode->fMasternode);
1336  } else {
1337  LogPrintf("ThreadSocketHandler -- removing node: peer=%d nRefCount=%d fInbound=%d fMasternode=%d\n",
1338  pnode->GetId(), pnode->GetRefCount(), pnode->fInbound, pnode->fMasternode);
1339  }
1340 
1341  // remove from vNodes
1342  it = vNodes.erase(it);
1343 
1344  // release outbound grant (if any)
1345  pnode->grantOutbound.Release();
1346 
1347  // close socket and cleanup
1348  pnode->CloseSocketDisconnect(this);
1349 
1350  // hold in disconnected pool until all refs are released
1351  pnode->Release();
1352  vNodesDisconnected.push_back(pnode);
1353  } else {
1354  ++it;
1355  }
1356  }
1357  }
1358  {
1359  // Delete disconnected nodes
1360  std::list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
1361  for (auto it = vNodesDisconnected.begin(); it != vNodesDisconnected.end(); )
1362  {
1363  CNode* pnode = *it;
1364  // wait until threads are done using it
1365  bool fDelete = false;
1366  if (pnode->GetRefCount() <= 0) {
1367  {
1368  TRY_LOCK(pnode->cs_inventory, lockInv);
1369  if (lockInv) {
1370  TRY_LOCK(pnode->cs_vSend, lockSend);
1371  if (lockSend) {
1372  fDelete = true;
1373  }
1374  }
1375  }
1376  if (fDelete) {
1377  it = vNodesDisconnected.erase(it);
1378  DeleteNode(pnode);
1379  }
1380  }
1381  if (!fDelete) {
1382  ++it;
1383  }
1384  }
1385  }
1386 }
1387 
1389 {
1390  size_t vNodesSize;
1391  {
1392  LOCK(cs_vNodes);
1393  vNodesSize = vNodes.size();
1394  }
1395 
1396  // If we had zero connections before and new connections now or if we just dropped
1397  // to zero connections reset the sync process if its outdated.
1398  if ((vNodesSize > 0 && nPrevNodeCount == 0) || (vNodesSize == 0 && nPrevNodeCount > 0)) {
1400  }
1401 
1402  if(vNodesSize != nPrevNodeCount) {
1403  nPrevNodeCount = vNodesSize;
1404  if(clientInterface)
1406  }
1407 }
1408 
1410 {
1411  int64_t nTime = GetSystemTimeInSeconds();
1412  if (nTime - pnode->nTimeConnected > 60)
1413  {
1414  if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
1415  {
1416  LogPrint(BCLog::NET, "socket no message in first 60 seconds, %d %d from %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0, pnode->GetId());
1417  pnode->fDisconnect = true;
1418  }
1419  else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL)
1420  {
1421  LogPrintf("socket sending timeout: %is\n", nTime - pnode->nLastSend);
1422  pnode->fDisconnect = true;
1423  }
1424  else if (nTime - pnode->nLastRecv > (pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL : 90*60))
1425  {
1426  LogPrintf("socket receive timeout: %is\n", nTime - pnode->nLastRecv);
1427  pnode->fDisconnect = true;
1428  }
1429  else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros())
1430  {
1431  LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart));
1432  pnode->fDisconnect = true;
1433  }
1434  else if (!pnode->fSuccessfullyConnected)
1435  {
1436  LogPrint(BCLog::NET, "version handshake timeout from %d\n", pnode->GetId());
1437  pnode->fDisconnect = true;
1438  }
1439  }
1440 }
1441 
1442 bool CConnman::GenerateSelectSet(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set)
1443 {
1444  for (const ListenSocket& hListenSocket : vhListenSocket) {
1445  recv_set.insert(hListenSocket.socket);
1446  }
1447 
1448  {
1449  LOCK(cs_vNodes);
1450  for (CNode* pnode : vNodes)
1451  {
1452  bool select_recv = !pnode->fHasRecvData;
1453  bool select_send = !pnode->fCanSendData;
1454 
1455  LOCK(pnode->cs_hSocket);
1456  if (pnode->hSocket == INVALID_SOCKET)
1457  continue;
1458 
1459  error_set.insert(pnode->hSocket);
1460  if (select_send) {
1461  send_set.insert(pnode->hSocket);
1462  }
1463  if (select_recv) {
1464  recv_set.insert(pnode->hSocket);
1465  }
1466  }
1467  }
1468 
1469 #ifdef USE_WAKEUP_PIPE
1470  // We add a pipe to the read set so that the select() call can be woken up from the outside
1471  // This is done when data is added to send buffers (vSendMsg) or when new peers are added
1472  // This is currently only implemented for POSIX compliant systems. This means that Windows will fall back to
1473  // timing out after 50ms and then trying to send. This is ok as we assume that heavy-load daemons are usually
1474  // run on Linux and friends.
1475  recv_set.insert(wakeupPipe[0]);
1476 #endif
1477 
1478  return !recv_set.empty() || !send_set.empty() || !error_set.empty();
1479 }
1480 
1481 #ifdef USE_EPOLL
1482 void CConnman::SocketEventsEpoll(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set, bool fOnlyPoll)
1483 {
1484  const size_t maxEvents = 64;
1485  epoll_event events[maxEvents];
1486 
1487  wakeupSelectNeeded = true;
1488  int n = epoll_wait(epollfd, events, maxEvents, fOnlyPoll ? 0 : SELECT_TIMEOUT_MILLISECONDS);
1489  wakeupSelectNeeded = false;
1490  for (int i = 0; i < n; i++) {
1491  auto& e = events[i];
1492  if((e.events & EPOLLERR) || (e.events & EPOLLHUP)) {
1493  error_set.insert((SOCKET)e.data.fd);
1494  continue;
1495  }
1496 
1497  if (e.events & EPOLLIN) {
1498  recv_set.insert((SOCKET)e.data.fd);
1499  }
1500 
1501  if (e.events & EPOLLOUT) {
1502  send_set.insert((SOCKET)e.data.fd);
1503  }
1504  }
1505 }
1506 #endif
1507 
1508 #ifdef USE_POLL
1509 void CConnman::SocketEventsPoll(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set, bool fOnlyPoll)
1510 {
1511  std::set<SOCKET> recv_select_set, send_select_set, error_select_set;
1512  if (!GenerateSelectSet(recv_select_set, send_select_set, error_select_set)) {
1513  if (!fOnlyPoll) interruptNet.sleep_for(std::chrono::milliseconds(SELECT_TIMEOUT_MILLISECONDS));
1514  return;
1515  }
1516 
1517  std::unordered_map<SOCKET, struct pollfd> pollfds;
1518  for (SOCKET socket_id : recv_select_set) {
1519  pollfds[socket_id].fd = socket_id;
1520  pollfds[socket_id].events |= POLLIN;
1521  }
1522 
1523  for (SOCKET socket_id : send_select_set) {
1524  pollfds[socket_id].fd = socket_id;
1525  pollfds[socket_id].events |= POLLOUT;
1526  }
1527 
1528  for (SOCKET socket_id : error_select_set) {
1529  pollfds[socket_id].fd = socket_id;
1530  // These flags are ignored, but we set them for clarity
1531  pollfds[socket_id].events |= POLLERR|POLLHUP;
1532  }
1533 
1534  std::vector<struct pollfd> vpollfds;
1535  vpollfds.reserve(pollfds.size());
1536  for (auto it : pollfds) {
1537  vpollfds.push_back(std::move(it.second));
1538  }
1539 
1540  wakeupSelectNeeded = true;
1541  int r = poll(vpollfds.data(), vpollfds.size(), fOnlyPoll ? 0 : SELECT_TIMEOUT_MILLISECONDS);
1542  wakeupSelectNeeded = false;
1543  if (r < 0) {
1544  return;
1545  }
1546 
1547  if (interruptNet) return;
1548 
1549  for (struct pollfd pollfd_entry : vpollfds) {
1550  if (pollfd_entry.revents & POLLIN) recv_set.insert(pollfd_entry.fd);
1551  if (pollfd_entry.revents & POLLOUT) send_set.insert(pollfd_entry.fd);
1552  if (pollfd_entry.revents & (POLLERR|POLLHUP)) error_set.insert(pollfd_entry.fd);
1553  }
1554 }
1555 #endif
1556 
1557 void CConnman::SocketEventsSelect(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set, bool fOnlyPoll)
1558 {
1559  std::set<SOCKET> recv_select_set, send_select_set, error_select_set;
1560  if (!GenerateSelectSet(recv_select_set, send_select_set, error_select_set)) {
1561  interruptNet.sleep_for(std::chrono::milliseconds(SELECT_TIMEOUT_MILLISECONDS));
1562  return;
1563  }
1564 
1565  //
1566  // Find which sockets have data to receive
1567  //
1568  struct timeval timeout;
1569  timeout.tv_sec = 0;
1570  timeout.tv_usec = fOnlyPoll ? 0 : SELECT_TIMEOUT_MILLISECONDS * 1000; // frequency to poll pnode->vSend
1571 
1572  fd_set fdsetRecv;
1573  fd_set fdsetSend;
1574  fd_set fdsetError;
1575  FD_ZERO(&fdsetRecv);
1576  FD_ZERO(&fdsetSend);
1577  FD_ZERO(&fdsetError);
1578  SOCKET hSocketMax = 0;
1579 
1580  for (SOCKET hSocket : recv_select_set) {
1581  FD_SET(hSocket, &fdsetRecv);
1582  hSocketMax = std::max(hSocketMax, hSocket);
1583  }
1584 
1585  for (SOCKET hSocket : send_select_set) {
1586  FD_SET(hSocket, &fdsetSend);
1587  hSocketMax = std::max(hSocketMax, hSocket);
1588  }
1589 
1590  for (SOCKET hSocket : error_select_set) {
1591  FD_SET(hSocket, &fdsetError);
1592  hSocketMax = std::max(hSocketMax, hSocket);
1593  }
1594 
1595  wakeupSelectNeeded = true;
1596  int nSelect = select(hSocketMax + 1, &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
1597  wakeupSelectNeeded = false;
1598  if (interruptNet)
1599  return;
1600 
1601  if (nSelect == SOCKET_ERROR)
1602  {
1603  int nErr = WSAGetLastError();
1604  LogPrintf("socket select error %s\n", NetworkErrorString(nErr));
1605  for (unsigned int i = 0; i <= hSocketMax; i++)
1606  FD_SET(i, &fdsetRecv);
1607  FD_ZERO(&fdsetSend);
1608  FD_ZERO(&fdsetError);
1609  if (!interruptNet.sleep_for(std::chrono::milliseconds(SELECT_TIMEOUT_MILLISECONDS)))
1610  return;
1611  }
1612 
1613  for (SOCKET hSocket : recv_select_set) {
1614  if (FD_ISSET(hSocket, &fdsetRecv)) {
1615  recv_set.insert(hSocket);
1616  }
1617  }
1618 
1619  for (SOCKET hSocket : send_select_set) {
1620  if (FD_ISSET(hSocket, &fdsetSend)) {
1621  send_set.insert(hSocket);
1622  }
1623  }
1624 
1625  for (SOCKET hSocket : error_select_set) {
1626  if (FD_ISSET(hSocket, &fdsetError)) {
1627  error_set.insert(hSocket);
1628  }
1629  }
1630 }
1631 
1632 void CConnman::SocketEvents(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set, bool fOnlyPoll)
1633 {
1634  switch (socketEventsMode) {
1635 #ifdef USE_EPOLL
1636  case SOCKETEVENTS_EPOLL:
1637  SocketEventsEpoll(recv_set, send_set, error_set, fOnlyPoll);
1638  break;
1639 #endif
1640 #ifdef USE_POLL
1641  case SOCKETEVENTS_POLL:
1642  SocketEventsPoll(recv_set, send_set, error_set, fOnlyPoll);
1643  break;
1644 #endif
1645  case SOCKETEVENTS_SELECT:
1646  SocketEventsSelect(recv_set, send_set, error_set, fOnlyPoll);
1647  break;
1648  default:
1649  assert(false);
1650  }
1651 }
1652 
1654 {
1655  bool fOnlyPoll = false;
1656  {
1657  // check if we have work to do and thus should avoid waiting for events
1659  if (!mapReceivableNodes.empty()) {
1660  fOnlyPoll = true;
1661  } else if (!mapSendableNodes.empty() && !mapNodesWithDataToSend.empty()) {
1662  // we must check if at least one of the nodes with pending messages is also sendable, as otherwise a single
1663  // node would be able to make the network thread busy with polling
1664  for (auto& p : mapNodesWithDataToSend) {
1665  if (mapSendableNodes.count(p.first)) {
1666  fOnlyPoll = true;
1667  break;
1668  }
1669  }
1670  }
1671  }
1672 
1673  std::set<SOCKET> recv_set, send_set, error_set;
1674  SocketEvents(recv_set, send_set, error_set, fOnlyPoll);
1675 
1676 #ifdef USE_WAKEUP_PIPE
1677  // drain the wakeup pipe
1678  if (recv_set.count(wakeupPipe[0])) {
1679  char buf[128];
1680  while (true) {
1681  int r = read(wakeupPipe[0], buf, sizeof(buf));
1682  if (r <= 0) {
1683  break;
1684  }
1685  }
1686  }
1687 #endif
1688 
1689  if (interruptNet) return;
1690 
1691  //
1692  // Accept new connections
1693  //
1694  for (const ListenSocket& hListenSocket : vhListenSocket)
1695  {
1696  if (hListenSocket.socket != INVALID_SOCKET && recv_set.count(hListenSocket.socket) > 0)
1697  {
1698  AcceptConnection(hListenSocket);
1699  }
1700  }
1701 
1702  std::vector<CNode*> vErrorNodes;
1703  std::vector<CNode*> vReceivableNodes;
1704  std::vector<CNode*> vSendableNodes;
1705  {
1706  LOCK(cs_vNodes);
1707  for (auto hSocket : error_set) {
1708  auto it = mapSocketToNode.find(hSocket);
1709  if (it == mapSocketToNode.end()) {
1710  continue;
1711  }
1712  it->second->AddRef();
1713  vErrorNodes.emplace_back(it->second);
1714  }
1715  for (auto hSocket : recv_set) {
1716  if (error_set.count(hSocket)) {
1717  // no need to handle it twice
1718  continue;
1719  }
1720 
1721  auto it = mapSocketToNode.find(hSocket);
1722  if (it == mapSocketToNode.end()) {
1723  continue;
1724  }
1725 
1726  auto jt = mapReceivableNodes.emplace(it->second->GetId(), it->second);
1727  assert(jt.first->second == it->second);
1728  it->second->fHasRecvData = true;
1729  }
1730  for (auto hSocket : send_set) {
1731  auto it = mapSocketToNode.find(hSocket);
1732  if (it == mapSocketToNode.end()) {
1733  continue;
1734  }
1735 
1736  auto jt = mapSendableNodes.emplace(it->second->GetId(), it->second);
1737  assert(jt.first->second == it->second);
1738  it->second->fCanSendData = true;
1739  }
1740 
1741  // collect nodes that have a receivable socket
1742  // also clean up mapReceivableNodes from nodes that were receivable in the last iteration but aren't anymore
1743  vReceivableNodes.reserve(mapReceivableNodes.size());
1744  for (auto it = mapReceivableNodes.begin(); it != mapReceivableNodes.end(); ) {
1745  if (!it->second->fHasRecvData) {
1746  it = mapReceivableNodes.erase(it);
1747  } else {
1748  // Implement the following logic:
1749  // * If there is data to send, try sending data. As this only
1750  // happens when optimistic write failed, we choose to first drain the
1751  // write buffer in this case before receiving more. This avoids
1752  // needlessly queueing received data, if the remote peer is not themselves
1753  // receiving data. This means properly utilizing TCP flow control signalling.
1754  // * Otherwise, if there is space left in the receive buffer (!fPauseRecv), try
1755  // receiving data (which should succeed as the socket signalled as receivable).
1756  if (!it->second->fPauseRecv && it->second->nSendMsgSize == 0 && !it->second->fDisconnect) {
1757  it->second->AddRef();
1758  vReceivableNodes.emplace_back(it->second);
1759  }
1760  ++it;
1761  }
1762  }
1763 
1764  // collect nodes that have data to send and have a socket with non-empty write buffers
1765  // also clean up mapNodesWithDataToSend from nodes that had messages to send in the last iteration
1766  // but don't have any in this iteration
1768  vSendableNodes.reserve(mapNodesWithDataToSend.size());
1769  for (auto it = mapNodesWithDataToSend.begin(); it != mapNodesWithDataToSend.end(); ) {
1770  if (it->second->nSendMsgSize == 0) {
1771  // See comment in PushMessage
1772  it->second->Release();
1773  it = mapNodesWithDataToSend.erase(it);
1774  } else {
1775  if (it->second->fCanSendData) {
1776  it->second->AddRef();
1777  vSendableNodes.emplace_back(it->second);
1778  }
1779  ++it;
1780  }
1781  }
1782  }
1783 
1784  for (CNode* pnode : vErrorNodes)
1785  {
1786  if (interruptNet) {
1787  break;
1788  }
1789  // let recv() return errors and then handle it
1790  SocketRecvData(pnode);
1791  }
1792 
1793  for (CNode* pnode : vReceivableNodes)
1794  {
1795  if (interruptNet) {
1796  break;
1797  }
1798  if (pnode->fPauseRecv) {
1799  continue;
1800  }
1801 
1802  SocketRecvData(pnode);
1803  }
1804 
1805  for (CNode* pnode : vSendableNodes) {
1806  if (interruptNet) {
1807  break;
1808  }
1809 
1810  LOCK(pnode->cs_vSend);
1811  size_t nBytes = SocketSendData(pnode);
1812  if (nBytes) {
1813  RecordBytesSent(nBytes);
1814  }
1815  }
1816 
1817  ReleaseNodeVector(vErrorNodes);
1818  ReleaseNodeVector(vReceivableNodes);
1819  ReleaseNodeVector(vSendableNodes);
1820 
1821  if (interruptNet) {
1822  return;
1823  }
1824 
1825  {
1826  LOCK(cs_vNodes);
1827  // remove nodes from mapSendableNodes, so that the next iteration knows that there is no work to do
1828  // (even if there are pending messages to be sent)
1829  for (auto it = mapSendableNodes.begin(); it != mapSendableNodes.end(); ) {
1830  if (!it->second->fCanSendData) {
1831  LogPrint(BCLog::NET, "%s -- remove mapSendableNodes, peer=%d\n", __func__, it->second->GetId());
1832  it = mapSendableNodes.erase(it);
1833  } else {
1834  ++it;
1835  }
1836  }
1837  }
1838 }
1839 
1841 {
1842  // typical socket buffer is 8K-64K
1843  char pchBuf[0x10000];
1844  int nBytes = 0;
1845  {
1846  LOCK(pnode->cs_hSocket);
1847  if (pnode->hSocket == INVALID_SOCKET)
1848  return 0;
1849  nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
1850  if (nBytes < (int)sizeof(pchBuf)) {
1851  pnode->fHasRecvData = false;
1852  }
1853  }
1854  if (nBytes > 0)
1855  {
1856  bool notify = false;
1857  if (!pnode->ReceiveMsgBytes(pchBuf, nBytes, notify)) {
1858  LOCK(cs_vNodes);
1859  pnode->CloseSocketDisconnect(this);
1860  }
1861  RecordBytesRecv(nBytes);
1862  if (notify) {
1863  size_t nSizeAdded = 0;
1864  auto it(pnode->vRecvMsg.begin());
1865  for (; it != pnode->vRecvMsg.end(); ++it) {
1866  if (!it->complete())
1867  break;
1868  nSizeAdded += it->vRecv.size() + CMessageHeader::HEADER_SIZE;
1869  }
1870  {
1871  LOCK(pnode->cs_vProcessMsg);
1872  pnode->vProcessMsg.splice(pnode->vProcessMsg.end(), pnode->vRecvMsg, pnode->vRecvMsg.begin(), it);
1873  pnode->nProcessQueueSize += nSizeAdded;
1875  }
1877  }
1878  }
1879  else if (nBytes == 0)
1880  {
1881  // socket closed gracefully
1882  if (!pnode->fDisconnect) {
1883  LogPrint(BCLog::NET, "socket closed\n");
1884  }
1885  LOCK(cs_vNodes);
1886  pnode->fOtherSideDisconnected = true; // avoid lingering
1887  pnode->CloseSocketDisconnect(this);
1888  }
1889  else if (nBytes < 0)
1890  {
1891  // error
1892  int nErr = WSAGetLastError();
1893  if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
1894  {
1895  if (!pnode->fDisconnect)
1896  LogPrintf("socket recv error %s\n", NetworkErrorString(nErr));
1897  LOCK(cs_vNodes);
1898  pnode->fOtherSideDisconnected = true; // avoid lingering
1899  pnode->CloseSocketDisconnect(this);
1900  }
1901  }
1902  if (nBytes < 0) {
1903  return 0;
1904  }
1905  return (size_t)nBytes;
1906 }
1907 
1909 {
1910  int64_t nLastCleanupNodes = 0;
1911 
1912  while (!interruptNet)
1913  {
1914  // Handle sockets before we do the next round of disconnects. This allows us to flush send buffers one last time
1915  // before actually closing sockets. Receiving is however skipped in case a peer is pending to be disconnected
1916  SocketHandler();
1917  if (GetTimeMillis() - nLastCleanupNodes > 1000) {
1918  ForEachNode(AllNodes, [&](CNode* pnode) {
1919  InactivityCheck(pnode);
1920  });
1921  nLastCleanupNodes = GetTimeMillis();
1922  }
1923  DisconnectNodes();
1925  }
1926 }
1927 
1929 {
1930  {
1931  std::lock_guard<std::mutex> lock(mutexMsgProc);
1932  fMsgProcWake = true;
1933  }
1934  condMsgProc.notify_one();
1935 }
1936 
1938 {
1939 #ifdef USE_WAKEUP_PIPE
1940  if (wakeupPipe[1] == -1) {
1941  return;
1942  }
1943 
1944  char buf[1];
1945  if (write(wakeupPipe[1], buf, 1) != 1) {
1946  LogPrint(BCLog::NET, "write to wakeupPipe failed\n");
1947  }
1948 #endif
1949 
1950  wakeupSelectNeeded = false;
1951 }
1952 
1953 
1954 
1955 
1956 
1957 #ifdef USE_UPNP
1958 void ThreadMapPort()
1959 {
1960  std::string port = strprintf("%u", GetListenPort());
1961  const char * multicastif = nullptr;
1962  const char * minissdpdpath = nullptr;
1963  struct UPNPDev * devlist = nullptr;
1964  char lanaddr[64];
1965 
1966 #ifndef UPNPDISCOVER_SUCCESS
1967  /* miniupnpc 1.5 */
1968  devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
1969 #elif MINIUPNPC_API_VERSION < 14
1970  /* miniupnpc 1.6 */
1971  int error = 0;
1972  devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
1973 #else
1974  /* miniupnpc 1.9.20150730 */
1975  int error = 0;
1976  devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, 2, &error);
1977 #endif
1978 
1979  struct UPNPUrls urls;
1980  struct IGDdatas data;
1981  int r;
1982 
1983  r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
1984  if (r == 1)
1985  {
1986  if (fDiscover) {
1987  char externalIPAddress[40];
1988  r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
1989  if(r != UPNPCOMMAND_SUCCESS)
1990  LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r);
1991  else
1992  {
1993  if(externalIPAddress[0])
1994  {
1995  CNetAddr resolved;
1996  if(LookupHost(externalIPAddress, resolved, false)) {
1997  LogPrintf("UPnP: ExternalIPAddress = %s\n", resolved.ToString().c_str());
1998  AddLocal(resolved, LOCAL_UPNP);
1999  }
2000  }
2001  else
2002  LogPrintf("UPnP: GetExternalIPAddress failed.\n");
2003  }
2004  }
2005 
2006  std::string strDesc = "Dash Core " + FormatFullVersion();
2007 
2008  try {
2009  while (true) {
2010 #ifndef UPNPDISCOVER_SUCCESS
2011  /* miniupnpc 1.5 */
2012  r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
2013  port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
2014 #else
2015  /* miniupnpc 1.6 */
2016  r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
2017  port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
2018 #endif
2019 
2020  if(r!=UPNPCOMMAND_SUCCESS)
2021  LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
2022  port, port, lanaddr, r, strupnperror(r));
2023  else
2024  LogPrintf("UPnP Port Mapping successful.\n");
2025 
2026  MilliSleep(20*60*1000); // Refresh every 20 minutes
2027  }
2028  }
2029  catch (const boost::thread_interrupted&)
2030  {
2031  r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
2032  LogPrintf("UPNP_DeletePortMapping() returned: %d\n", r);
2033  freeUPNPDevlist(devlist); devlist = nullptr;
2034  FreeUPNPUrls(&urls);
2035  throw;
2036  }
2037  } else {
2038  LogPrintf("No valid UPnP IGDs found\n");
2039  freeUPNPDevlist(devlist); devlist = nullptr;
2040  if (r != 0)
2041  FreeUPNPUrls(&urls);
2042  }
2043 }
2044 
2045 void MapPort(bool fUseUPnP)
2046 {
2047  static std::unique_ptr<boost::thread> upnp_thread;
2048 
2049  if (fUseUPnP)
2050  {
2051  if (upnp_thread) {
2052  upnp_thread->interrupt();
2053  upnp_thread->join();
2054  }
2055  upnp_thread.reset(new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort)));
2056  }
2057  else if (upnp_thread) {
2058  upnp_thread->interrupt();
2059  upnp_thread->join();
2060  upnp_thread.reset();
2061  }
2062 }
2063 
2064 #else
2065 void MapPort(bool)
2066 {
2067  // Intentionally left blank.
2068 }
2069 #endif
2070 
2071 
2072 
2073 
2074 
2075 
2077 {
2078  // goal: only query DNS seeds if address need is acute
2079  // Avoiding DNS seeds when we don't need them improves user privacy by
2080  // creating fewer identifying DNS requests, reduces trust by giving seeds
2081  // less influence on the network topology, and reduces traffic to the seeds.
2082  if ((addrman.size() > 0) &&
2083  (!gArgs.GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED))) {
2084  if (!interruptNet.sleep_for(std::chrono::seconds(11)))
2085  return;
2086 
2087  LOCK(cs_vNodes);
2088  int nRelevant = 0;
2089  for (auto pnode : vNodes) {
2090  nRelevant += pnode->fSuccessfullyConnected && !pnode->fFeeler && !pnode->fOneShot && !pnode->m_manual_connection && !pnode->fInbound && !pnode->fMasternodeProbe;
2091  }
2092  if (nRelevant >= 2) {
2093  LogPrintf("P2P peers available. Skipped DNS seeding.\n");
2094  return;
2095  }
2096  }
2097 
2098  const std::vector<std::string> &vSeeds = Params().DNSSeeds();
2099  int found = 0;
2100 
2101  LogPrintf("Loading addresses from DNS seeds (could take a while)\n");
2102 
2103  for (const std::string &seed : vSeeds) {
2104  if (interruptNet) {
2105  return;
2106  }
2107  if (HaveNameProxy()) {
2108  AddOneShot(seed);
2109  } else {
2110  std::vector<CNetAddr> vIPs;
2111  std::vector<CAddress> vAdd;
2112  ServiceFlags requiredServiceBits = GetDesirableServiceFlags(NODE_NONE);
2113  std::string host = strprintf("x%x.%s", requiredServiceBits, seed);
2114  CNetAddr resolveSource;
2115  if (!resolveSource.SetInternal(host)) {
2116  continue;
2117  }
2118  unsigned int nMaxIPs = 256; // Limits number of IPs learned from a DNS seed
2119  if (LookupHost(host.c_str(), vIPs, nMaxIPs, true))
2120  {
2121  for (const CNetAddr& ip : vIPs)
2122  {
2123  int nOneDay = 24*3600;
2124  CAddress addr = CAddress(CService(ip, Params().GetDefaultPort()), requiredServiceBits);
2125  addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
2126  vAdd.push_back(addr);
2127  found++;
2128  }
2129  addrman.Add(vAdd, resolveSource);
2130  } else {
2131  // We now avoid directly using results from DNS Seeds which do not support service bit filtering,
2132  // instead using them as a oneshot to get nodes with our desired service bits.
2133  AddOneShot(seed);
2134  }
2135  }
2136  }
2137 
2138  LogPrintf("%d addresses found from DNS seeds\n", found);
2139 }
2140 
2141 
2142 
2143 
2144 
2145 
2146 
2147 
2148 
2149 
2150 
2151 
2153 {
2154  int64_t nStart = GetTimeMillis();
2155 
2156  CAddrDB adb;
2157  adb.Write(addrman);
2158 
2159  LogPrint(BCLog::NET, "Flushed %d addresses to peers.dat %dms\n",
2160  addrman.size(), GetTimeMillis() - nStart);
2161 }
2162 
2164 {
2165  DumpAddresses();
2166  DumpBanlist();
2167 }
2168 
2170 {
2171  std::string strDest;
2172  {
2173  LOCK(cs_vOneShots);
2174  if (vOneShots.empty())
2175  return;
2176  strDest = vOneShots.front();
2177  vOneShots.pop_front();
2178  }
2179  CAddress addr;
2180  CSemaphoreGrant grant(*semOutbound, true);
2181  if (grant) {
2182  OpenNetworkConnection(addr, false, &grant, strDest.c_str(), true);
2183  }
2184 }
2185 
2187 {
2189 }
2190 
2192 {
2194  LogPrint(BCLog::NET, "net: setting try another outbound peer=%s\n", flag ? "true" : "false");
2195 }
2196 
2197 // Return the number of peers we have over our outbound connection limit
2198 // Exclude peers that are marked for disconnect, or are going to be
2199 // disconnected soon (eg one-shots and feelers)
2200 // Also exclude peers that haven't finished initial connection handshake yet
2201 // (so that we don't decide we're over our desired connection limit, and then
2202 // evict some peer that has finished the handshake)
2204 {
2205  int nOutbound = 0;
2206  {
2207  LOCK(cs_vNodes);
2208  for (CNode* pnode : vNodes) {
2209  // don't count outbound masternodes
2210  if (pnode->fMasternode) {
2211  continue;
2212  }
2213  if (!pnode->fInbound && !pnode->m_manual_connection && !pnode->fFeeler && !pnode->fDisconnect && !pnode->fOneShot && pnode->fSuccessfullyConnected && !pnode->fMasternodeProbe) {
2214  ++nOutbound;
2215  }
2216  }
2217  }
2218  return std::max(nOutbound - nMaxOutbound, 0);
2219 }
2220 
2221 void CConnman::ThreadOpenConnections(const std::vector<std::string> connect)
2222 {
2223  // Connect to specific addresses
2224  if (!connect.empty())
2225  {
2226  for (int64_t nLoop = 0;; nLoop++)
2227  {
2228  ProcessOneShot();
2229  for (const std::string& strAddr : connect)
2230  {
2231  CAddress addr(CService(), NODE_NONE);
2232  OpenNetworkConnection(addr, false, nullptr, strAddr.c_str(), false, false, true);
2233  for (int i = 0; i < 10 && i < nLoop; i++)
2234  {
2235  if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
2236  return;
2237  }
2238  }
2239  if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
2240  return;
2241  }
2242  }
2243 
2244  // Initiate network connections
2245  int64_t nStart = GetTime();
2246 
2247  // Minimum time before next feeler connection (in microseconds).
2248  int64_t nNextFeeler = PoissonNextSend(nStart*1000*1000, FEELER_INTERVAL);
2249  while (!interruptNet)
2250  {
2251  ProcessOneShot();
2252 
2253  if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
2254  return;
2255 
2256  CSemaphoreGrant grant(*semOutbound);
2257  if (interruptNet)
2258  return;
2259 
2260  // Add seed nodes if DNS seeds are all down (an infrastructure attack?).
2261  if (addrman.size() == 0 && (GetTime() - nStart > 60)) {
2262  static bool done = false;
2263  if (!done) {
2264  LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n");
2265  CNetAddr local;
2266  local.SetInternal("fixedseeds");
2267  addrman.Add(convertSeed6(Params().FixedSeeds()), local);
2268  done = true;
2269  }
2270  }
2271 
2272  //
2273  // Choose an address to connect to based on most recently seen
2274  //
2275  CAddress addrConnect;
2276 
2277  // Only connect out to one peer per network group (/16 for IPv4).
2278  // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
2279  // This is only done for mainnet and testnet
2280  int nOutbound = 0;
2281  std::set<std::vector<unsigned char> > setConnected;
2282  if (!Params().AllowMultipleAddressesFromGroup()) {
2283  LOCK(cs_vNodes);
2284  for (CNode* pnode : vNodes) {
2285  if (!pnode->fInbound && !pnode->fMasternode && !pnode->m_manual_connection) {
2286  // Netgroups for inbound and addnode peers are not excluded because our goal here
2287  // is to not use multiple of our limited outbound slots on a single netgroup
2288  // but inbound and addnode peers do not use our outbound slots. Inbound peers
2289  // also have the added issue that they're attacker controlled and could be used
2290  // to prevent us from connecting to particular hosts if we used them here.
2291  setConnected.insert(pnode->addr.GetGroup());
2292  nOutbound++;
2293  }
2294  }
2295  }
2296 
2297  std::set<uint256> setConnectedMasternodes;
2298  {
2299  LOCK(cs_vNodes);
2300  for (CNode* pnode : vNodes) {
2301  if (!pnode->verifiedProRegTxHash.IsNull()) {
2302  setConnectedMasternodes.emplace(pnode->verifiedProRegTxHash);
2303  }
2304  }
2305  }
2306 
2307  // Feeler Connections
2308  //
2309  // Design goals:
2310  // * Increase the number of connectable addresses in the tried table.
2311  //
2312  // Method:
2313  // * Choose a random address from new and attempt to connect to it if we can connect
2314  // successfully it is added to tried.
2315  // * Start attempting feeler connections only after node finishes making outbound
2316  // connections.
2317  // * Only make a feeler connection once every few minutes.
2318  //
2319  bool fFeeler = false;
2320 
2321  if (nOutbound >= nMaxOutbound && !GetTryNewOutboundPeer()) {
2322  int64_t nTime = GetTimeMicros(); // The current time right now (in microseconds).
2323  if (nTime > nNextFeeler) {
2324  nNextFeeler = PoissonNextSend(nTime, FEELER_INTERVAL);
2325  fFeeler = true;
2326  } else {
2327  continue;
2328  }
2329  }
2330 
2331  auto mnList = deterministicMNManager->GetListAtChainTip();
2332 
2333  int64_t nANow = GetAdjustedTime();
2334  int nTries = 0;
2335  while (!interruptNet)
2336  {
2337  CAddrInfo addr = addrman.Select(fFeeler);
2338 
2339  auto dmn = mnList.GetMNByService(addr);
2340  bool isMasternode = dmn != nullptr;
2341 
2342  // if we selected an invalid address, restart
2343  if (!addr.IsValid() || setConnected.count(addr.GetGroup()))
2344  break;
2345 
2346  // don't try to connect to masternodes that we already have a connection to (most likely inbound)
2347  if (isMasternode && setConnectedMasternodes.count(dmn->proTxHash))
2348  break;
2349 
2350  // if we selected a local address, restart (local addresses are allowed in regtest and devnet)
2351  bool fAllowLocal = Params().AllowMultiplePorts() && addrConnect.GetPort() != GetListenPort();
2352  if (!fAllowLocal && IsLocal(addrConnect))
2353  break;
2354 
2355  // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
2356  // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
2357  // already-connected network ranges, ...) before trying new addrman addresses.
2358  nTries++;
2359  if (nTries > 100)
2360  break;
2361 
2362  if (IsLimited(addr))
2363  continue;
2364 
2365  // only consider very recently tried nodes after 30 failed attempts
2366  if (nANow - addr.nLastTry < 600 && nTries < 30)
2367  continue;
2368 
2369  // for non-feelers, require all the services we'll want,
2370  // for feelers, only require they be a full node (only because most
2371  // SPV clients don't have a good address DB available)
2372  if (!isMasternode && !fFeeler && !HasAllDesirableServiceFlags(addr.nServices)) {
2373  continue;
2374  } else if (!isMasternode && fFeeler && !MayHaveUsefulAddressDB(addr.nServices)) {
2375  continue;
2376  }
2377 
2378  // do not allow non-default ports, unless after 50 invalid addresses selected already
2379  if ((!isMasternode || !Params().AllowMultiplePorts()) && addr.GetPort() != Params().GetDefaultPort() && addr.GetPort() != GetListenPort() && nTries < 50)
2380  continue;
2381 
2382  addrConnect = addr;
2383  break;
2384  }
2385 
2386  if (addrConnect.IsValid()) {
2387 
2388  if (fFeeler) {
2389  // Add small amount of random noise before connection to avoid synchronization.
2390  int randsleep = GetRandInt(FEELER_SLEEP_WINDOW * 1000);
2391  if (!interruptNet.sleep_for(std::chrono::milliseconds(randsleep)))
2392  return;
2393  if (fLogIPs) {
2394  LogPrint(BCLog::NET, "Making feeler connection to %s\n", addrConnect.ToString());
2395  } else {
2396  LogPrint(BCLog::NET, "Making feeler connection\n");
2397  }
2398  }
2399 
2400  OpenNetworkConnection(addrConnect, (int)setConnected.size() >= std::min(nMaxConnections - 1, 2), &grant, nullptr, false, fFeeler);
2401  }
2402  }
2403 }
2404 
2405 std::vector<AddedNodeInfo> CConnman::GetAddedNodeInfo()
2406 {
2407  std::vector<AddedNodeInfo> ret;
2408 
2409  std::list<std::string> lAddresses(0);
2410  {
2412  ret.reserve(vAddedNodes.size());
2413  std::copy(vAddedNodes.cbegin(), vAddedNodes.cend(), std::back_inserter(lAddresses));
2414  }
2415 
2416 
2417  // Build a map of all already connected addresses (by IP:port and by name) to inbound/outbound and resolved CService
2418  std::map<CService, bool> mapConnected;
2419  std::map<std::string, std::pair<bool, CService>> mapConnectedByName;
2420  {
2421  LOCK(cs_vNodes);
2422  for (const CNode* pnode : vNodes) {
2423  if (pnode->addr.IsValid()) {
2424  mapConnected[pnode->addr] = pnode->fInbound;
2425  }
2426  std::string addrName = pnode->GetAddrName();
2427  if (!addrName.empty()) {
2428  mapConnectedByName[std::move(addrName)] = std::make_pair(pnode->fInbound, static_cast<const CService&>(pnode->addr));
2429  }
2430  }
2431  }
2432 
2433  for (const std::string& strAddNode : lAddresses) {
2434  CService service(LookupNumeric(strAddNode.c_str(), Params().GetDefaultPort()));
2435  AddedNodeInfo addedNode{strAddNode, CService(), false, false};
2436  if (service.IsValid()) {
2437  // strAddNode is an IP:port
2438  auto it = mapConnected.find(service);
2439  if (it != mapConnected.end()) {
2440  addedNode.resolvedAddress = service;
2441  addedNode.fConnected = true;
2442  addedNode.fInbound = it->second;
2443  }
2444  } else {
2445  // strAddNode is a name
2446  auto it = mapConnectedByName.find(strAddNode);
2447  if (it != mapConnectedByName.end()) {
2448  addedNode.resolvedAddress = it->second.second;
2449  addedNode.fConnected = true;
2450  addedNode.fInbound = it->second.first;
2451  }
2452  }
2453  ret.emplace_back(std::move(addedNode));
2454  }
2455 
2456  return ret;
2457 }
2458 
2460 {
2461  while (true)
2462  {
2463  CSemaphoreGrant grant(*semAddnode);
2464  std::vector<AddedNodeInfo> vInfo = GetAddedNodeInfo();
2465  bool tried = false;
2466  for (const AddedNodeInfo& info : vInfo) {
2467  if (!info.fConnected) {
2468  if (!grant.TryAcquire()) {
2469  // If we've used up our semaphore and need a new one, lets not wait here since while we are waiting
2470  // the addednodeinfo state might change.
2471  break;
2472  }
2473  tried = true;
2474  CAddress addr(CService(), NODE_NONE);
2475  OpenNetworkConnection(addr, false, &grant, info.strAddedNode.c_str(), false, false, true);
2476  if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
2477  return;
2478  }
2479  }
2480  // Retry every 60 seconds if a connection was attempted, otherwise two seconds
2481  if (!interruptNet.sleep_for(std::chrono::seconds(tried ? 60 : 2)))
2482  return;
2483  }
2484 }
2485 
2487 {
2488  // Connecting to specific addresses, no masternode connections available
2489  if (gArgs.IsArgSet("-connect") && gArgs.GetArgs("-connect").size() > 0)
2490  return;
2491 
2492  auto& chainParams = Params();
2493 
2494  bool didConnect = false;
2495  while (!interruptNet)
2496  {
2497  int sleepTime = 1000;
2498  if (didConnect) {
2499  sleepTime = 100;
2500  }
2501  if (!interruptNet.sleep_for(std::chrono::milliseconds(sleepTime)))
2502  return;
2503 
2504  didConnect = false;
2505 
2507  continue;
2508 
2509  std::set<CService> connectedNodes;
2510  std::map<uint256, bool> connectedProRegTxHashes;
2511  ForEachNode([&](const CNode* pnode) {
2512  connectedNodes.emplace(pnode->addr);
2513  if (!pnode->verifiedProRegTxHash.IsNull()) {
2514  connectedProRegTxHashes.emplace(pnode->verifiedProRegTxHash, pnode->fInbound);
2515  }
2516  });
2517 
2518  auto mnList = deterministicMNManager->GetListAtChainTip();
2519 
2520  if (interruptNet)
2521  return;
2522 
2523  int64_t nANow = GetAdjustedTime();
2524 
2525  // NOTE: Process only one pending masternode at a time
2526 
2527  CDeterministicMNCPtr connectToDmn;
2528  bool isProbe = false;
2529  { // don't hold lock while calling OpenMasternodeConnection as cs_main is locked deep inside
2531 
2532  if (!vPendingMasternodes.empty()) {
2533  auto dmn = mnList.GetValidMN(vPendingMasternodes.front());
2535  if (dmn && !connectedNodes.count(dmn->pdmnState->addr) && !IsMasternodeOrDisconnectRequested(dmn->pdmnState->addr)) {
2536  connectToDmn = dmn;
2537  LogPrint(BCLog::NET_NETCONN, "CConnman::%s -- opening pending masternode connection to %s, service=%s\n", __func__, dmn->proTxHash.ToString(), dmn->pdmnState->addr.ToString(false));
2538  }
2539  }
2540 
2541  if (!connectToDmn) {
2542  std::vector<CDeterministicMNCPtr> pending;
2543  for (const auto& group : masternodeQuorumNodes) {
2544  for (const auto& proRegTxHash : group.second) {
2545  auto dmn = mnList.GetMN(proRegTxHash);
2546  if (!dmn) {
2547  continue;
2548  }
2549  const auto& addr2 = dmn->pdmnState->addr;
2550  if (!connectedNodes.count(addr2) && !IsMasternodeOrDisconnectRequested(addr2) && !connectedProRegTxHashes.count(proRegTxHash)) {
2551  int64_t lastAttempt = mmetaman.GetMetaInfo(dmn->proTxHash)->GetLastOutboundAttempt();
2552  // back off trying connecting to an address if we already tried recently
2553  if (nANow - lastAttempt < chainParams.LLMQConnectionRetryTimeout()) {
2554  continue;
2555  }
2556  pending.emplace_back(dmn);
2557  }
2558  }
2559  }
2560 
2561  if (!pending.empty()) {
2562  connectToDmn = pending[GetRandInt(pending.size())];
2563  LogPrint(BCLog::NET_NETCONN, "CConnman::%s -- opening quorum connection to %s, service=%s\n", __func__, connectToDmn->proTxHash.ToString(), connectToDmn->pdmnState->addr.ToString(false));
2564  }
2565  }
2566 
2567  if (!connectToDmn) {
2568  std::vector<CDeterministicMNCPtr> pending;
2569  for (auto it = masternodePendingProbes.begin(); it != masternodePendingProbes.end(); ) {
2570  auto dmn = mnList.GetMN(*it);
2571  if (!dmn) {
2572  it = masternodePendingProbes.erase(it);
2573  continue;
2574  }
2575  bool connectedAndOutbound = connectedProRegTxHashes.count(dmn->proTxHash) && !connectedProRegTxHashes[dmn->proTxHash];
2576  if (connectedAndOutbound) {
2577  // we already have an outbound connection to this MN so there is no theed to probe it again
2578  mmetaman.GetMetaInfo(dmn->proTxHash)->SetLastOutboundSuccess(nANow);
2579  it = masternodePendingProbes.erase(it);
2580  continue;
2581  }
2582 
2583  ++it;
2584 
2585  int64_t lastAttempt = mmetaman.GetMetaInfo(dmn->proTxHash)->GetLastOutboundAttempt();
2586  // back off trying connecting to an address if we already tried recently
2587  if (nANow - lastAttempt < chainParams.LLMQConnectionRetryTimeout()) {
2588  continue;
2589  }
2590  pending.emplace_back(dmn);
2591  }
2592 
2593  if (!pending.empty()) {
2594  connectToDmn = pending[GetRandInt(pending.size())];
2595  masternodePendingProbes.erase(connectToDmn->proTxHash);
2596  isProbe = true;
2597 
2598  LogPrint(BCLog::NET_NETCONN, "CConnman::%s -- probing masternode %s, service=%s\n", __func__, connectToDmn->proTxHash.ToString(), connectToDmn->pdmnState->addr.ToString(false));
2599  }
2600  }
2601  }
2602 
2603  if (!connectToDmn) {
2604  continue;
2605  }
2606 
2607  didConnect = true;
2608 
2609  mmetaman.GetMetaInfo(connectToDmn->proTxHash)->SetLastOutboundAttempt(nANow);
2610 
2611  OpenMasternodeConnection(CAddress(connectToDmn->pdmnState->addr, NODE_NETWORK), isProbe);
2612  // should be in the list now if connection was opened
2613  bool connected = ForNode(connectToDmn->pdmnState->addr, CConnman::AllNodes, [&](CNode* pnode) {
2614  if (pnode->fDisconnect) {
2615  return false;
2616  }
2617  return true;
2618  });
2619  if (!connected) {
2620  LogPrint(BCLog::NET_NETCONN, "CConnman::%s -- connection failed for masternode %s, service=%s\n", __func__, connectToDmn->proTxHash.ToString(), connectToDmn->pdmnState->addr.ToString(false));
2621  // reset last outbound success
2622  mmetaman.GetMetaInfo(connectToDmn->proTxHash)->SetLastOutboundSuccess(0);
2623  }
2624  }
2625 }
2626 
2627 // if successful, this moves the passed grant to the constructed node
2628 void CConnman::OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *pszDest, bool fOneShot, bool fFeeler, bool manual_connection, bool fConnectToMasternode, bool fMasternodeProbe)
2629 {
2630  //
2631  // Initiate outbound network connection
2632  //
2633  if (interruptNet) {
2634  return;
2635  }
2636  if (!fNetworkActive) {
2637  return;
2638  }
2639  if (!pszDest) {
2640  // banned or exact match?
2641  if (IsBanned(addrConnect) || FindNode(addrConnect.ToStringIPPort()))
2642  return;
2643  // local and not a connection to itself?
2644  bool fAllowLocal = Params().AllowMultiplePorts() && addrConnect.GetPort() != GetListenPort();
2645  if (!fAllowLocal && IsLocal(addrConnect))
2646  return;
2647  // if multiple ports for same IP are allowed, search for IP:PORT match, otherwise search for IP-only match
2648  if ((!Params().AllowMultiplePorts() && FindNode((CNetAddr)addrConnect)) ||
2649  (Params().AllowMultiplePorts() && FindNode((CService)addrConnect)))
2650  return;
2651  } else if (FindNode(std::string(pszDest)))
2652  return;
2653 
2654  auto getIpStr = [&]() {
2655  if (fLogIPs) {
2656  return addrConnect.ToString(false);
2657  } else {
2658  return std::string("new peer");
2659  }
2660  };
2661 
2662  LogPrint(BCLog::NET_NETCONN, "CConnman::%s -- connecting to %s\n", __func__, getIpStr());
2663  CNode* pnode = ConnectNode(addrConnect, pszDest, fCountFailure);
2664 
2665  if (!pnode) {
2666  LogPrint(BCLog::NET_NETCONN, "CConnman::%s -- ConnectNode failed for %s\n", __func__, getIpStr());
2667  return;
2668  }
2669  LogPrint(BCLog::NET_NETCONN, "CConnman::%s -- succesfully connected to %s, sock=%d, peer=%d\n", __func__, getIpStr(), pnode->hSocket, pnode->GetId());
2670  if (grantOutbound)
2671  grantOutbound->MoveTo(pnode->grantOutbound);
2672  if (fOneShot)
2673  pnode->fOneShot = true;
2674  if (fFeeler)
2675  pnode->fFeeler = true;
2676  if (manual_connection)
2677  pnode->m_manual_connection = true;
2678  if (fConnectToMasternode)
2679  pnode->fMasternode = true;
2680  if (fMasternodeProbe)
2681  pnode->fMasternodeProbe = true;
2682 
2683  {
2684  LOCK(cs_vNodes);
2685  mapSocketToNode.emplace(pnode->hSocket, pnode);
2686  }
2687 
2688  m_msgproc->InitializeNode(pnode);
2689  {
2690  LOCK(cs_vNodes);
2691  vNodes.push_back(pnode);
2692  RegisterEvents(pnode);
2693  WakeSelect();
2694  }
2695 }
2696 
2697 void CConnman::OpenMasternodeConnection(const CAddress &addrConnect, bool probe) {
2698  OpenNetworkConnection(addrConnect, false, nullptr, nullptr, false, false, false, true, probe);
2699 }
2700 
2702 {
2703  int64_t nLastSendMessagesTimeMasternodes = 0;
2704 
2705  while (!flagInterruptMsgProc)
2706  {
2707  std::vector<CNode*> vNodesCopy = CopyNodeVector();
2708 
2709  bool fMoreWork = false;
2710 
2711  bool fSkipSendMessagesForMasternodes = true;
2712  if (GetTimeMillis() - nLastSendMessagesTimeMasternodes >= 100) {
2713  fSkipSendMessagesForMasternodes = false;
2714  nLastSendMessagesTimeMasternodes = GetTimeMillis();
2715  }
2716 
2717  for (CNode* pnode : vNodesCopy)
2718  {
2719  if (pnode->fDisconnect)
2720  continue;
2721 
2722  // Receive messages
2723  bool fMoreNodeWork = m_msgproc->ProcessMessages(pnode, flagInterruptMsgProc);
2724  fMoreWork |= (fMoreNodeWork && !pnode->fPauseSend);
2726  return;
2727  // Send messages
2728  if (!fSkipSendMessagesForMasternodes || !pnode->fMasternode) {
2729  LOCK(pnode->cs_sendProcessing);
2731  }
2732 
2734  return;
2735  }
2736 
2737  ReleaseNodeVector(vNodesCopy);
2738 
2739  std::unique_lock<std::mutex> lock(mutexMsgProc);
2740  if (!fMoreWork) {
2741  condMsgProc.wait_until(lock, std::chrono::steady_clock::now() + std::chrono::milliseconds(100), [this] { return fMsgProcWake; });
2742  }
2743  fMsgProcWake = false;
2744  }
2745 }
2746 
2747 
2748 
2749 
2750 
2751 
2752 bool CConnman::BindListenPort(const CService &addrBind, std::string& strError, bool fWhitelisted)
2753 {
2754  strError = "";
2755  int nOne = 1;
2756 
2757  // Create socket for listening for incoming connections
2758  struct sockaddr_storage sockaddr;
2759  socklen_t len = sizeof(sockaddr);
2760  if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
2761  {
2762  strError = strprintf("Error: Bind address family for %s not supported", addrBind.ToString());
2763  LogPrintf("%s\n", strError);
2764  return false;
2765  }
2766 
2767  SOCKET hListenSocket = CreateSocket(addrBind);
2768  if (hListenSocket == INVALID_SOCKET)
2769  {
2770  strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError()));
2771  LogPrintf("%s\n", strError);
2772  return false;
2773  }
2774 
2775  // Allow binding if the port is still in TIME_WAIT state after
2776  // the program was closed and restarted.
2777  setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (sockopt_arg_type)&nOne, sizeof(int));
2778 
2779  // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
2780  // and enable it by default or not. Try to enable it, if possible.
2781  if (addrBind.IsIPv6()) {
2782 #ifdef IPV6_V6ONLY
2783  setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (sockopt_arg_type)&nOne, sizeof(int));
2784 #endif
2785 #ifdef WIN32
2786  int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED;
2787  setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, (const char*)&nProtLevel, sizeof(int));
2788 #endif
2789  }
2790 
2791  if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
2792  {
2793  int nErr = WSAGetLastError();
2794  if (nErr == WSAEADDRINUSE)
2795  strError = strprintf(_("Unable to bind to %s on this computer. %s is probably already running."), addrBind.ToString(), _(PACKAGE_NAME));
2796  else
2797  strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToString(), NetworkErrorString(nErr));
2798  LogPrintf("%s\n", strError);
2799  CloseSocket(hListenSocket);
2800  return false;
2801  }
2802  LogPrintf("Bound to %s\n", addrBind.ToString());
2803 
2804  // Listen for incoming connections
2805  if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
2806  {
2807  strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError()));
2808  LogPrintf("%s\n", strError);
2809  CloseSocket(hListenSocket);
2810  return false;
2811  }
2812 
2813 #ifdef USE_EPOLL
2815  epoll_event event;
2816  event.data.fd = hListenSocket;
2817  event.events = EPOLLIN;
2818  if (epoll_ctl(epollfd, EPOLL_CTL_ADD, hListenSocket, &event) != 0) {
2819  strError = strprintf(_("Error: failed to add socket to epollfd (epoll_ctl returned error %s)"), NetworkErrorString(WSAGetLastError()));
2820  LogPrintf("%s\n", strError);
2821  CloseSocket(hListenSocket);
2822  return false;
2823  }
2824  }
2825 #endif
2826 
2827  vhListenSocket.push_back(ListenSocket(hListenSocket, fWhitelisted));
2828 
2829  if (addrBind.IsRoutable() && fDiscover && !fWhitelisted)
2830  AddLocal(addrBind, LOCAL_BIND);
2831 
2832  return true;
2833 }
2834 
2835 void Discover(boost::thread_group& threadGroup)
2836 {
2837  if (!fDiscover)
2838  return;
2839 
2840 #ifdef WIN32
2841  // Get local host IP
2842  char pszHostName[256] = "";
2843  if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
2844  {
2845  std::vector<CNetAddr> vaddr;
2846  if (LookupHost(pszHostName, vaddr, 0, true))
2847  {
2848  for (const CNetAddr &addr : vaddr)
2849  {
2850  if (AddLocal(addr, LOCAL_IF))
2851  LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToString());
2852  }
2853  }
2854  }
2855 #else
2856  // Get local host ip
2857  struct ifaddrs* myaddrs;
2858  if (getifaddrs(&myaddrs) == 0)
2859  {
2860  for (struct ifaddrs* ifa = myaddrs; ifa != nullptr; ifa = ifa->ifa_next)
2861  {
2862  if (ifa->ifa_addr == nullptr) continue;
2863  if ((ifa->ifa_flags & IFF_UP) == 0) continue;
2864  if (strcmp(ifa->ifa_name, "lo") == 0) continue;
2865  if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
2866  if (ifa->ifa_addr->sa_family == AF_INET)
2867  {
2868  struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
2869  CNetAddr addr(s4->sin_addr);
2870  if (AddLocal(addr, LOCAL_IF))
2871  LogPrintf("%s: IPv4 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
2872  }
2873  else if (ifa->ifa_addr->sa_family == AF_INET6)
2874  {
2875  struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
2876  CNetAddr addr(s6->sin6_addr);
2877  if (AddLocal(addr, LOCAL_IF))
2878  LogPrintf("%s: IPv6 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
2879  }
2880  }
2881  freeifaddrs(myaddrs);
2882  }
2883 #endif
2884 }
2885 
2887 {
2888  LogPrint(BCLog::NET, "SetNetworkActive: %s\n", active);
2889 
2890  if (fNetworkActive == active) {
2891  return;
2892  }
2893 
2894  fNetworkActive = active;
2895 
2896  // Always call the Reset() if the network gets enabled/disabled to make sure the sync process
2897  // gets a reset if its outdated..
2899 
2901 }
2902 
2903 CConnman::CConnman(uint64_t nSeed0In, uint64_t nSeed1In) :
2904  addrman(Params().AllowMultiplePorts()),
2905  nSeed0(nSeed0In), nSeed1(nSeed1In)
2906 {
2907  fNetworkActive = true;
2908  setBannedIsDirty = false;
2909  fAddressesInitialized = false;
2910  nLastNodeId = 0;
2911  nPrevNodeCount = 0;
2912  nSendBufferMaxSize = 0;
2913  nReceiveFloodSize = 0;
2914  flagInterruptMsgProc = false;
2915  SetTryNewOutboundPeer(false);
2916 
2917  Options connOptions;
2918  Init(connOptions);
2919 }
2920 
2922 {
2923  return nLastNodeId.fetch_add(1, std::memory_order_relaxed);
2924 }
2925 
2926 
2927 bool CConnman::Bind(const CService &addr, unsigned int flags) {
2928  if (!(flags & BF_EXPLICIT) && IsLimited(addr))
2929  return false;
2930  std::string strError;
2931  if (!BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) {
2932  if ((flags & BF_REPORT_ERROR) && clientInterface) {
2934  }
2935  return false;
2936  }
2937  return true;
2938 }
2939 
2940 bool CConnman::InitBinds(const std::vector<CService>& binds, const std::vector<CService>& whiteBinds) {
2941  bool fBound = false;
2942  for (const auto& addrBind : binds) {
2943  fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
2944  }
2945  for (const auto& addrBind : whiteBinds) {
2946  fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
2947  }
2948  if (binds.empty() && whiteBinds.empty()) {
2949  struct in_addr inaddr_any;
2950  inaddr_any.s_addr = INADDR_ANY;
2951  fBound |= Bind(CService((in6_addr)IN6ADDR_ANY_INIT, GetListenPort()), BF_NONE);
2952  fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
2953  }
2954  return fBound;
2955 }
2956 
2957 bool CConnman::Start(CScheduler& scheduler, const Options& connOptions)
2958 {
2959  Init(connOptions);
2960 
2961  {
2963  nTotalBytesRecv = 0;
2964  }
2965  {
2967  nTotalBytesSent = 0;
2968  nMaxOutboundTotalBytesSentInCycle = 0;
2969  nMaxOutboundCycleStartTime = 0;
2970  }
2971 
2972 #ifdef USE_EPOLL
2974  epollfd = epoll_create1(0);
2975  if (epollfd == -1) {
2976  LogPrintf("epoll_create1 failed\n");
2977  return false;
2978  }
2979  }
2980 #endif
2981 
2982  if (fListen && !InitBinds(connOptions.vBinds, connOptions.vWhiteBinds)) {
2983  if (clientInterface) {
2985  _("Failed to listen on any port. Use -listen=0 if you want this."),
2987  }
2988  return false;
2989  }
2990 
2991  for (const auto& strDest : connOptions.vSeedNodes) {
2992  AddOneShot(strDest);
2993  }
2994 
2995  if (clientInterface) {
2996  clientInterface->InitMessage(_("Loading P2P addresses..."));
2997  }
2998  // Load addresses from peers.dat
2999  int64_t nStart = GetTimeMillis();
3000  {
3001  CAddrDB adb;
3002  if (adb.Read(addrman))
3003  LogPrintf("Loaded %i addresses from peers.dat %dms\n", addrman.size(), GetTimeMillis() - nStart);
3004  else {
3005  addrman.Clear(); // Addrman can be in an inconsistent state after failure, reset it
3006  LogPrintf("Invalid or missing peers.dat; recreating\n");
3007  DumpAddresses();
3008  }
3009  }
3010  if (clientInterface)
3011  clientInterface->InitMessage(_("Loading banlist..."));
3012  // Load addresses from banlist.dat
3013  nStart = GetTimeMillis();
3014  CBanDB bandb;
3015  banmap_t banmap;
3016  if (bandb.Read(banmap)) {
3017  SetBanned(banmap); // thread save setter
3018  SetBannedSetDirty(false); // no need to write down, just read data
3019  SweepBanned(); // sweep out unused entries
3020 
3021  LogPrint(BCLog::NET, "Loaded %d banned node ips/subnets from banlist.dat %dms\n",
3022  banmap.size(), GetTimeMillis() - nStart);
3023  } else {
3024  LogPrintf("Invalid or missing banlist.dat; recreating\n");
3025  SetBannedSetDirty(true); // force write
3026  DumpBanlist();
3027  }
3028 
3029  uiInterface.InitMessage(_("Starting network threads..."));
3030 
3031  fAddressesInitialized = true;
3032 
3033  if (semOutbound == nullptr) {
3034  // initialize semaphore
3035  semOutbound = MakeUnique<CSemaphore>(std::min((nMaxOutbound + nMaxFeeler), nMaxConnections));
3036  }
3037  if (semAddnode == nullptr) {
3038  // initialize semaphore
3039  semAddnode = MakeUnique<CSemaphore>(nMaxAddnode);
3040  }
3041 
3042  //
3043  // Start threads
3044  //
3045  assert(m_msgproc);
3046  InterruptSocks5(false);
3047  interruptNet.reset();
3048  flagInterruptMsgProc = false;
3049 
3050  {
3051  std::unique_lock<std::mutex> lock(mutexMsgProc);
3052  fMsgProcWake = false;
3053  }
3054 
3055 #ifdef USE_WAKEUP_PIPE
3056  if (pipe(wakeupPipe) != 0) {
3057  wakeupPipe[0] = wakeupPipe[1] = -1;
3058  LogPrint(BCLog::NET, "pipe() for wakeupPipe failed\n");
3059  } else {
3060  int fFlags = fcntl(wakeupPipe[0], F_GETFL, 0);
3061  if (fcntl(wakeupPipe[0], F_SETFL, fFlags | O_NONBLOCK) == -1) {
3062  LogPrint(BCLog::NET, "fcntl for O_NONBLOCK on wakeupPipe failed\n");
3063  }
3064  fFlags = fcntl(wakeupPipe[1], F_GETFL, 0);
3065  if (fcntl(wakeupPipe[1], F_SETFL, fFlags | O_NONBLOCK) == -1) {
3066  LogPrint(BCLog::NET, "fcntl for O_NONBLOCK on wakeupPipe failed\n");
3067  }
3068 #ifdef USE_EPOLL
3070  epoll_event event;
3071  event.events = EPOLLIN;
3072  event.data.fd = wakeupPipe[0];
3073  int r = epoll_ctl(epollfd, EPOLL_CTL_ADD, wakeupPipe[0], &event);
3074  if (r != 0) {
3075  LogPrint(BCLog::NET, "%s -- epoll_ctl(%d, %d, %d, ...) failed. error: %s\n", __func__,
3076  epollfd, EPOLL_CTL_ADD, wakeupPipe[0], NetworkErrorString(WSAGetLastError()));
3077  return false;
3078  }
3079  }
3080 #endif
3081  }
3082 #endif
3083 
3084  // Send and receive from sockets, accept connections
3085  threadSocketHandler = std::thread(&TraceThread<std::function<void()> >, "net", std::function<void()>(std::bind(&CConnman::ThreadSocketHandler, this)));
3086 
3087  if (!gArgs.GetBoolArg("-dnsseed", true))
3088  LogPrintf("DNS seeding disabled\n");
3089  else
3090  threadDNSAddressSeed = std::thread(&TraceThread<std::function<void()> >, "dnsseed", std::function<void()>(std::bind(&CConnman::ThreadDNSAddressSeed, this)));
3091 
3092  // Initiate outbound connections from -addnode
3093  threadOpenAddedConnections = std::thread(&TraceThread<std::function<void()> >, "addcon", std::function<void()>(std::bind(&CConnman::ThreadOpenAddedConnections, this)));
3094 
3095  if (connOptions.m_use_addrman_outgoing && !connOptions.m_specified_outgoing.empty()) {
3096  if (clientInterface) {
3098  _("Cannot provide specific connections and have addrman find outgoing connections at the same."),
3100  }
3101  return false;
3102  }
3103  if (connOptions.m_use_addrman_outgoing || !connOptions.m_specified_outgoing.empty())
3104  threadOpenConnections = std::thread(&TraceThread<std::function<void()> >, "opencon", std::function<void()>(std::bind(&CConnman::ThreadOpenConnections, this, connOptions.m_specified_outgoing)));
3105 
3106  // Initiate masternode connections
3107  threadOpenMasternodeConnections = std::thread(&TraceThread<std::function<void()> >, "mncon", std::function<void()>(std::bind(&CConnman::ThreadOpenMasternodeConnections, this)));
3108 
3109  // Process messages
3110  threadMessageHandler = std::thread(&TraceThread<std::function<void()> >, "msghand", std::function<void()>(std::bind(&CConnman::ThreadMessageHandler, this)));
3111 
3112  // Dump network addresses
3114 
3115  return true;
3116 }
3117 
3119 {
3120 public:
3122 
3124  {
3125 #ifdef WIN32
3126  // Shutdown Windows Sockets
3127  WSACleanup();
3128 #endif
3129  }
3130 }
3132 
3134 {
3135  // Explicit call to destructor of CNetCleanup because it's not implicitly called
3136  // when the wallet is restarted from within the wallet itself.
3137  CNetCleanup *tmp = new CNetCleanup();
3138  delete tmp; // Stroustrup's gonna kill me for that
3139 }
3140 
3142 {
3143  {
3144  std::lock_guard<std::mutex> lock(mutexMsgProc);
3145  flagInterruptMsgProc = true;
3146  }
3147  condMsgProc.notify_all();
3148 
3149  interruptNet();
3150  InterruptSocks5(true);
3151 
3152  if (semOutbound) {
3153  for (int i=0; i<(nMaxOutbound + nMaxFeeler); i++) {
3154  semOutbound->post();
3155  }
3156  }
3157 
3158  if (semAddnode) {
3159  for (int i=0; i<nMaxAddnode; i++) {
3160  semAddnode->post();
3161  }
3162  }
3163 }
3164 
3166 {
3167  if (threadMessageHandler.joinable())
3168  threadMessageHandler.join();
3169  if (threadOpenMasternodeConnections.joinable())
3171  if (threadOpenConnections.joinable())
3172  threadOpenConnections.join();
3173  if (threadOpenAddedConnections.joinable())
3175  if (threadDNSAddressSeed.joinable())
3176  threadDNSAddressSeed.join();
3177  if (threadSocketHandler.joinable())
3178  threadSocketHandler.join();
3179 
3181  {
3182  DumpData();
3183  fAddressesInitialized = false;
3184  }
3185 
3186  {
3187  LOCK(cs_vNodes);
3188 
3189  // Close sockets
3190  for (CNode *pnode : vNodes)
3191  pnode->CloseSocketDisconnect(this);
3192  }
3193  for (ListenSocket& hListenSocket : vhListenSocket)
3194  if (hListenSocket.socket != INVALID_SOCKET) {
3195 #ifdef USE_EPOLL
3197  epoll_ctl(epollfd, EPOLL_CTL_DEL, hListenSocket.socket, nullptr);
3198  }
3199 #endif
3200  if (!CloseSocket(hListenSocket.socket))
3201  LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError()));
3202  }
3203 
3204  // clean up some globals (to help leak detection)
3205  for (CNode *pnode : vNodes) {
3206  DeleteNode(pnode);
3207  }
3208  for (CNode *pnode : vNodesDisconnected) {
3209  DeleteNode(pnode);
3210  }
3211  vNodes.clear();
3212  mapSocketToNode.clear();
3213  mapReceivableNodes.clear();
3214  {
3216  mapNodesWithDataToSend.clear();
3217  }
3218  vNodesDisconnected.clear();
3219  vhListenSocket.clear();
3220  semOutbound.reset();
3221  semAddnode.reset();
3222 
3223 #ifdef USE_EPOLL
3224  if (socketEventsMode == SOCKETEVENTS_EPOLL && epollfd != -1) {
3225 #ifdef USE_WAKEUP_PIPE
3226  epoll_ctl(epollfd, EPOLL_CTL_DEL, wakeupPipe[0], nullptr);
3227 #endif
3228  close(epollfd);
3229  }
3230  epollfd = -1;
3231 #endif
3232 
3233 #ifdef USE_WAKEUP_PIPE
3234  if (wakeupPipe[0] != -1) close(wakeupPipe[0]);
3235  if (wakeupPipe[1] != -1) close(wakeupPipe[1]);
3236  wakeupPipe[0] = wakeupPipe[1] = -1;
3237 #endif
3238 }
3239 
3241 {
3242  assert(pnode);
3243  bool fUpdateConnectionTime = false;
3244  m_msgproc->FinalizeNode(pnode->GetId(), fUpdateConnectionTime);
3245  if(fUpdateConnectionTime) {
3246  addrman.Connected(pnode->addr);
3247  }
3248  delete pnode;
3249 }
3250 
3252 {
3253  Interrupt();
3254  Stop();
3255 }
3256 
3258 {
3259  return addrman.size();
3260 }
3261 
3262 void CConnman::SetServices(const CService &addr, ServiceFlags nServices)
3263 {
3264  addrman.SetServices(addr, nServices);
3265 }
3266 
3268 {
3269  addrman.Good(addr);
3270 }
3271 
3272 void CConnman::AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty)
3273 {
3274  addrman.Add(vAddr, addrFrom, nTimePenalty);
3275 }
3276 
3277 std::vector<CAddress> CConnman::GetAddresses()
3278 {
3279  return addrman.GetAddr();
3280 }
3281 
3282 bool CConnman::AddNode(const std::string& strNode)
3283 {
3285  for (const std::string& it : vAddedNodes) {
3286  if (strNode == it) return false;
3287  }
3288 
3289  vAddedNodes.push_back(strNode);
3290  return true;
3291 }
3292 
3293 bool CConnman::RemoveAddedNode(const std::string& strNode)
3294 {
3296  for(std::vector<std::string>::iterator it = vAddedNodes.begin(); it != vAddedNodes.end(); ++it) {
3297  if (strNode == *it) {
3298  vAddedNodes.erase(it);
3299  return true;
3300  }
3301  }
3302  return false;
3303 }
3304 
3306 {
3308  if (std::find(vPendingMasternodes.begin(), vPendingMasternodes.end(), proTxHash) != vPendingMasternodes.end()) {
3309  return false;
3310  }
3311 
3312  vPendingMasternodes.push_back(proTxHash);
3313  return true;
3314 }
3315 
3316 void CConnman::SetMasternodeQuorumNodes(Consensus::LLMQType llmqType, const uint256& quorumHash, const std::set<uint256>& proTxHashes)
3317 {
3319  auto it = masternodeQuorumNodes.emplace(std::make_pair(llmqType, quorumHash), proTxHashes);
3320  if (!it.second) {
3321  it.first->second = proTxHashes;
3322  }
3323 }
3324 
3326 {
3328  return masternodeQuorumNodes.count(std::make_pair(llmqType, quorumHash));
3329 }
3330 
3332 {
3334  std::set<uint256> result;
3335  for (const auto& p : masternodeQuorumNodes) {
3336  if (p.first.first != llmqType) {
3337  continue;
3338  }
3339  result.emplace(p.first.second);
3340  }
3341  return result;
3342 }
3343 
3344 std::set<NodeId> CConnman::GetMasternodeQuorumNodes(Consensus::LLMQType llmqType, const uint256& quorumHash) const
3345 {
3347  auto it = masternodeQuorumNodes.find(std::make_pair(llmqType, quorumHash));
3348  if (it == masternodeQuorumNodes.end()) {
3349  return {};
3350  }
3351  const auto& proRegTxHashes = it->second;
3352 
3353  std::set<NodeId> nodes;
3354  for (const auto pnode : vNodes) {
3355  if (pnode->fDisconnect) {
3356  continue;
3357  }
3358  if (!pnode->qwatch && (pnode->verifiedProRegTxHash.IsNull() || !proRegTxHashes.count(pnode->verifiedProRegTxHash))) {
3359  continue;
3360  }
3361  nodes.emplace(pnode->GetId());
3362  }
3363  return nodes;
3364 }
3365 
3367 {
3369  masternodeQuorumNodes.erase(std::make_pair(llmqType, quorumHash));
3370 }
3371 
3373 {
3374  // Let's see if this is an outgoing connection to an address that is known to be a masternode
3375  // We however only need to know this if the node did not authenticate itself as a MN yet
3376  uint256 assumedProTxHash;
3377  if (pnode->verifiedProRegTxHash.IsNull() && !pnode->fInbound) {
3378  auto mnList = deterministicMNManager->GetListAtChainTip();
3379  auto dmn = mnList.GetMNByService(pnode->addr);
3380  if (dmn == nullptr) {
3381  // This is definitely not a masternode
3382  return false;
3383  }
3384  assumedProTxHash = dmn->proTxHash;
3385  }
3386 
3388  for (const auto& p : masternodeQuorumNodes) {
3389  if (!pnode->verifiedProRegTxHash.IsNull()) {
3390  if (p.second.count(pnode->verifiedProRegTxHash)) {
3391  return true;
3392  }
3393  } else if (!assumedProTxHash.IsNull()) {
3394  if (p.second.count(assumedProTxHash)) {
3395  return true;
3396  }
3397  }
3398  }
3399  return false;
3400 }
3401 
3402 void CConnman::AddPendingProbeConnections(const std::set<uint256> &proTxHashes)
3403 {
3405  masternodePendingProbes.insert(proTxHashes.begin(), proTxHashes.end());
3406 }
3407 
3409 {
3410  LOCK(cs_vNodes);
3411 
3412  int nNum = 0;
3413  for (const auto& pnode : vNodes) {
3414  if (pnode->fDisconnect) {
3415  continue;
3416  }
3417  if (flags & (pnode->fInbound ? CONNECTIONS_IN : CONNECTIONS_OUT)) {
3418  nNum++;
3419  }
3420  }
3421 
3422  return nNum;
3423 }
3424 
3426 {
3427  return nMaxOutbound;
3428 }
3429 
3430 void CConnman::GetNodeStats(std::vector<CNodeStats>& vstats)
3431 {
3432  vstats.clear();
3433  LOCK(cs_vNodes);
3434  vstats.reserve(vNodes.size());
3435  for (CNode* pnode : vNodes) {
3436  if (pnode->fDisconnect) {
3437  continue;
3438  }
3439  vstats.emplace_back();
3440  pnode->copyStats(vstats.back());
3441  }
3442 }
3443 
3444 bool CConnman::DisconnectNode(const std::string& strNode)
3445 {
3446  LOCK(cs_vNodes);
3447  if (CNode* pnode = FindNode(strNode)) {
3448  pnode->fDisconnect = true;
3449  return true;
3450  }
3451  return false;
3452 }
3454 {
3455  LOCK(cs_vNodes);
3456  for(CNode* pnode : vNodes) {
3457  if (id == pnode->GetId()) {
3458  pnode->fDisconnect = true;
3459  return true;
3460  }
3461  }
3462  return false;
3463 }
3464 
3466 {
3467  uint256 hash = tx.GetHash();
3468  int nInv = MSG_TX;
3469  if (CPrivateSend::GetDSTX(hash)) {
3470  nInv = MSG_DSTX;
3471  }
3472  CInv inv(nInv, hash);
3473  LOCK(cs_vNodes);
3474  for (CNode* pnode : vNodes)
3475  {
3476  if (pnode->fMasternode)
3477  continue;
3478  pnode->PushInventory(inv);
3479  }
3480 }
3481 
3482 void CConnman::RelayInv(CInv &inv, const int minProtoVersion, bool fAllowMasternodeConnections) {
3483  LOCK(cs_vNodes);
3484  for (const auto& pnode : vNodes) {
3485  if (pnode->nVersion < minProtoVersion || (pnode->fMasternode && !fAllowMasternodeConnections))
3486  continue;
3487  pnode->PushInventory(inv);
3488  }
3489 }
3490 
3491 void CConnman::RelayInvFiltered(CInv &inv, const CTransaction& relatedTx, const int minProtoVersion, bool fAllowMasternodeConnections)
3492 {
3493  LOCK(cs_vNodes);
3494  for (const auto& pnode : vNodes) {
3495  if (pnode->nVersion < minProtoVersion || (pnode->fMasternode && !fAllowMasternodeConnections))
3496  continue;
3497  {
3498  LOCK(pnode->cs_filter);
3499  if(pnode->pfilter && !pnode->pfilter->IsRelevantAndUpdate(relatedTx))
3500  continue;
3501  }
3502  pnode->PushInventory(inv);
3503  }
3504 }
3505 
3506 void CConnman::RelayInvFiltered(CInv &inv, const uint256& relatedTxHash, const int minProtoVersion, bool fAllowMasternodeConnections)
3507 {
3508  LOCK(cs_vNodes);
3509  for (const auto& pnode : vNodes) {
3510  if (pnode->nVersion < minProtoVersion || (pnode->fMasternode && !fAllowMasternodeConnections))
3511  continue;
3512  {
3513  LOCK(pnode->cs_filter);
3514  if(pnode->pfilter && !pnode->pfilter->contains(relatedTxHash)) continue;
3515  }
3516  pnode->PushInventory(inv);
3517  }
3518 }
3519 
3520 void CConnman::RecordBytesRecv(uint64_t bytes)
3521 {
3523  nTotalBytesRecv += bytes;
3524 }
3525 
3526 void CConnman::RecordBytesSent(uint64_t bytes)
3527 {
3529  nTotalBytesSent += bytes;
3530 
3531  uint64_t now = GetTime();
3532  if (nMaxOutboundCycleStartTime + nMaxOutboundTimeframe < now)
3533  {
3534  // timeframe expired, reset cycle
3535  nMaxOutboundCycleStartTime = now;
3536  nMaxOutboundTotalBytesSentInCycle = 0;
3537  }
3538 
3539  // TODO, exclude whitebind peers
3540  nMaxOutboundTotalBytesSentInCycle += bytes;
3541 }
3542 
3544 {
3546  nMaxOutboundLimit = limit;
3547 }
3548 
3550 {
3552  return nMaxOutboundLimit;
3553 }
3554 
3556 {
3558  return nMaxOutboundTimeframe;
3559 }
3560 
3562 {
3564  if (nMaxOutboundLimit == 0)
3565  return 0;
3566 
3567  if (nMaxOutboundCycleStartTime == 0)
3568  return nMaxOutboundTimeframe;
3569 
3570  uint64_t cycleEndTime = nMaxOutboundCycleStartTime + nMaxOutboundTimeframe;
3571  uint64_t now = GetTime();
3572  return (cycleEndTime < now) ? 0 : cycleEndTime - GetTime();
3573 }
3574 
3575 void CConnman::SetMaxOutboundTimeframe(uint64_t timeframe)
3576 {
3578  if (nMaxOutboundTimeframe != timeframe)
3579  {
3580  // reset measure-cycle in case of changing
3581  // the timeframe
3582  nMaxOutboundCycleStartTime = GetTime();
3583  }
3584  nMaxOutboundTimeframe = timeframe;
3585 }
3586 
3587 bool CConnman::OutboundTargetReached(bool historicalBlockServingLimit)
3588 {
3590  if (nMaxOutboundLimit == 0)
3591  return false;
3592 
3593  if (historicalBlockServingLimit)
3594  {
3595  // keep a large enough buffer to at least relay each block once
3596  uint64_t timeLeftInCycle = GetMaxOutboundTimeLeftInCycle();
3597  uint64_t buffer = timeLeftInCycle / 600 * MaxBlockSize(fDIP0001ActiveAtTip);
3598  if (buffer >= nMaxOutboundLimit || nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit - buffer)
3599  return true;
3600  }
3601  else if (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit)
3602  return true;
3603 
3604  return false;
3605 }
3606 
3608 {
3610  if (nMaxOutboundLimit == 0)
3611  return 0;
3612 
3613  return (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit) ? 0 : nMaxOutboundLimit - nMaxOutboundTotalBytesSentInCycle;
3614 }
3615 
3617 {
3619  return nTotalBytesRecv;
3620 }
3621 
3623 {
3625  return nTotalBytesSent;
3626 }
3627 
3629 {
3630  return nLocalServices;
3631 }
3632 
3633 void CConnman::SetBestHeight(int height)
3634 {
3635  nBestHeight.store(height, std::memory_order_release);
3636 }
3637 
3639 {
3640  return nBestHeight.load(std::memory_order_acquire);
3641 }
3642 
3643 unsigned int CConnman::GetReceiveFloodSize() const { return nReceiveFloodSize; }
3644 
3645 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) :
3646  nTimeConnected(GetSystemTimeInSeconds()),
3647  nTimeFirstMessageReceived(0),
3648  fFirstMessageIsMNAUTH(false),
3649  addr(addrIn),
3650  addrBind(addrBindIn),
3651  fInbound(fInboundIn),
3652  nKeyedNetGroup(nKeyedNetGroupIn),
3653  addrKnown(5000, 0.001),
3654  filterInventoryKnown(50000, 0.000001),
3655  id(idIn),
3656  nLocalHostNonce(nLocalHostNonceIn),
3657  nLocalServices(nLocalServicesIn),
3658  nMyStartingHeight(nMyStartingHeightIn),
3659  nSendVersion(0)
3660 {
3661  nServices = NODE_NONE;
3662  hSocket = hSocketIn;
3664  nLastSend = 0;
3665  nLastRecv = 0;
3666  nSendBytes = 0;
3667  nRecvBytes = 0;
3668  nTimeOffset = 0;
3669  addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
3670  nVersion = 0;
3671  nNumWarningsSkipped = 0;
3672  nLastWarningTime = 0;
3673  strSubVer = "";
3674  fWhitelisted = false;
3675  fOneShot = false;
3676  m_manual_connection = false;
3677  fClient = false; // set by version message
3678  m_limited_node = false; // set by version message
3679  fFeeler = false;
3680  fSuccessfullyConnected = false;
3681  fDisconnect = false;
3682  nRefCount = 0;
3683  nSendSize = 0;
3684  nSendOffset = 0;
3685  hashContinue = uint256();
3686  nStartingHeight = -1;
3687  filterInventoryKnown.reset();
3688  fSendMempool = false;
3689  fGetAddr = false;
3690  nNextLocalAddrSend = 0;
3691  nNextAddrSend = 0;
3692  fRelayTxes = false;
3693  fSentAddr = false;
3694  pfilter = MakeUnique<CBloomFilter>();
3695  timeLastMempoolReq = 0;
3696  nLastBlockTime = 0;
3697  nLastTXTime = 0;
3698  nPingNonceSent = 0;
3699  nPingUsecStart = 0;
3700  nPingUsecTime = 0;
3701  fPingQueued = false;
3702  fMasternode = false;
3703  fMasternodeProbe = false;
3704  nMinPingUsecTime = std::numeric_limits<int64_t>::max();
3705  fPauseRecv = false;
3706  fPauseSend = false;
3707  fHasRecvData = false;
3708  fCanSendData = false;
3709  nProcessQueueSize = 0;
3710  nSendMsgSize = 0;
3711 
3712  for (const std::string &msg : getAllNetMessageTypes())
3713  mapRecvBytesPerMsgCmd[msg] = 0;
3714  mapRecvBytesPerMsgCmd[NET_MESSAGE_COMMAND_OTHER] = 0;
3715 
3716  if (fLogIPs) {
3717  LogPrint(BCLog::NET, "Added connection to %s peer=%d\n", addrName, id);
3718  } else {
3719  LogPrint(BCLog::NET, "Added connection peer=%d\n", id);
3720  }
3721 }
3722 
3724 {
3725  CloseSocket(hSocket);
3726 }
3727 
3729 {
3730  return pnode && pnode->fSuccessfullyConnected && !pnode->fDisconnect;
3731 }
3732 
3734 {
3735  size_t nMessageSize = msg.data.size();
3736  size_t nTotalSize = nMessageSize + CMessageHeader::HEADER_SIZE;
3737  LogPrint(BCLog::NET, "sending %s (%d bytes) peer=%d\n", SanitizeString(msg.command.c_str()), nMessageSize, pnode->GetId());
3738 
3739  std::vector<unsigned char> serializedHeader;
3740  serializedHeader.reserve(CMessageHeader::HEADER_SIZE);
3741  uint256 hash = Hash(msg.data.data(), msg.data.data() + nMessageSize);
3742  CMessageHeader hdr(Params().MessageStart(), msg.command.c_str(), nMessageSize);
3743  memcpy(hdr.pchChecksum, hash.begin(), CMessageHeader::CHECKSUM_SIZE);
3744 
3745  CVectorWriter{SER_NETWORK, INIT_PROTO_VERSION, serializedHeader, 0, hdr};
3746 
3747  size_t nBytesSent = 0;
3748  {
3749  LOCK(pnode->cs_vSend);
3750  bool hasPendingData = !pnode->vSendMsg.empty();
3751 
3752  //log total amount of bytes per command
3753  pnode->mapSendBytesPerMsgCmd[msg.command] += nTotalSize;
3754  pnode->nSendSize += nTotalSize;
3755 
3756  if (pnode->nSendSize > nSendBufferMaxSize)
3757  pnode->fPauseSend = true;
3758  pnode->vSendMsg.push_back(std::move(serializedHeader));
3759  if (nMessageSize)
3760  pnode->vSendMsg.push_back(std::move(msg.data));
3761  pnode->nSendMsgSize = pnode->vSendMsg.size();
3762 
3763  {
3765  // we're not holding cs_vNodes here, so there is a chance of this node being disconnected shortly before
3766  // we get here. Whoever called PushMessage still has a ref to CNode*, but will later Release() it, so we
3767  // might end up having an entry in mapNodesWithDataToSend that is not in vNodes anymore. We need to
3768  // Add/Release refs when adding/erasing mapNodesWithDataToSend.
3769  if (mapNodesWithDataToSend.emplace(pnode->GetId(), pnode).second) {
3770  pnode->AddRef();
3771  }
3772  }
3773 
3774  // wake up select() call in case there was no pending data before (so it was not selecting this socket for sending)
3775  if (!hasPendingData && wakeupSelectNeeded)
3776  WakeSelect();
3777  }
3778  if (nBytesSent)
3779  RecordBytesSent(nBytesSent);
3780 }
3781 
3782 bool CConnman::ForNode(const CService& addr, std::function<bool(const CNode* pnode)> cond, std::function<bool(CNode* pnode)> func)
3783 {
3784  CNode* found = nullptr;
3785  LOCK(cs_vNodes);
3786  for (auto&& pnode : vNodes) {
3787  if((CService)pnode->addr == addr) {
3788  found = pnode;
3789  break;
3790  }
3791  }
3792  return found != nullptr && cond(found) && func(found);
3793 }
3794 
3795 bool CConnman::ForNode(NodeId id, std::function<bool(const CNode* pnode)> cond, std::function<bool(CNode* pnode)> func)
3796 {
3797  CNode* found = nullptr;
3798  LOCK(cs_vNodes);
3799  for (auto&& pnode : vNodes) {
3800  if(pnode->GetId() == id) {
3801  found = pnode;
3802  break;
3803  }
3804  }
3805  return found != nullptr && cond(found) && func(found);
3806 }
3807 
3809  return ForNode(addr, AllNodes, [](CNode* pnode){
3810  return pnode->fMasternode || pnode->fDisconnect;
3811  });
3812 }
3813 
3814 int64_t CConnman::PoissonNextSendInbound(int64_t now, int average_interval_seconds)
3815 {
3816  if (m_next_send_inv_to_incoming < now) {
3817  // If this function were called from multiple threads simultaneously
3818  // it would possible that both update the next send variable, and return a different result to their caller.
3819  // This is not possible in practice as only the net processing thread invokes this function.
3820  m_next_send_inv_to_incoming = PoissonNextSend(now, average_interval_seconds);
3821  }
3823 }
3824 
3825 int64_t PoissonNextSend(int64_t now, int average_interval_seconds)
3826 {
3827  return now + (int64_t)(log1p(GetRand(1ULL << 48) * -0.0000000000000035527136788 /* -1/2^48 */) * average_interval_seconds * -1000000.0 + 0.5);
3828 }
3829 
3830 std::vector<CNode*> CConnman::CopyNodeVector(std::function<bool(const CNode* pnode)> cond)
3831 {
3832  std::vector<CNode*> vecNodesCopy;
3833  LOCK(cs_vNodes);
3834  vecNodesCopy.reserve(vNodes.size());
3835  for(size_t i = 0; i < vNodes.size(); ++i) {
3836  CNode* pnode = vNodes[i];
3837  if (!cond(pnode))
3838  continue;
3839  pnode->AddRef();
3840  vecNodesCopy.push_back(pnode);
3841  }
3842  return vecNodesCopy;
3843 }
3844 
3845 std::vector<CNode*> CConnman::CopyNodeVector()
3846 {
3847  return CopyNodeVector(AllNodes);
3848 }
3849 
3850 void CConnman::ReleaseNodeVector(const std::vector<CNode*>& vecNodes)
3851 {
3852  for(size_t i = 0; i < vecNodes.size(); ++i) {
3853  CNode* pnode = vecNodes[i];
3854  pnode->Release();
3855  }
3856 }
3857 
3859 {
3860  return CSipHasher(nSeed0, nSeed1).Write(id);
3861 }
3862 
3864 {
3865  std::vector<unsigned char> vchNetGroup(ad.GetGroup());
3866 
3867  return GetDeterministicRandomizer(RANDOMIZER_ID_NETGROUP).Write(vchNetGroup.data(), vchNetGroup.size()).Finalize();
3868 }
3869 
3871 {
3872 #ifdef USE_EPOLL
3874  return;
3875  }
3876 
3877  LOCK(pnode->cs_hSocket);
3878  assert(pnode->hSocket != INVALID_SOCKET);
3879 
3880  epoll_event e;
3881  // We're using edge-triggered mode, so it's important that we drain sockets even if no signals come in
3882  e.events = EPOLLIN | EPOLLOUT | EPOLLET | EPOLLERR | EPOLLHUP;
3883  e.data.fd = pnode->hSocket;
3884 
3885  int r = epoll_ctl(epollfd, EPOLL_CTL_ADD, pnode->hSocket, &e);
3886  if (r != 0) {
3887  LogPrint(BCLog::NET, "%s -- epoll_ctl(%d, %d, %d, ...) failed. error: %s\n", __func__,
3888  epollfd, EPOLL_CTL_ADD, pnode->hSocket, NetworkErrorString(WSAGetLastError()));
3889  }
3890 #endif
3891 }
3892 
3894 {
3895 #ifdef USE_EPOLL
3897  return;
3898  }
3899 
3900  LOCK(pnode->cs_hSocket);
3901  if (pnode->hSocket == INVALID_SOCKET) {
3902  return;
3903  }
3904 
3905  int r = epoll_ctl(epollfd, EPOLL_CTL_DEL, pnode->hSocket, nullptr);
3906  if (r != 0) {
3907  LogPrint(BCLog::NET, "%s -- epoll_ctl(%d, %d, %d, ...) failed. error: %s\n", __func__,
3908  epollfd, EPOLL_CTL_DEL, pnode->hSocket, NetworkErrorString(WSAGetLastError()));
3909  }
3910 #endif
3911 }
const std::vector< std::string > & DNSSeeds() const
Return the list of hostnames to look up for DNS seeds.
Definition: chainparams.h:78
void RegisterEvents(CNode *pnode)
Definition: net.cpp:3870
std::vector< CService > vBinds
Definition: net.h:170
std::atomic< bool > flagInterruptMsgProc
Definition: net.h:603
uint64_t CalculateKeyedNetGroup(const CAddress &ad) const
Definition: net.cpp:3863
#define WSAEINPROGRESS
Definition: compat.h:70
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:3645
int nMaxFeeler
Definition: net.h:590
unsigned short GetPort() const
Definition: netaddress.cpp:512
CNode * FindNode(const CNetAddr &ip, bool fExcludeDisconnecting=true)
Definition: net.cpp:330
bool BannedSetIsDirty()
check is the banlist has unwritten changes
Definition: net.cpp:703
uint256 data_hash
Definition: net.h:758
std::atomic< uint64_t > nPingNonceSent
Definition: net.h:924
void SocketHandler()
Definition: net.cpp:1653
static constexpr const CAllNodes AllNodes
Definition: net.h:225
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: util.cpp:784
OutIter copy(Range &&r, OutIter out)
Definition: algorithm.hpp:168
CCriticalSection cs_addrName
Definition: net.h:965
void MoveTo(CSemaphoreGrant &grant)
Definition: sync.h:261
std::atomic_bool fPauseSend
Definition: net.h:875
Access to the (IP) address database (peers.dat)
Definition: addrdb.h:80
#define WSAEINTR
Definition: compat.h:69
std::vector< uint256 > vPendingMasternodes
Definition: net.h:571
void ThreadOpenAddedConnections()
Definition: net.cpp:2459
bool GetLocal(CService &addr, const CNetAddr *paddrPeer)
Definition: net.cpp:132
bool sleep_for(std::chrono::milliseconds rel_time)
void SetBannedSetDirty(bool dirty=true)
set the "dirty" flag for the banlist
Definition: net.cpp:709
static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH
Maximum length of incoming protocol messages (no message over 3 MiB is currently acceptable).
Definition: net.h:66
CMasternodeSync masternodeSync
#define MSG_DONTWAIT
Definition: net.cpp:69
int GetSendVersion() const
Definition: net.cpp:887
void OpenMasternodeConnection(const CAddress &addrConnect, bool probe=false)
Definition: net.cpp:2697
std::atomic_bool fCanSendData
Definition: net.h:878
void SetBanned(const banmap_t &banmap)
Definition: net.cpp:668
std::atomic< bool > fNetworkActive
Definition: net.h:561
void UnregisterEvents(CNode *pnode)
Definition: net.cpp:3893
bool fMsgProcWake
flag for waking the message processor.
Definition: net.h:599
ServiceFlags
nServices flags
Definition: protocol.h:280
std::string ToString(bool fUseGetnameinfo=true) const
Definition: netaddress.cpp:581
CAddrInfo Select(bool newOnly=false)
Choose an address to connect to.
Definition: addrman.h:567
CCriticalSection cs_filter
Definition: net.h:868
BanReason
Definition: addrdb.h:19
void TraceThread(const std::string name, Callable func)
Definition: util.h:436
void Attempt(const CService &addr, bool fCountFailure, int64_t nTime=GetAdjustedTime())
Mark an entry as connection attempted to.
Definition: addrman.h:556
bool AddLocal(const CService &addr, int nScore)
Definition: net.cpp:236
void MilliSleep(int64_t n)
Definition: utiltime.cpp:75
CConnman(uint64_t seed0, uint64_t seed1)
Definition: net.cpp:2903
void SetMasternodeQuorumNodes(Consensus::LLMQType llmqType, const uint256 &quorumHash, const std::set< uint256 > &proTxHashes)
Definition: net.cpp:3316
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: hash.cpp:102
int GetRandInt(int nMax)
Definition: random.cpp:379
#define TRY_LOCK(cs, name)
Definition: sync.h:180
static bool IsSelectableSocket(const SOCKET &s)
Definition: compat.h:117
std::atomic< int > nBestHeight
Definition: net.h:591
size_t GetAddressCount() const
Definition: net.cpp:3257
void SetIP(const CNetAddr &ip)
Definition: netaddress.cpp:26
void WakeMessageHandler()
Definition: net.cpp:1928
std::set< NodeId > GetMasternodeQuorumNodes(Consensus::LLMQType llmqType, const uint256 &quorumHash) const
Definition: net.cpp:3344
void SetServices(const CService &addr, ServiceFlags nServices)
Definition: net.cpp:3262
void Interrupt()
Definition: net.cpp:3141
int64_t nLastTXTime
Definition: net.cpp:1017
size_t SocketSendData(CNode *pnode)
Definition: net.cpp:956
static const bool DEFAULT_FORCEDNSSEED
Definition: net.h:94
unsigned int MaxBlockSize(bool fDIP0001Active)
Definition: consensus.h:12
void SweepBanned()
clean unused entries (if bantime has expired)
Definition: net.cpp:675
bool ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool &complete)
Definition: net.cpp:820
#define strprintf
Definition: tinyformat.h:1066
mapMsgCmdSize mapSendBytesPerMsgCmd
Definition: net.h:882
#define WSAEADDRINUSE
Definition: compat.h:71
bool IsIPv6() const
Definition: netaddress.cpp:94
CHash256 & Write(const unsigned char *data, size_t len)
Definition: hash.h:47
inv message data
Definition: protocol.h:429
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:101
void resize(size_type n, value_type c=0)
Definition: streams.h:196
bool GetNameProxy(proxyType &nameProxyOut)
Definition: netbase.cpp:573
void CloseSocketDisconnect(CConnman *connman)
Definition: net.cpp:535
boost::signals2::signal< void(bool networkActive)> NotifyNetworkActiveChanged
Network activity state changed.
Definition: ui_interface.h:88
CCriticalSection cs_hSocket
Definition: net.h:813
std::atomic< bool > wakeupSelectNeeded
Definition: net.h:611
size_t GetMaxOutboundNodeCount()
Definition: net.cpp:3425
bool fSendMempool
Definition: net.h:914
CCriticalSection cs_SubVer
Definition: net.h:844
bool GetTryNewOutboundPeer()
Definition: net.cpp:2186
#define FEELER_SLEEP_WINDOW
Definition: net.cpp:61
std::atomic< int64_t > m_next_send_inv_to_incoming
Definition: net.h:637
void SetLimited(enum Network net, bool fLimited)
Make a particular network entirely off-limits (no automatic connects to it)
Definition: net.cpp:276
std::mutex mutexMsgProc
Definition: net.h:602
unsigned int nHdrPos
Definition: net.h:764
CCriticalSection cs_addrLocal
Definition: net.h:970
int nMaxAddnode
Definition: net.h:589
RAII-style semaphore lock.
Definition: sync.h:231
CCriticalSection cs_mnauth
Definition: net.h:938
bool Unban(const CNetAddr &ip)
Definition: net.cpp:642
uint64_t GetMaxOutboundTarget()
Definition: net.cpp:3549
static const int BIP0031_VERSION
BIP 0031, pong message, is enabled for all versions AFTER this one.
Definition: version.h:33
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
Definition: net.cpp:3733
#define MSG_NOSIGNAL
Definition: net.cpp:64
void SetMaxOutboundTimeframe(uint64_t timeframe)
set the timeframe for the max outbound target
Definition: net.cpp:3575
int flags
Definition: dash-tx.cpp:462
bool fDiscover
Definition: net.cpp:112
void GetBanned(banmap_t &banmap)
Definition: net.cpp:660
NetEventsInterface * m_msgproc
Definition: net.h:593
std::atomic< int64_t > nPingUsecStart
Definition: net.h:926
void ClearBanned()
Definition: net.cpp:565
CCriticalSection cs_vNodes
Definition: net.h:578
CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
Definition: net.cpp:180
void scheduleEvery(Function f, int64_t deltaMilliSeconds)
Definition: scheduler.cpp:126
int64_t GetTimeMicros()
Returns the system time (not mockable)
Definition: utiltime.cpp:63
static void EraseLastKElements(std::vector< T > &elements, Comparator comparator, size_t k)
Sort an array by the specified comparator, then erase the last K elements.
Definition: net.cpp:1058
std::shared_ptr< const CDeterministicMN > CDeterministicMNCPtr
CCriticalSection cs_vAddedNodes
Definition: net.h:570
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: util.cpp:824
void SetTryNewOutboundPeer(bool flag)
Definition: net.cpp:2191
unsigned short GetListenPort()
Definition: net.cpp:126
uint32_t nMessageSize
Definition: protocol.h:59
std::string ToString() const
Definition: netaddress.cpp:288
CCriticalSection cs_inventory
Definition: net.h:908
static const uint64_t RANDOMIZER_ID_LOCALHOSTNONCE
Definition: net.cpp:108
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:296
CDataStream hdrbuf
Definition: net.h:762
void ThreadSocketHandler()
Definition: net.cpp:1908
bool fMasternode
Definition: net.h:864
static bool CompareNodeBlockTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition: net.cpp:1038
std::vector< CService > vWhiteBinds
Definition: net.h:170
#define INVALID_SOCKET
Definition: compat.h:73
size_t GetNodeCount(NumConnections num)
Definition: net.cpp:3408
bool Add(const CAddress &addr, const CNetAddr &source, int64_t nTimePenalty=0)
Add a single address.
Definition: addrman.h:518
static boost::thread_group threadGroup
Definition: init.cpp:212
bool IsBlockchainSynced()
std::atomic< int > nStartingHeight
Definition: net.h:887
static CScheduler scheduler
Definition: init.cpp:213
void PushAddress(const CAddress &_addr, FastRandomContext &insecure_rand)
Definition: net.h:1026
std::thread threadOpenMasternodeConnections
Definition: net.h:629
static const int FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes or 120 seconds.
Definition: net.h:60
std::set< uint256 > GetMasternodeQuorums(Consensus::LLMQType llmqType)
Definition: net.cpp:3331
static const int TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:56
unsigned char * begin()
Definition: uint256.h:57
std::unique_ptr< CDeterministicMNManager > deterministicMNManager
bool in_data
Definition: net.h:760
std::atomic< int64_t > timeLastMempoolReq
Definition: net.h:921
void AddOneShot(const std::string &strDest)
Definition: net.cpp:120
static constexpr const CFullyConnectedOnly FullyConnectedOnly
Definition: net.h:219
std::atomic_bool fOtherSideDisconnected
Definition: net.h:856
#define WSAGetLastError()
Definition: compat.h:64
static bool CompareNodeTXTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition: net.cpp:1046
std::list< CNetMessage > vRecvMsg
Definition: net.h:963
std::set< uint256 > masternodePendingProbes
Definition: net.h:573
std::string ToStringIP(bool fUseGetnameinfo=true) const
Definition: netaddress.cpp:261
bool IsNull() const
Definition: uint256.h:33
void NotifyNumConnectionsChanged()
Definition: net.cpp:1388
enum Network GetNetwork() const
Definition: netaddress.cpp:244
void SetMaxOutboundTarget(uint64_t limit)
set the max outbound target in bytes
Definition: net.cpp:3543
void RecordBytesSent(uint64_t bytes)
Definition: net.cpp:3526
CAddrMan addrman
Definition: net.h:566
std::atomic< ServiceFlags > nServices
Definition: net.h:805
void SetAddrLocal(const CService &addrLocalIn)
May not be called more than once.
Definition: net.cpp:741
int nSendVersion
Definition: net.h:962
void AddPendingProbeConnections(const std::set< uint256 > &proTxHashes)
Definition: net.cpp:3402
friend class CNode
Definition: net.h:138
void MapPort(bool)
Definition: net.cpp:2065
uint64_t GetMaxOutboundTimeframe()
Definition: net.cpp:3555
void ForEachNode(const Condition &cond, Callable &&func)
Definition: net.h:288
std::vector< CNode * > CopyNodeVector()
Definition: net.cpp:3845
int GetRefCount() const
Definition: net.h:985
ServiceFlags nLocalServices
Services this instance offers.
Definition: net.h:583
CDataStream vRecv
Definition: net.h:766
void WakeSelect()
Definition: net.cpp:1937
bool IsWhitelistedRange(const CNetAddr &addr)
Definition: net.cpp:716
SocketEventsMode socketEventsMode
Definition: net.h:613
bool IsValid() const
Definition: netaddress.cpp:191
bool DisconnectNode(const std::string &node)
Definition: net.cpp:3444
std::vector< unsigned char > GetGroup() const
Definition: netaddress.cpp:319
CMasternodeMetaMan mmetaman
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: hash.h:41
boost::signals2::signal< void(void)> BannedListChanged
Banlist did change.
Definition: ui_interface.h:117
Definition: net.cpp:85
std::atomic< int64_t > nLastSend
Definition: net.h:826
void RecordBytesRecv(uint64_t bytes)
Definition: net.cpp:3520
virtual bool SendMessages(CNode *pnode, std::atomic< bool > &interrupt)=0
bool HaveNameProxy()
Definition: netbase.cpp:581
void DumpAddresses()
Definition: net.cpp:2152
Access to the banlist database (banlist.dat)
Definition: addrdb.h:92
bool done
bool fSentAddr
Definition: net.h:862
std::vector< CAddress > GetAddr()
Return a bunch of addresses, selected at random.
Definition: addrman.h:580
CHash256 hasher
Definition: net.h:757
std::unordered_map< SOCKET, CNode * > mapSocketToNode
Definition: net.h:577
bool IsMasternodeQuorumNode(const CNode *pnode)
Definition: net.cpp:3372
std::atomic< int64_t > nPingUsecTime
Definition: net.h:928
int64_t GetTime()
Return system time (or mocked time, if set)
Definition: utiltime.cpp:22
bool fMasternodeMode
Definition: util.cpp:93
LLMQType
Definition: params.h:48
false
Definition: bls_dkg.cpp:168
void RemoveMasternodeQuorumNodes(Consensus::LLMQType llmqType, const uint256 &quorumHash)
Definition: net.cpp:3366
std::atomic< int64_t > nMinPingUsecTime
Definition: net.h:930
#define LOCK2(cs1, cs2)
Definition: sync.h:179
void Ban(const CNetAddr &netAddr, const BanReason &reason, int64_t bantimeoffset=0, bool sinceUnixEpoch=false)
Definition: net.cpp:605
Extended statistics about a CAddress.
Definition: addrman.h:24
ServiceFlags GetLocalServices() const
Definition: net.h:1087
#define SOCKET_ERROR
Definition: compat.h:74
static CAddress GetBindAddress(SOCKET sock)
Get the bind address for a socket as CAddress.
Definition: net.cpp:397
std::map< CSubNet, CBanEntry > banmap_t
Definition: addrdb.h:77
bool fClient
Definition: net.h:849
bool ForNode(NodeId id, std::function< bool(const CNode *pnode)> cond, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:3795
bool fRelayTxes
Definition: net.cpp:114
uint64_t GetOutboundTargetBytesLeft()
response the bytes left in the current max outbound cycle
Definition: net.cpp:3607
#define LogPrintf(...)
Definition: util.h:203
bool Write(const CAddrMan &addr)
Definition: addrdb.cpp:127
void Release()
Definition: net.h:1014
size_type size() const
Definition: streams.h:194
static bool NodeFullyConnected(const CNode *pnode)
Definition: net.cpp:3728
unsigned int nPrevNodeCount
Definition: net.h:580
bool ConnectSocketDirectly(const CService &addrConnect, const SOCKET &hSocket, int nTimeout)
Definition: netbase.cpp:482
int GetnScore(const CService &addr)
Definition: net.cpp:192
static const uint64_t RANDOMIZER_ID_NETGROUP
Definition: net.cpp:107
bool AddNode(const std::string &node)
Definition: net.cpp:3282
size_t nProcessQueueSize
Definition: net.h:818
std::condition_variable condMsgProc
Definition: net.h:601
int64_t GetSystemTimeInSeconds()
Returns the system time (not mockable)
Definition: utiltime.cpp:70
CService GetAddrLocal() const
Definition: net.cpp:736
uint64_t GetMaxOutboundTimeLeftInCycle()
response the time in second left in the current max outbound cycle
Definition: net.cpp:3561
void InactivityCheck(CNode *pnode)
Definition: net.cpp:1409
std::atomic< int64_t > nLastRecv
Definition: net.h:827
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition: net.h:596
bool fOneShot
Definition: net.h:847
bool InitBinds(const std::vector< CService > &binds, const std::vector< CService > &whiteBinds)
Definition: net.cpp:2940
static bool HasAllDesirableServiceFlags(ServiceFlags services)
A shortcut for (services & GetDesirableServiceFlags(services)) == GetDesirableServiceFlags(services)...
Definition: protocol.h:345
std::thread threadOpenAddedConnections
Definition: net.h:627
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Definition: netaddress.cpp:527
static CPrivateSendBroadcastTx GetDSTX(const uint256 &hash)
#define LOCK(cs)
Definition: sync.h:178
std::vector< CNode * > vNodes
Definition: net.h:575
ServiceFlags GetLocalServices() const
Definition: net.cpp:3628
const uint256 & GetHash() const
Definition: transaction.h:256
void ThreadOpenMasternodeConnections()
Definition: net.cpp:2486
bool IsPeerAddrLocalGood(CNode *pnode)
Definition: net.cpp:201
static const int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
Definition: version.h:17
CCriticalSection cs_mapLocalHost
Definition: net.cpp:115
void SocketEventsSelect(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set, bool fOnlyPoll)
Definition: net.cpp:1557
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:143
Fast randomness source.
Definition: random.h:48
const CAddress addrBind
Definition: net.h:836
std::vector< std::string > vSeedNodes
Definition: net.h:168
int64_t PoissonNextSendInbound(int64_t now, int average_interval_seconds)
Attempts to obfuscate tx time through exponentially distributed emitting.
Definition: net.cpp:3814
bool OutboundTargetReached(bool historicalBlockServingLimit)
check if the outbound target is reached
Definition: net.cpp:3587
std::vector< std::string > m_specified_outgoing
Definition: net.h:172
void DumpData()
Definition: net.cpp:2163
std::vector< CAddress > GetAddresses()
Definition: net.cpp:3277
void DisconnectNodes()
Definition: net.cpp:1282
void RelayInvFiltered(CInv &inv, const CTransaction &relatedTx, const int minProtoVersion=MIN_PEER_PROTO_VERSION, bool fAllowMasternodeConnections=false)
Definition: net.cpp:3491
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:585
void ThreadOpenConnections(std::vector< std::string > connect)
Definition: net.cpp:2221
std::thread threadMessageHandler
Definition: net.h:630
CMessageHeader hdr
Definition: net.h:763
bool ConnectThroughProxy(const proxyType &proxy, const std::string &strDest, int port, const SOCKET &hSocket, int nTimeout, bool *outProxyConnectionFailed)
Definition: netbase.cpp:595
bool m_manual_connection
Definition: net.h:848
void ProcessOneShot()
Definition: net.cpp:2169
A CService with information about it as peer.
Definition: protocol.h:358
bool Start(CScheduler &scheduler, const Options &options)
Definition: net.cpp:2957
size_t SocketRecvData(CNode *pnode)
Definition: net.cpp:1840
void MaybeSetAddrName(const std::string &addrNameIn)
Sets the addrName only if it was not previously set.
Definition: net.cpp:729
void Release()
Definition: sync.h:246
const std::vector< std::string > & getAllNetMessageTypes()
Definition: protocol.cpp:293
uint64_t GetTotalBytesRecv()
Definition: net.cpp:3616
double dPingTime
Definition: net.h:738
std::string addrName
Definition: net.h:727
std::atomic< bool > fDIP0001ActiveAtTip
Definition: validation.cpp:240
Network
Definition: netaddress.h:21
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:635
int64_t NodeId
Definition: net.h:109
CNetCleanup()
Definition: net.cpp:3121
virtual void FinalizeNode(NodeId id, bool &update_connection_time)=0
Definition: net.h:136
uint256 Hash(const T1 pbegin, const T1 pend)
Compute the 256-bit hash of an object.
Definition: hash.h:84
void SetNetworkActive(bool active)
Definition: net.cpp:2886
void AddNewAddresses(const std::vector< CAddress > &vAddr, const CAddress &addrFrom, int64_t nTimePenalty=0)
Definition: net.cpp:3272
int GetDefaultPort() const
Definition: chainparams.h:56
bool fMasternodeProbe
Definition: net.h:866
NumConnections
Definition: net.h:141
uint64_t Finalize() const
Compute the 64-bit SipHash-2-4 of the data written so far.
Definition: hash.cpp:150
bool fGetAddr
Definition: net.h:892
static constexpr size_t CHECKSUM_SIZE
Definition: protocol.h:34
CClientUIInterface * clientInterface
Definition: net.h:592
NodeId GetId() const
Definition: net.h:973
void GetNodeStats(std::vector< CNodeStats > &vstats)
Definition: net.cpp:3430
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition: net.cpp:3858
size_t nSendOffset
Definition: net.h:808
bool RequireRoutableExternalIP() const
Require addresses specified with "-externalip" parameter to be routable.
Definition: chainparams.h:65
std::atomic_bool fDisconnect
Definition: net.h:853
int nMaxConnections
Definition: net.h:587
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:118
size_t nSendSize
Definition: net.h:807
bool CloseSocket(SOCKET &hSocket)
Close socket and set hSocket to INVALID_SOCKET.
Definition: netbase.cpp:690
int nConnectTimeout
Definition: netbase.cpp:35
std::atomic< int64_t > nLastWarningTime
Definition: net.h:830
#define DUMP_ADDRESSES_INTERVAL
Definition: net.cpp:58
CCriticalSection cs_vOneShots
Definition: net.h:568
bool Write(const banmap_t &banSet)
Definition: addrdb.cpp:112
bool IsRoutable() const
Definition: netaddress.cpp:230
#define WSAEWOULDBLOCK
Definition: compat.h:67
std::string FormatFullVersion()
static const std::string NET_MESSAGE_COMMAND_OTHER
Definition: net.cpp:102
bool IsBanned(CNetAddr ip)
Definition: net.cpp:577
void DumpBanlist()
Definition: net.cpp:515
static bool MayHaveUsefulAddressDB(ServiceFlags services)
Checks if a peer with the given service flags may be capable of having a robust address-storage DB...
Definition: protocol.h:353
int64_t nBanUntil
Definition: addrdb.h:32
CCriticalSection cs_setBanned
Definition: net.h:563
unsigned int GetReceiveFloodSize() const
Definition: net.cpp:3643
int readData(const char *pch, unsigned int nBytes)
Definition: net.cpp:931
static const int INBOUND_EVICTION_PROTECTION_TIME
Eviction protection time for incoming connections.
Definition: net.h:74
~CNode()
Definition: net.cpp:3723
void DeleteNode(CNode *pnode)
Definition: net.cpp:3240
unsigned int SOCKET
Definition: compat.h:62
bool CheckIncomingNonce(uint64_t nonce)
Definition: net.cpp:386
CCriticalSection cs_vPendingMasternodes
Definition: net.h:574
const CAddress addr
Definition: net.h:834
bool AddPendingMasternode(const uint256 &proTxHash)
Definition: net.cpp:3305
std::atomic< int > nRefCount
Definition: net.h:870
boost::signals2::signal< void(int newNumConnections)> NotifyNumConnectionsChanged
Number of network connections changed.
Definition: ui_interface.h:85
bool Match(const CNetAddr &addr) const
Definition: netaddress.cpp:647
const int64_t nTimeConnected
Definition: net.h:828
int64_t nTime
Definition: net.h:769
bool Read(banmap_t &banSet)
Definition: addrdb.cpp:117
#define LogPrint(category,...)
Definition: util.h:214
#define X(name)
Definition: net.cpp:756
std::atomic< NodeId > nLastNodeId
Definition: net.h:579
bool RemoveAddedNode(const std::string &node)
Definition: net.cpp:3293
#define SD_SEND
Definition: compat.h:75
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
Definition: netaddress.h:33
CCriticalSection cs_vRecv
Definition: net.h:814
std::list< CNode * > vNodesDisconnected
Definition: net.h:576
bool fLogIPs
Definition: util.cpp:115
std::atomic< bool > fPingQueued
Definition: net.h:932
size_t size() const
Return the number of (unique) addresses in all tables.
Definition: addrman.h:498
256-bit opaque blob.
Definition: uint256.h:123
CNode * ConnectNode(CAddress addrConnect, const char *pszDest=nullptr, bool fCountFailure=false)
Definition: net.cpp:412
int GetBestHeight() const
Definition: net.cpp:3638
~CNetCleanup()
Definition: net.cpp:3123
bool AllowMultiplePorts() const
Allow nodes with the same address and multiple ports.
Definition: chainparams.h:72
unsigned int nTime
Definition: protocol.h:390
bool IsReachable(enum Network net)
check whether a given network is one we can probably connect to
Definition: net.cpp:316
ArgsManager gArgs
Definition: util.cpp:108
int nScore
Definition: net.h:709
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound=nullptr, const char *strDest=nullptr, bool fOneShot=false, bool fFeeler=false, bool manual_connection=false, bool fConnectToMasternode=false, bool fMasternodeProbe=false)
Definition: net.cpp:2628
ServiceFlags nServices
Definition: protocol.h:387
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:50
void ReleaseNodeVector(const std::vector< CNode *> &vecNodes)
Definition: net.cpp:3850
CService proxy
Definition: netbase.h:37
bool Bind(const CService &addr, unsigned int flags)
Definition: net.cpp:2927
std::string ToString() const
Definition: netaddress.cpp:673
bool fFeeler
Definition: net.h:846
void SplitHostPort(std::string in, int &portOut, std::string &hostOut)
uint256 verifiedProRegTxHash
Definition: net.h:941
std::atomic< int64_t > nLastTXTime
Definition: net.h:918
bool complete() const
Definition: net.h:779
const bool fInbound
Definition: net.h:851
void Clear()
Definition: addrman.h:462
static const uint64_t SELECT_TIMEOUT_MILLISECONDS
Definition: net.cpp:94
uint8_t banReason
Definition: addrdb.h:33
std::vector< CSubNet > vWhitelistedRange
Definition: net.h:555
~CConnman()
Definition: net.cpp:3251
std::thread threadOpenConnections
Definition: net.h:628
bool AttemptToEvictConnection()
Try to find a connection to evict when the node is full.
Definition: net.cpp:1073
static const unsigned int MAX_SIZE
Definition: serialize.h:29
static std::vector< CAddress > convertSeed6(const std::vector< SeedSpec6 > &vSeedsIn)
Convert the pnSeed6 array into usable address objects.
Definition: net.cpp:157
bool RemoveLocal(const CService &addr)
Definition: net.cpp:267
const CChainParams & Params()
Return the currently selected parameters.
CSemaphoreGrant grantOutbound
Definition: net.h:867
bool SetSocketNoDelay(const SOCKET &hSocket)
Set the TCP_NODELAY flag on a socket.
Definition: netbase.cpp:733
std::map< std::pair< Consensus::LLMQType, uint256 >, std::set< uint256 > > masternodeQuorumNodes
Definition: net.h:572
uint256 hashContinue
Definition: net.h:886
void * memcpy(void *a, const void *b, size_t c)
bool fWhitelisted
Definition: net.h:845
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: utiltime.cpp:56
NodeId GetNewNodeId()
Definition: net.cpp:2921
unsigned int nDataPos
Definition: net.h:767
static const unsigned int DEFAULT_MISBEHAVING_BANTIME
Definition: net.h:99
std::string addrLocal
Definition: net.h:742
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: util.cpp:808
bool fAddressesInitialized
Definition: net.h:565
std::thread threadDNSAddressSeed
Definition: net.h:625
int64_t nTimeConnected
Definition: net.cpp:1014
int64_t GetAdjustedTime()
Definition: timedata.cpp:35
ServiceFlags GetDesirableServiceFlags(ServiceFlags services)
Gets the set of service flags which are "desirable" for a given peer.
Definition: protocol.cpp:201
bool Lookup(const char *pszName, std::vector< CService > &vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
Definition: netbase.cpp:140
CCriticalSection cs_vProcessMsg
Definition: net.h:816
void SetSendVersion(int nVersionIn)
Definition: net.cpp:873
std::vector< ListenSocket > vhListenSocket
Definition: net.h:560
void SetBestHeight(int height)
Definition: net.cpp:3633
SOCKET CreateSocket(const CService &addrConnect)
Definition: netbase.cpp:446
double dMinPing
Definition: net.h:740
std::atomic< int64_t > nTimeOffset
Definition: net.h:829
std::string GetLogString() const
Definition: net.cpp:750
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:3825
bool fListen
Definition: net.cpp:113
CCriticalSection cs_totalBytesSent
Definition: net.h:543
std::atomic_bool fSuccessfullyConnected
Definition: net.h:852
SipHash-2-4.
Definition: hash.h:266
void Discover(boost::thread_group &threadGroup)
Definition: net.cpp:2835
void ThreadMessageHandler()
Definition: net.cpp:2701
std::atomic< int64_t > nDisconnectLingerTime
Definition: net.h:854
void RelayInv(CInv &inv, const int minProtoVersion=MIN_PEER_PROTO_VERSION, bool fAllowMasternodeConnections=false)
Definition: net.cpp:3482
std::atomic_bool fHasRecvData
Definition: net.h:877
bool error(const char *fmt, const Args &... args)
Definition: util.h:222
std::atomic< int > nVersion
Definition: net.h:838
bool fRelayTxes
Definition: net.h:861
std::string ToStringIPPort(bool fUseGetnameinfo=true) const
Definition: netaddress.cpp:572
int nMaxOutbound
Definition: net.h:588
bool HasMasternodeQuorumNodes(Consensus::LLMQType llmqType, const uint256 &quorumHash)
Definition: net.cpp:3325
bool IsMasternodeOrDisconnectRequested(const CService &addr)
Definition: net.cpp:3808
void InterruptSocks5(bool interrupt)
Definition: netbase.cpp:740
unsigned int nSendBufferMaxSize
Definition: net.h:557
boost::signals2::signal< bool(const std::string &message, const std::string &caption, unsigned int style), boost::signals2::last_value< bool > > ThreadSafeMessageBox
Show message box.
Definition: ui_interface.h:76
int64_t nMinPingUsecTime
Definition: net.cpp:1015
class CNetCleanup instance_of_cnetcleanup
int readHeader(const char *pch, unsigned int nBytes)
Definition: net.cpp:900
static constexpr size_t HEADER_SIZE
Definition: protocol.h:37
bool m_limited_node
Definition: net.h:850
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(cs_mapLocalHost)
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
Definition: netbase.cpp:556
int GetExtraOutboundCount()
Definition: net.cpp:2203
std::atomic_bool fSocketShutdown
Definition: net.h:855
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
Definition: netbase.cpp:672
#define WSAEMSGSIZE
Definition: compat.h:68
BindFlags
Used to pass flags to the Bind() function.
Definition: net.cpp:84
void SetServices(const CService &addr, ServiceFlags nServices)
Definition: addrman.h:601
uint64_t GetTotalBytesSent()
Definition: net.cpp:3622
bool GenerateSelectSet(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set)
Definition: net.cpp:1442
void AcceptConnection(const ListenSocket &hListenSocket)
Definition: net.cpp:1167
CClientUIInterface uiInterface
Definition: ui_interface.cpp:8
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:198
void MarkAddressGood(const CAddress &addr)
Definition: net.cpp:3267
static bool CompareNetGroupKeyed(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition: net.cpp:1034
Information about a peer.
Definition: net.h:800
bool LookupHost(const char *pszName, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
Definition: netbase.cpp:117
bool SetSockAddr(const struct sockaddr *paddr)
Definition: netaddress.cpp:498
std::thread threadSocketHandler
Definition: net.h:626
Definition: net.h:677
static void callCleanup()
Definition: net.cpp:3133
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: util.cpp:765
bool SetInternal(const std::string &name)
Transform an arbitrary string into a non-routable ipv6 address.
Definition: netaddress.cpp:47
Definition: addrdb.h:26
uint64_t nKeyedNetGroup
Definition: net.cpp:1021
virtual void InitializeNode(CNode *pnode)=0
std::string GetAddrName() const
Definition: net.cpp:724
CCriticalSection cs_vSend
Definition: net.h:812
AssertLockHeld(g_cs_orphans)
void RelayTransaction(const CTransaction &tx)
Definition: net.cpp:3465
bool TryAcquire()
Definition: sync.h:254
std::atomic< size_t > nSendMsgSize
Definition: net.h:811
void Connected(const CService &addr, int64_t nTime=GetAdjustedTime())
Mark an entry as currently-connected-to.
Definition: addrman.h:593
void copyStats(CNodeStats &stats)
Definition: net.cpp:757
std::atomic< int > nNumWarningsSkipped
Definition: net.h:837
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
std::atomic_bool fPauseRecv
Definition: net.h:874
CNode * AddRef()
Definition: net.h:1008
std::unique_ptr< CSemaphore > semAddnode
Definition: net.h:586
double dPingWait
Definition: net.h:739
void Init(const Options &connOptions)
Definition: net.h:177
CThreadInterrupt interruptNet
Definition: net.h:605
CCriticalSection cs_totalBytesRecv
Definition: net.h:542
static bool ReverseCompareNodeMinPingTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition: net.cpp:1024
const uint64_t nSeed1
Definition: net.h:596
void Stop()
Definition: net.cpp:3165
bool m_use_addrman_outgoing
Definition: net.h:171
std::atomic< int > nRecvVersion
Definition: net.h:824
std::atomic< int64_t > nLastBlockTime
Definition: net.h:917
CCriticalSection cs_mapNodesWithDataToSend
Definition: net.h:623
CMasternodeMetaInfoPtr GetMetaInfo(const uint256 &proTxHash, bool fCreate=true)
bool Read(CAddrMan &addr)
Definition: addrdb.cpp:132
void AdvertiseLocal(CNode *pnode)
Definition: net.cpp:209
std::vector< AddedNodeInfo > GetAddedNodeInfo()
Definition: net.cpp:2405
bool fNameLookup
Definition: netbase.cpp:36
int64_t nLastBlockTime
Definition: net.cpp:1016
const uint256 & GetMessageHash() const
Definition: net.cpp:948
bool IsLimited(enum Network net)
Definition: net.cpp:284
std::string _(const char *psz)
Translation function: Call Translate signal on UI interface, which returns a boost::optional result...
Definition: util.h:92
void SocketEvents(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set, bool fOnlyPoll)
Definition: net.cpp:1632
virtual bool ProcessMessages(CNode *pnode, std::atomic< bool > &interrupt)=0
Wrapped mutex: supports recursive locking, but no waiting TODO: We should move away from using the re...
Definition: sync.h:94
int64_t nLastTry
last try whatsoever by us (memory only)
Definition: addrman.h:30
boost::signals2::signal< void(const std::string &message)> InitMessage
Progress message during initialization.
Definition: ui_interface.h:82
NodeId nodeid
Definition: net.h:720
int wakeupPipe[2]
a pipe which is added to select() calls to wakeup before the timeout
Definition: net.h:609
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:309
uint64_t GetRand(uint64_t nMax)
Definition: random.cpp:354
unsigned int nReceiveFloodSize
Definition: net.h:558
Message header.
Definition: protocol.h:28
void Good(const CService &addr, int64_t nTime=GetAdjustedTime())
Mark an entry as accessible.
Definition: addrman.h:547
bool BindListenPort(const CService &bindAddr, std::string &strError, bool fWhitelisted=false)
Definition: net.cpp:2752
void ThreadDNSAddressSeed()
Definition: net.cpp:2076
static bool ReverseCompareNodeTimeConnected(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition: net.cpp:1029
void Reset(bool fForce=false, bool fNotifyReset=true)
Released under the MIT license