PIVX Core  5.6.99
P2P Digital Currency
net.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 The Bitcoin developers
3 // Copyright (c) 2014-2015 The Dash developers
4 // Copyright (c) 2015-2022 The PIVX Core developers
5 // Distributed under the MIT/X11 software license, see the accompanying
6 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 
8 #if defined(HAVE_CONFIG_H)
9 #include "config/pivx-config.h"
10 #endif
11 
12 #include "net.h"
13 
14 #include "chainparams.h"
15 #include "clientversion.h"
16 #include "crypto/common.h"
17 #include "crypto/sha256.h"
18 #include "guiinterface.h"
19 #include "netaddress.h"
20 #include "netbase.h"
21 #include "netmessagemaker.h"
22 #include "optional.h"
23 #include "primitives/transaction.h"
24 #include "scheduler.h"
26 
27 #ifdef WIN32
28 #include <string.h>
29 #else
30 #include <fcntl.h>
31 #endif
32 
33 #if HAVE_DECL_GETIFADDRS && HAVE_DECL_FREEIFADDRS
34 #include <ifaddrs.h>
35 #endif
36 
37 #ifdef USE_POLL
38 #include <poll.h>
39 #endif
40 
41 #include <cstdint>
42 #include <unordered_map>
43 
44 #include <math.h>
45 
46 // Dump addresses to peers.dat and banlist.dat every 15 minutes (900s)
47 #define DUMP_ADDRESSES_INTERVAL 900
48 
49 // We add a random period time (0 to 1 seconds) to feeler connections to prevent synchronization.
50 #define FEELER_SLEEP_WINDOW 1
51 
52 #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
53 #define MSG_NOSIGNAL 0
54 #endif
55 
56 // Fix for ancient MinGW versions, that don't have defined these in ws2tcpip.h.
57 // Todo: Can be removed when our pull-tester is upgraded to a modern MinGW version.
58 #ifdef WIN32
59 #ifndef PROTECTION_LEVEL_UNRESTRICTED
60 #define PROTECTION_LEVEL_UNRESTRICTED 10
61 #endif
62 #ifndef IPV6_PROTECTION_LEVEL
63 #define IPV6_PROTECTION_LEVEL 23
64 #endif
65 #endif
66 
68 enum BindFlags {
69  BF_NONE = 0,
70  BF_EXPLICIT = (1U << 0),
71  BF_REPORT_ERROR = (1U << 1),
72  BF_WHITELIST = (1U << 2),
73 };
74 
75 // The set of sockets cannot be modified while waiting
76 // The sleep time needs to be small to avoid new sockets stalling
77 static const uint64_t SELECT_TIMEOUT_MILLISECONDS = 50;
78 
79 const static std::string NET_MESSAGE_COMMAND_OTHER = "*other*";
80 
83 
84 static const uint64_t RANDOMIZER_ID_NETGROUP = 0x6c0edd8036ef4036ULL; // SHA256("netgroup")[0:8]
85 static const uint64_t RANDOMIZER_ID_LOCALHOSTNONCE = 0xd93e69e2bbfa5735ULL; // SHA256("localhostnonce")[0:8]
86 //
87 // Global state variables
88 //
89 bool fDiscover = true;
90 bool fListen = true;
92 std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
93 static bool vfLimited[NET_MAX] = {};
94 std::string strSubVersion;
95 
97 
98 void CConnman::AddOneShot(const std::string& strDest)
99 {
101  vOneShots.push_back(strDest);
102 }
103 
104 uint16_t GetListenPort()
105 {
106  return (uint16_t)(gArgs.GetArg("-port", Params().GetDefaultPort()));
107 }
108 
109 // find 'best' local address for a particular peer
110 bool GetLocal(CService& addr, const CNetAddr* paddrPeer)
111 {
112  if (!fListen)
113  return false;
114 
115  int nBestScore = -1;
116  int nBestReachability = -1;
117  {
119  for (const auto& entry : mapLocalHost) {
120  int nScore = entry.second.nScore;
121  int nReachability = entry.first.GetReachabilityFrom(paddrPeer);
122  if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore)) {
123  addr = CService(entry.first, entry.second.nPort);
124  nBestReachability = nReachability;
125  nBestScore = nScore;
126  }
127  }
128  }
129  return nBestScore >= 0;
130 }
131 
133 static std::vector<CAddress> ConvertSeeds(const std::vector<uint8_t> &vSeedsIn)
134 {
135  // It'll only connect to one or two seed nodes because once it connects,
136  // it'll get a pile of addresses with newer timestamps.
137  // Seed nodes are given a random 'last seen time' of between one and two
138  // weeks ago.
139  const int64_t nOneWeek = 7 * 24 * 60 * 60;
140  std::vector<CAddress> vSeedsOut;
141  FastRandomContext rng;
142  CDataStream s(vSeedsIn, SER_NETWORK, PROTOCOL_VERSION | ADDRV2_FORMAT);
143  while (!s.eof()) {
144  CService endpoint;
145  s >> endpoint;
146  CAddress addr{endpoint, NODE_NETWORK};
147  addr.nTime = GetTime() - rng.randrange(nOneWeek) - nOneWeek;
148  LogPrint(BCLog::NET, "Added hardcoded seed: %s\n", addr.ToString());
149  vSeedsOut.push_back(addr);
150  }
151  return vSeedsOut;
152 }
153 
154 // get best local address for a particular peer as a CAddress
155 // Otherwise, return the unroutable 0.0.0.0 but filled in with
156 // the normal parameters, since the IP may be changed to a useful
157 // one by discovery.
158 CAddress GetLocalAddress(const CNetAddr* paddrPeer, ServiceFlags nLocalServices)
159 {
160  CAddress ret(CService(CNetAddr(), GetListenPort()), nLocalServices);
161  CService addr;
162  if (GetLocal(addr, paddrPeer)) {
163  ret = CAddress(addr, nLocalServices);
164  }
165  ret.nTime = GetAdjustedTime();
166  return ret;
167 }
168 
169 int GetnScore(const CService& addr)
170 {
172  if (mapLocalHost.count(addr) == LOCAL_NONE)
173  return 0;
174  return mapLocalHost[addr].nScore;
175 }
176 
177 // Is our peer's addrLocal potentially useful as an external IP source?
179 {
180  CService addrLocal = pnode->GetAddrLocal();
181  return fDiscover && pnode->addr.IsRoutable() && addrLocal.IsRoutable() &&
182  IsReachable(addrLocal.GetNetwork());
183 }
184 
185 // pushes our own address to a peer
186 void AdvertiseLocal(CNode* pnode)
187 {
188  if (fListen && pnode->fSuccessfullyConnected) {
189  CAddress addrLocal = GetLocalAddress(&pnode->addr, pnode->GetLocalServices());
190  // If discovery is enabled, sometimes give our peer the address it
191  // tells us that it sees us as in case it has a better idea of our
192  // address than we do.
193  FastRandomContext rng;
194  if (IsPeerAddrLocalGood(pnode) && (!addrLocal.IsRoutable() ||
195  rng.randbits((GetnScore(addrLocal) > LOCAL_MANUAL) ? 3 : 1) == 0)) {
196  addrLocal.SetIP(pnode->GetAddrLocal());
197  }
198  if (addrLocal.IsRoutable()) {
199  LogPrintf("%s: advertising address %s\n", __func__, addrLocal.ToString());
200  pnode->PushAddress(addrLocal, rng);
201  }
202  }
203 }
204 
205 // learn a new local address
206 bool AddLocal(const CService& addr, int nScore)
207 {
208  if (!addr.IsRoutable())
209  return false;
210 
211  if (!fDiscover && nScore < LOCAL_MANUAL)
212  return false;
213 
214  if (!IsReachable(addr))
215  return false;
216 
217  LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore);
218 
219  {
221  bool fAlready = mapLocalHost.count(addr) > 0;
222  LocalServiceInfo& info = mapLocalHost[addr];
223  if (!fAlready || nScore >= info.nScore) {
224  info.nScore = nScore + (fAlready ? 1 : 0);
225  info.nPort = addr.GetPort();
226  }
227  }
228 
229  return true;
230 }
231 
232 bool AddLocal(const CNetAddr& addr, int nScore)
233 {
234  return AddLocal(CService(addr, GetListenPort()), nScore);
235 }
236 
237 bool RemoveLocal(const CService& addr)
238 {
240  LogPrintf("RemoveLocal(%s)\n", addr.ToString());
241  mapLocalHost.erase(addr);
242  return true;
243 }
244 
245 void SetReachable(enum Network net, bool reachable)
246 {
247  if (net == NET_UNROUTABLE || net == NET_INTERNAL)
248  return;
250  vfLimited[net] = !reachable;
251 }
252 
253 bool IsReachable(enum Network net)
254 {
256  return !vfLimited[net];
257 }
258 
259 bool IsReachable(const CNetAddr& addr)
260 {
261  return IsReachable(addr.GetNetwork());
262 }
263 
265 bool SeenLocal(const CService& addr)
266 {
267  {
269  if (mapLocalHost.count(addr) == 0)
270  return false;
271  mapLocalHost[addr].nScore++;
272  }
273  return true;
274 }
275 
276 
278 bool IsLocal(const CService& addr)
279 {
281  return mapLocalHost.count(addr) > 0;
282 }
283 
285 {
286  LOCK(cs_vNodes);
287  for (CNode* pnode : vNodes) {
288  if (static_cast<CNetAddr>(pnode->addr) == ip) {
289  return pnode;
290  }
291  }
292  return nullptr;
293 }
294 
296 {
297  LOCK(cs_vNodes);
298  for (CNode* pnode : vNodes) {
299  if (subNet.Match(static_cast<CNetAddr>(pnode->addr))) {
300  return pnode;
301  }
302  }
303  return nullptr;
304 }
305 
306 CNode* CConnman::FindNode(const std::string& addrName)
307 {
308  LOCK(cs_vNodes);
309  for (CNode* pnode : vNodes) {
310  if (pnode->GetAddrName() == addrName) {
311  return pnode;
312  }
313  }
314  return nullptr;
315 }
316 
318 {
319  LOCK(cs_vNodes);
320  const bool isRegTestNet = Params().IsRegTestNet();
321  for (CNode* pnode : vNodes) {
322  if (isRegTestNet) {
323  //if using regtest, just check the IP
324  if (static_cast<CNetAddr>(pnode->addr) == static_cast<CNetAddr>(addr))
325  return pnode;
326  } else {
327  if (pnode->addr == addr)
328  return pnode;
329  }
330  }
331  return nullptr;
332 }
333 
335 {
336  LOCK(cs_vNodes);
337  for(CNode* pnode : vNodes) {
338  if (!pnode->fSuccessfullyConnected && !pnode->fInbound && pnode->GetLocalNonce() == nonce)
339  return false;
340  }
341  return true;
342 }
343 
344 CNode* CConnman::ConnectNode(CAddress addrConnect, const char* pszDest, bool fCountFailure, bool manual_connection)
345 {
346  if (pszDest == nullptr) {
347  if (IsLocal(addrConnect)) {
348  LogPrintf("%s: cannot connect to local node\n", __func__);
349  return nullptr;
350  }
351 
352  // Look for an existing connection
353  CNode* pnode = FindNode(static_cast<CService>(addrConnect));
354  if (pnode) {
355  LogPrintf("Failed to open new connection, already connected\n");
356  return nullptr;
357  }
358  }
359 
361  LogPrint(BCLog::NET, "trying connection %s lastseen=%.1fhrs\n",
362  pszDest ? pszDest : addrConnect.ToString(),
363  pszDest ? 0.0 : (double)(GetAdjustedTime() - addrConnect.nTime) / 3600.0);
364 
365  // Resolve
366  const int default_port = Params().GetDefaultPort();
367  if (pszDest) {
368  std::vector<CService> resolved;
369  if (Lookup(pszDest, resolved, default_port, fNameLookup && !HaveNameProxy(), 256) && !resolved.empty()) {
370  addrConnect = CAddress(resolved[GetRand(resolved.size())], NODE_NONE);
371  if (!addrConnect.IsValid()) {
372  LogPrint(BCLog::NET, "Resolver returned invalid address %s for %s\n", addrConnect.ToString(), pszDest);
373  return nullptr;
374  }
375  }
376  }
377 
378  // Connect
379  bool connected = false;
380  SOCKET hSocket = INVALID_SOCKET;
381  proxyType proxy;
382  if (addrConnect.IsValid()) {
383  bool proxyConnectionFailed = false;
384 
385  if (GetProxy(addrConnect.GetNetwork(), proxy)) {
386  hSocket = CreateSocket(proxy.proxy);
387  if (hSocket == INVALID_SOCKET) {
388  return nullptr;
389  }
390  connected = ConnectThroughProxy(proxy, addrConnect.ToStringIP(), addrConnect.GetPort(), hSocket, nConnectTimeout, &proxyConnectionFailed);
391  } else {
392  // no proxy needed (none set for target network)
393  hSocket = CreateSocket(addrConnect);
394  if (hSocket == INVALID_SOCKET) {
395  return nullptr;
396  }
397  connected = ConnectSocketDirectly(addrConnect, hSocket, nConnectTimeout, manual_connection);
398  }
399  if (!proxyConnectionFailed) {
400  // If a connection to the node was attempted, and failure (if any) is not caused by a problem connecting to
401  // the proxy, mark this as an attempt.
402  addrman.Attempt(addrConnect, fCountFailure);
403  }
404  } else if (pszDest && GetNameProxy(proxy)) {
405  hSocket = CreateSocket(proxy.proxy);
406  if (hSocket == INVALID_SOCKET) {
407  return nullptr;
408  }
409  std::string host;
410  int port = default_port;
411  SplitHostPort(std::string(pszDest), port, host);
412  connected = ConnectThroughProxy(proxy, host, port, hSocket, nConnectTimeout, nullptr);
413  }
414  if (!connected) {
415  CloseSocket(hSocket);
416  return nullptr;
417  }
418 
419  // Add node
420  NodeId id = GetNewNodeId();
421  uint64_t nonce = GetDeterministicRandomizer(RANDOMIZER_ID_LOCALHOSTNONCE).Write(id).Finalize();
422  CNode* pnode = new CNode(id, nLocalServices, GetBestHeight(), hSocket, addrConnect, CalculateKeyedNetGroup(addrConnect), nonce, pszDest ? pszDest : "", false);
424  pnode->fWhitelisted = IsWhitelistedRange(addrConnect);
425  pnode->AddRef();
426 
427  // We're making a new connection, harvest entropy from the time (and our peer count)
428  RandAddEvent((uint32_t)id);
429 
430  return pnode;
431 }
432 
434 {
435  SweepBanned(); // clean unused entries (if bantime has expired)
436 
437  if (!BannedSetIsDirty())
438  return;
439 
440  int64_t nStart = GetTimeMillis();
441 
442  CBanDB bandb;
443  banmap_t banmap;
444  GetBanned(banmap);
445  if (bandb.Write(banmap)) {
446  SetBannedSetDirty(false);
447  }
448 
449  LogPrint(BCLog::NET, "Flushed %d banned node ips/subnets to banlist.dat %dms\n",
450  banmap.size(), GetTimeMillis() - nStart);
451 }
452 
454 {
455  fDisconnect = true;
456  LOCK(cs_hSocket);
457  if (hSocket != INVALID_SOCKET) {
458  LogPrint(BCLog::NET, "disconnecting peer=%d\n", id);
460  }
461 }
462 
463 bool CNode::DisconnectOldProtocol(int nVersionIn, int nVersionRequired)
464 {
465  fDisconnect = false;
466  if (nVersionIn < nVersionRequired) {
467  LogPrintf("%s : peer=%d using obsolete version %i; disconnecting\n", __func__, id, nVersionIn);
468  fDisconnect = true;
469  }
470  return fDisconnect;
471 }
472 
474 {
475  {
477  setBanned.clear();
478  setBannedIsDirty = true;
479  }
480  DumpBanlist(); // store banlist to Disk
481  if(clientInterface)
483 }
484 
486 {
488  for (const auto& it : setBanned) {
489  CSubNet subNet = it.first;
490  CBanEntry banEntry = it.second;
491 
492  if (subNet.Match(ip) && GetTime() < banEntry.nBanUntil) {
493  return true;
494  }
495  }
496  return false;
497 }
498 
500 {
502  banmap_t::iterator i = setBanned.find(subnet);
503  if (i != setBanned.end()) {
504  CBanEntry banEntry = (*i).second;
505  if (GetTime() < banEntry.nBanUntil) {
506  return true;
507  }
508  }
509  return false;
510 }
511 
512 void CConnman::Ban(const CNetAddr& addr, const BanReason &banReason, int64_t bantimeoffset, bool sinceUnixEpoch)
513 {
514  CSubNet subNet(addr);
515  Ban(subNet, banReason, bantimeoffset, sinceUnixEpoch);
516 }
517 
518 void CConnman::Ban(const CSubNet& subNet, const BanReason &banReason, int64_t bantimeoffset, bool sinceUnixEpoch)
519 {
520  CBanEntry banEntry(GetTime());
521  banEntry.banReason = banReason;
522  if (bantimeoffset <= 0)
523  {
524  bantimeoffset = gArgs.GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME); // Default 24-hour ban
525  sinceUnixEpoch = false;
526  }
527  banEntry.nBanUntil = (sinceUnixEpoch ? 0 : GetTime() )+bantimeoffset;
528 
529  {
531  if (setBanned[subNet].nBanUntil < banEntry.nBanUntil) {
532  setBanned[subNet] = banEntry;
533  setBannedIsDirty = true;
534  }
535  else
536  return;
537  }
538  if(clientInterface)
540  {
541  LOCK(cs_vNodes);
542  for (CNode* pnode : vNodes) {
543  if (subNet.Match(static_cast<CNetAddr>(pnode->addr)))
544  pnode->fDisconnect = true;
545  }
546  }
547  if(banReason == BanReasonManuallyAdded)
548  DumpBanlist(); //store banlist to disk immediately if user requested ban
549 }
550 
551 bool CConnman::Unban(const CNetAddr &addr)
552 {
553  CSubNet subNet(addr);
554  return Unban(subNet);
555 }
556 
557 bool CConnman::Unban(const CSubNet &subNet)
558 {
559  {
561  if (!setBanned.erase(subNet))
562  return false;
563  setBannedIsDirty = true;
564  }
565  if(clientInterface)
567  DumpBanlist(); //store banlist to disk immediately
568  return true;
569 }
570 
572 {
574  // Sweep the banlist so expired bans are not returned
575  SweepBanned();
576  banMap = setBanned; //create a thread safe copy
577 }
578 
579 void CConnman::SetBanned(const banmap_t &banMap)
580 {
582  setBanned = banMap;
583  setBannedIsDirty = true;
584 }
585 
587 {
588  int64_t now = GetTime();
589 
590  bool notifyUI = false;
591  {
593  banmap_t::iterator it = setBanned.begin();
594  while(it != setBanned.end())
595  {
596  CSubNet subNet = (*it).first;
597  CBanEntry banEntry = (*it).second;
598  if(now > banEntry.nBanUntil)
599  {
600  setBanned.erase(it++);
601  setBannedIsDirty = true;
602  notifyUI = true;
603  LogPrint(BCLog::NET, "%s: Removed banned node ip/subnet from banlist.dat: %s\n", __func__, subNet.ToString());
604  }
605  else
606  ++it;
607  }
608  }
609  // update UI
610  if(notifyUI) {
612  }
613 }
614 
616 {
618  return setBannedIsDirty;
619 }
620 
622 {
623  LOCK(cs_setBanned); //reuse setBanned lock for the isDirty flag
624  setBannedIsDirty = dirty;
625 }
626 
627 
629 {
630  for (const CSubNet& subnet : vWhitelistedRange) {
631  if (subnet.Match(addr))
632  return true;
633  }
634  return false;
635 }
636 
637 std::string CNode::GetAddrName() const {
638  LOCK(cs_addrName);
639  return addrName;
640 }
641 
642 void CNode::MaybeSetAddrName(const std::string& addrNameIn) {
643  LOCK(cs_addrName);
644  if (addrName.empty()) {
645  addrName = addrNameIn;
646  }
647 }
648 
651  return addrLocal;
652 }
653 
654 void CNode::SetAddrLocal(const CService& addrLocalIn) {
656  if (addrLocal.IsValid()) {
657  error("Addr local already set for node: %i. Refusing to change from %s to %s", id, addrLocal.ToString(), addrLocalIn.ToString());
658  } else {
659  addrLocal = addrLocalIn;
660  }
661 }
662 
663 #undef X
664 #define X(name) stats.name = name
665 void CNode::copyStats(CNodeStats& stats, const std::vector<bool>& m_asmap)
666 {
667  stats.nodeid = this->GetId();
668  X(nServices);
669  stats.m_mapped_as = addr.GetMappedAS(m_asmap);
670  X(nLastSend);
671  X(nLastRecv);
672  X(nTimeConnected);
673  X(nTimeOffset);
674  stats.addrName = GetAddrName();
675  X(nVersion);
676  {
677  LOCK(cs_SubVer);
678  X(cleanSubVer);
679  }
680  X(fInbound);
681  X(fAddnode);
683  {
684  LOCK(cs_vSend);
686  X(nSendBytes);
687  }
688  {
689  LOCK(cs_vRecv);
691  X(nRecvBytes);
692  }
693  X(fWhitelisted);
697  {
698  LOCK(cs_mnauth);
701  }
702 
703  // It is common for nodes with good ping times to suddenly become lagged,
704  // due to a new block arriving or other large transfer.
705  // Merely reporting pingtime might fool the caller into thinking the node was still responsive,
706  // since pingtime does not update until the ping is complete, which might take a while.
707  // So, if a ping is taking an unusually long time in flight,
708  // the caller can immediately detect that this is happening.
709  int64_t nPingUsecWait = 0;
710  if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) {
711  nPingUsecWait = GetTimeMicros() - nPingUsecStart;
712  }
713 
714  // Raw ping time is in microseconds, but show it to user as whole seconds (PIVX users should be well used to small numbers with many decimal places by now :)
715  stats.dPingTime = (((double)nPingUsecTime) / 1e6);
716  stats.dPingWait = (((double)nPingUsecWait) / 1e6);
717 
718  // Leave string empty if addrLocal invalid (not filled in yet)
719  CService addrLocalUnlocked = GetAddrLocal();
720  stats.addrLocal = addrLocalUnlocked.IsValid() ? addrLocalUnlocked.ToString() : "";
721 }
722 #undef X
723 
724 bool CNode::ReceiveMsgBytes(const char* pch, unsigned int nBytes, bool& complete)
725 {
726  complete = false;
727  int64_t nTimeMicros = GetTimeMicros();
728  LOCK(cs_vRecv);
729  nLastRecv = nTimeMicros / 1000000;
730  nRecvBytes += nBytes;
731  while (nBytes > 0) {
732  // get current incomplete message, or create a new one
733  if (vRecvMsg.empty() ||
734  vRecvMsg.back().complete())
735  vRecvMsg.emplace_back(Params().MessageStart(), SER_NETWORK, INIT_PROTO_VERSION);
736 
737  CNetMessage& msg = vRecvMsg.back();
738 
739  // absorb network data
740  int handled;
741  if (!msg.in_data)
742  handled = msg.readHeader(pch, nBytes);
743  else
744  handled = msg.readData(pch, nBytes);
745 
746  if (handled < 0)
747  return false;
748 
749  if (msg.in_data && msg.hdr.nMessageSize > MAX_PROTOCOL_MESSAGE_LENGTH) {
750  LogPrint(BCLog::NET, "Oversized message from peer=%i, disconnecting\n", GetId());
751  return false;
752  }
753 
754  pch += handled;
755  nBytes -= handled;
756 
757  if (msg.complete()) {
758 
759  // Store received bytes per message command
760  // to prevent a memory DOS, only allow valid commands
761  mapMsgCmdSize::iterator i = mapRecvBytesPerMsgCmd.find(msg.hdr.pchCommand);
762  if (i == mapRecvBytesPerMsgCmd.end())
763  i = mapRecvBytesPerMsgCmd.find(NET_MESSAGE_COMMAND_OTHER);
764  assert(i != mapRecvBytesPerMsgCmd.end());
765  i->second += msg.hdr.nMessageSize + CMessageHeader::HEADER_SIZE;
766 
767  msg.nTime = nTimeMicros;
768  complete = true;
769  }
770  }
771 
772  return true;
773 }
774 
775 void CNode::SetSendVersion(int nVersionIn)
776 {
777  // Send version may only be changed in the version message, and
778  // only one version message is allowed per session. We can therefore
779  // treat this value as const and even atomic as long as it's only used
780  // once a version message has been successfully processed. Any attempt to
781  // set this twice is an error.
782  if (nSendVersion != 0) {
783  error("Send version already set for node: %i. Refusing to change from %i to %i", id, nSendVersion, nVersionIn);
784  } else {
785  nSendVersion = nVersionIn;
786  }
787 }
788 
790 {
791  // The send version should always be explicitly set to
792  // INIT_PROTO_VERSION rather than using this value until SetSendVersion
793  // has been called.
794  if (nSendVersion == 0) {
795  error("Requesting unset send version for node: %i. Using %i", id, INIT_PROTO_VERSION);
796  return INIT_PROTO_VERSION;
797  }
798  return nSendVersion;
799 }
800 
801 int CNetMessage::readHeader(const char* pch, unsigned int nBytes)
802 {
803  // copy data to temporary parsing buffer
804  unsigned int nRemaining = 24 - nHdrPos;
805  unsigned int nCopy = std::min(nRemaining, nBytes);
806 
807  memcpy(&hdrbuf[nHdrPos], pch, nCopy);
808  nHdrPos += nCopy;
809 
810  // if header incomplete, exit
811  if (nHdrPos < 24)
812  return nCopy;
813 
814  // deserialize to CMessageHeader
815  try {
816  hdrbuf >> hdr;
817  } catch (const std::exception&) {
818  return -1;
819  }
820 
821  // reject messages larger than MAX_SIZE
822  if (hdr.nMessageSize > MAX_SIZE)
823  return -1;
824 
825  // switch state to reading message data
826  in_data = true;
827 
828  return nCopy;
829 }
830 
831 int CNetMessage::readData(const char* pch, unsigned int nBytes)
832 {
833  unsigned int nRemaining = hdr.nMessageSize - nDataPos;
834  unsigned int nCopy = std::min(nRemaining, nBytes);
835 
836  if (vRecv.size() < nDataPos + nCopy) {
837  // Allocate up to 256 KiB ahead, but never more than the total message size.
838  vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024));
839  }
840 
841  hasher.Write((const unsigned char*)pch, nCopy);
842  memcpy(&vRecv[nDataPos], pch, nCopy);
843  nDataPos += nCopy;
844 
845  return nCopy;
846 }
847 
849 {
850  assert(complete());
851  if (data_hash.IsNull())
853  return data_hash;
854 }
855 
856 // requires LOCK(cs_vSend)
858 {
859  auto it = pnode->vSendMsg.begin();
860  size_t nSentSize = 0;
861 
862  while (it != pnode->vSendMsg.end()) {
863  const auto& data = *it;
864  assert(data.size() > pnode->nSendOffset);
865  int nBytes = 0;
866  {
867  LOCK(pnode->cs_hSocket);
868  if (pnode->hSocket == INVALID_SOCKET)
869  break;
870  nBytes = send(pnode->hSocket, reinterpret_cast<const char*>(data.data()) + pnode->nSendOffset, data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT);
871  }
872  if (nBytes > 0) {
874  pnode->nSendBytes += nBytes;
875  pnode->nSendOffset += nBytes;
876  nSentSize += nBytes;
877  if (pnode->nSendOffset == data.size()) {
878  pnode->nSendOffset = 0;
879  pnode->nSendSize -= data.size();
880  pnode->fPauseSend = pnode->nSendSize > nSendBufferMaxSize;
881  it++;
882  } else {
883  // could not send full message; stop sending more
884  break;
885  }
886  } else {
887  if (nBytes < 0) {
888  // error
889  int nErr = WSAGetLastError();
890  if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) {
891  LogPrintf("socket send error %s\n", NetworkErrorString(nErr));
892  pnode->CloseSocketDisconnect();
893  }
894  }
895  // couldn't send anything at all
896  break;
897  }
898  }
899 
900  if (it == pnode->vSendMsg.end()) {
901  assert(pnode->nSendOffset == 0);
902  assert(pnode->nSendSize == 0);
903  }
904  pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it);
905  return nSentSize;
906 }
907 
909 {
910  int nConnections = 0;
911  if (g_connman) {
912  g_connman->ForEachNode([&nConnections](CNode* pnode) {
913  if (pnode->fSuccessfullyConnected)
914  nConnections++;
915  if (nConnections == ENOUGH_CONNECTIONS)
916  return;
917  });
918  }
919 
920  // Not enough connections. Insert peer.
921  static std::set<CNetAddr> setOffsetDisconnectedPeers;
922  setOffsetDisconnectedPeers.insert(ip);
923  if (setOffsetDisconnectedPeers.size() >= MAX_TIMEOFFSET_DISCONNECTIONS) {
924  // clear the set
925  setOffsetDisconnectedPeers.clear();
926  // Trigger the warning
927  std::string strWarn1 = _("Peers are being disconnected due time differences.");
928  std::string strWarn2 = strprintf(_("Please check that your computer's date and time are correct! If your clock is wrong %s will not work properly."), PACKAGE_NAME);
929 
930  LogPrintf("*** Warning: %s %s\n", strWarn1, strWarn2);
931 
932  static int64_t nLastGUINotif = 0;
933  int64_t now = GetTime();
934  if (nLastGUINotif + 40 < now) { // Notify the GUI if needed.
935  nLastGUINotif = now;
936  uiInterface.ThreadSafeMessageBox(strprintf("%s\n\n%s", strWarn1, strWarn2), _("Warning"), CClientUIInterface::MSG_ERROR);
937  }
938  }
939 }
940 
942 {
944  int64_t nTimeConnected;
947  uint64_t nKeyedNetGroup;
948 };
949 
950 static bool ReverseCompareNodeMinPingTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
951 {
952  return a.nMinPingUsecTime > b.nMinPingUsecTime;
953 }
954 
955 static bool ReverseCompareNodeTimeConnected(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
956 {
957  return a.nTimeConnected > b.nTimeConnected;
958 }
959 
960 static bool CompareNetGroupKeyed(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b) {
961  return a.nKeyedNetGroup < b.nKeyedNetGroup;
962 };
963 
972 bool CConnman::AttemptToEvictConnection(bool fPreferNewConnection)
973 {
974  std::vector<NodeEvictionCandidate> vEvictionCandidates;
975  {
976  LOCK(cs_vNodes);
977 
978  for (const CNode* node : vNodes) {
979  if (node->fWhitelisted)
980  continue;
981  if (!node->fInbound)
982  continue;
983  if (node->fDisconnect)
984  continue;
985 
986  // Protect verified MN-only connections
987  if (fMasterNode) {
988  // This handles eviction protected nodes. Nodes are always protected for a short time after the connection
989  // was accepted. This short time is meant for the VERSION/VERACK exchange and the possible MNAUTH that might
990  // follow when the incoming connection is from another masternode. When a message other than MNAUTH
991  // is received after VERSION/VERACK, the protection is lifted immediately.
992  bool isProtected = GetSystemTimeInSeconds() - node->nTimeConnected < INBOUND_EVICTION_PROTECTION_TIME;
993  if (node->fFirstMessageReceived && !node->fFirstMessageIsMNAUTH) {
994  isProtected = false;
995  }
996  // if MNAUTH was valid, the node is always protected (and at the same time not accounted when
997  // checking incoming connection limits)
998  if (!node->verifiedProRegTxHash.IsNull()) {
999  isProtected = true;
1000  }
1001  if (isProtected) {
1002  continue;
1003  }
1004  }
1005 
1006  NodeEvictionCandidate candidate = {node->GetId(), node->nTimeConnected, node->nMinPingUsecTime, node->addr, node->nKeyedNetGroup};
1007  vEvictionCandidates.push_back(candidate);
1008  }
1009  }
1010 
1011  if (vEvictionCandidates.empty()) return false;
1012 
1013  // Protect connections with certain characteristics
1014 
1015  // Deterministically select 4 peers to protect by netgroup.
1016  // An attacker cannot predict which netgroups will be protected
1017  std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), CompareNetGroupKeyed);
1018  vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(4, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end());
1019 
1020  if (vEvictionCandidates.empty()) return false;
1021 
1022  // Protect the 8 nodes with the lowest minimum ping time.
1023  // An attacker cannot manipulate this metric without physically moving nodes closer to the target.
1024  std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), ReverseCompareNodeMinPingTime);
1025  vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(8, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end());
1026 
1027  if (vEvictionCandidates.empty()) return false;
1028 
1029  // Protect the half of the remaining nodes which have been connected the longest.
1030  // This replicates the non-eviction implicit behavior, and precludes attacks that start later.
1031  std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), ReverseCompareNodeTimeConnected);
1032  vEvictionCandidates.erase(vEvictionCandidates.end() - static_cast<int>(vEvictionCandidates.size() / 2), vEvictionCandidates.end());
1033 
1034  if (vEvictionCandidates.empty()) return false;
1035 
1036  // Identify the network group with the most connections and youngest member.
1037  // (vEvictionCandidates is already sorted by reverse connect time)
1038  uint64_t naMostConnections;
1039  unsigned int nMostConnections = 0;
1040  int64_t nMostConnectionsTime = 0;
1041  std::map<uint64_t, std::vector<NodeEvictionCandidate> > mapAddrCounts;
1042  for (const NodeEvictionCandidate& node : vEvictionCandidates) {
1043  mapAddrCounts[node.nKeyedNetGroup].push_back(node);
1044  int64_t grouptime = mapAddrCounts[node.nKeyedNetGroup][0].nTimeConnected;
1045  size_t groupsize = mapAddrCounts[node.nKeyedNetGroup].size();
1046  if (groupsize > nMostConnections || (groupsize == nMostConnections && grouptime > nMostConnectionsTime)) {
1047  nMostConnections = groupsize;
1048  nMostConnectionsTime = grouptime;
1049  naMostConnections = node.nKeyedNetGroup;
1050  }
1051  }
1052 
1053  // Reduce to the network group with the most connections
1054  vEvictionCandidates = std::move(mapAddrCounts[naMostConnections]);
1055 
1056  // Do not disconnect peers if there is only 1 connection from their network group
1057  if (vEvictionCandidates.size() <= 1)
1058  // unless we prefer the new connection (for whitelisted peers)
1059  if (!fPreferNewConnection)
1060  return false;
1061 
1062  // Disconnect from the network group with the most connections
1063  NodeId evicted = vEvictionCandidates.front().id;
1064  LOCK(cs_vNodes);
1065  for (CNode* pnode : vNodes) {
1066  if (pnode->GetId() == evicted) {
1067  pnode->fDisconnect = true;
1068  return true;
1069  }
1070  }
1071  return false;
1072 }
1073 
1074 void CConnman::AcceptConnection(const ListenSocket& hListenSocket) {
1075  struct sockaddr_storage sockaddr;
1076  socklen_t len = sizeof(sockaddr);
1077  SOCKET hSocket = accept(hListenSocket.socket, (struct sockaddr*)&sockaddr, &len);
1078  CAddress addr;
1079  int nInbound = 0;
1080  int nVerifiedInboundMasternodes = 0;
1081 
1082  if (hSocket != INVALID_SOCKET)
1083  if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
1084  LogPrintf("Warning: Unknown socket family\n");
1085 
1086  bool whitelisted = hListenSocket.whitelisted || IsWhitelistedRange(addr);
1087  {
1088  LOCK(cs_vNodes);
1089  for (const CNode* pnode : vNodes) {
1090  if (pnode->fInbound) {
1091  nInbound++;
1092  if (!pnode->verifiedProRegTxHash.IsNull()) {
1093  nVerifiedInboundMasternodes++;
1094  }
1095  }
1096  }
1097  }
1098 
1099  if (hSocket == INVALID_SOCKET) {
1100  int nErr = WSAGetLastError();
1101  if (nErr != WSAEWOULDBLOCK)
1102  LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr));
1103  return;
1104  }
1105 
1106  if (!fNetworkActive) {
1107  LogPrintf("connection from %s dropped: not accepting new connections\n", addr.ToString());
1108  CloseSocket(hSocket);
1109  return;
1110  }
1111 
1112  if (!IsSelectableSocket(hSocket)) {
1113  LogPrintf("connection from %s dropped: non-selectable socket\n", addr.ToString());
1114  CloseSocket(hSocket);
1115  return;
1116  }
1117 
1118  // According to the internet TCP_NODELAY is not carried into accepted sockets
1119  // on all platforms. Set it again here just to be sure.
1120  SetSocketNoDelay(hSocket);
1121 
1122  if (IsBanned(addr) && !whitelisted)
1123  {
1124  LogPrintf("connection from %s dropped (banned)\n", addr.ToString());
1125  CloseSocket(hSocket);
1126  return;
1127  }
1128 
1129  // TODO: pending review.
1130  // Evict connections until we are below nMaxInbound. In case eviction protection resulted in nodes to not be evicted
1131  // before, they might get evicted in batches now (after the protection timeout).
1132  // We don't evict verified MN connections and also don't take them into account when checking limits. We can do this
1133  // because we know that such connections are naturally limited by the total number of MNs, so this is not usable
1134  // for attacks.
1135  while (nInbound - nVerifiedInboundMasternodes >= nMaxConnections - MAX_OUTBOUND_CONNECTIONS) {
1136  if (!AttemptToEvictConnection(whitelisted)) {
1137  // No connection to evict, disconnect the new connection
1138  LogPrint(BCLog::NET, "failed to find an eviction candidate - connection dropped (full)\n");
1139  CloseSocket(hSocket);
1140  return;
1141  }
1142  nInbound--;
1143  }
1144 
1145  NodeId id = GetNewNodeId();
1146  uint64_t nonce = GetDeterministicRandomizer(RANDOMIZER_ID_LOCALHOSTNONCE).Write(id).Finalize();
1147 
1148  CNode* pnode = new CNode(id, nLocalServices, GetBestHeight(), hSocket, addr, CalculateKeyedNetGroup(addr), nonce, "", true);
1149  pnode->AddRef();
1150  pnode->fWhitelisted = whitelisted;
1151  m_msgproc->InitializeNode(pnode);
1152 
1153  LogPrint(BCLog::NET, "connection from %s accepted\n", addr.ToString());
1154 
1155  {
1156  LOCK(cs_vNodes);
1157  vNodes.push_back(pnode);
1158  }
1159 
1160  // We received a new connection, harvest entropy from the time (and our peer count)
1161  RandAddEvent((uint32_t)id);
1162 }
1163 
1165 {
1166  {
1167  LOCK(cs_vNodes);
1168 
1169  if (!fNetworkActive) {
1170  // Disconnect any connected nodes
1171  for (CNode* pnode : vNodes) {
1172  if (!pnode->fDisconnect) {
1173  LogPrint(BCLog::NET, "Network not active, dropping peer=%d\n", pnode->GetId());
1174  pnode->fDisconnect = true;
1175  }
1176  }
1177  }
1178 
1179  // Disconnect unused nodes
1180  std::vector<CNode*> vNodesCopy = vNodes;
1181  for (CNode* pnode : vNodesCopy) {
1182  if (pnode->fDisconnect) {
1183  // remove from vNodes
1184  vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
1185 
1186  // release outbound grant (if any)
1187  pnode->grantOutbound.Release();
1188 
1189  // close socket and cleanup
1190  pnode->CloseSocketDisconnect();
1191 
1192  // hold in disconnected pool until all refs are released
1193  pnode->Release();
1194  vNodesDisconnected.push_back(pnode);
1195  }
1196  }
1197  }
1198  {
1199  // Delete disconnected nodes
1200  std::list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
1201  for (CNode* pnode : vNodesDisconnectedCopy) {
1202  // wait until threads are done using it
1203  if (pnode->GetRefCount() <= 0) {
1204  bool fDelete = false;
1205  {
1206  TRY_LOCK(pnode->cs_inventory, lockInv);
1207  if (lockInv) {
1208  TRY_LOCK(pnode->cs_vSend, lockSend);
1209  if (lockSend) {
1210  fDelete = true;
1211  }
1212  }
1213  }
1214  if (fDelete) {
1215  vNodesDisconnected.remove(pnode);
1216  DeleteNode(pnode);
1217  }
1218  }
1219  }
1220  }
1221 }
1222 
1224 {
1225  size_t vNodesSize;
1226  {
1227  LOCK(cs_vNodes);
1228  vNodesSize = vNodes.size();
1229  }
1230  if (vNodesSize != nPrevNodeCount) {
1231  nPrevNodeCount = vNodesSize;
1232  if (clientInterface)
1233  clientInterface->NotifyNumConnectionsChanged((int)vNodesSize);
1234  }
1235 }
1236 
1238 {
1239  int64_t nTime = GetSystemTimeInSeconds();
1240  if (nTime - pnode->nTimeConnected > 60) {
1241  if (pnode->nLastRecv == 0 || pnode->nLastSend == 0) {
1242  LogPrint(BCLog::NET, "socket no message in first 60 seconds, %d %d from %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0, pnode->GetId());
1243  pnode->fDisconnect = true;
1244  } else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL) {
1245  LogPrintf("socket sending timeout: %is\n", nTime - pnode->nLastSend);
1246  pnode->fDisconnect = true;
1247  } else if (nTime - pnode->nLastRecv > TIMEOUT_INTERVAL) {
1248  LogPrintf("socket receive timeout: %is\n", nTime - pnode->nLastRecv);
1249  pnode->fDisconnect = true;
1250  } else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros()) {
1251  LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart));
1252  pnode->fDisconnect = true;
1253  } else if (!pnode->fSuccessfullyConnected) {
1254  LogPrint(BCLog::NET, "version handshake timeout from %d\n", pnode->GetId());
1255  pnode->fDisconnect = true;
1256  }
1257  }
1258 }
1259 
1260 bool CConnman::GenerateSelectSet(std::set<SOCKET>& recv_set, std::set<SOCKET>& send_set, std::set<SOCKET>& error_set)
1261 {
1262  for (const ListenSocket& hListenSocket : vhListenSocket) {
1263  recv_set.insert(hListenSocket.socket);
1264  }
1265 
1266  {
1267  LOCK(cs_vNodes);
1268  for (CNode* pnode: vNodes) {
1269  // Implement the following logic:
1270  // * If there is data to send, select() for sending data. As this only
1271  // happens when optimistic write failed, we choose to first drain the
1272  // write buffer in this case before receiving more. This avoids
1273  // needlessly queueing received data, if the remote peer is not themselves
1274  // receiving data. This means properly utilizing TCP flow control signalling.
1275  // * Otherwise, if there is space left in the receive buffer, select() for
1276  // receiving data.
1277  // * Hand off all complete messages to the processor, to be handled without
1278  // blocking here.
1279 
1280  bool select_recv = !pnode->fPauseRecv;
1281  bool select_send;
1282  {
1283  LOCK(pnode->cs_vSend);
1284  select_send = !pnode->vSendMsg.empty();
1285  }
1286 
1287  LOCK(pnode->cs_hSocket);
1288  if (pnode->hSocket == INVALID_SOCKET)
1289  continue;
1290 
1291  error_set.insert(pnode->hSocket);
1292  if (select_send) {
1293  send_set.insert(pnode->hSocket);
1294  continue;
1295  }
1296  if (select_recv) {
1297  recv_set.insert(pnode->hSocket);
1298  }
1299  }
1300  }
1301 
1302 #ifdef USE_WAKEUP_PIPE
1303  // We add a pipe to the read set so that the select() call can be woken up from the outside
1304  // This is done when data is added to send buffers (vSendMsg) or when new peers are added
1305  // This is currently only implemented for POSIX compliant systems. This means that Windows will fall back to
1306  // timing out after 50ms and then trying to send. This is ok as we assume that heavy-load daemons are usually
1307  // run on Linux and friends.
1308  recv_set.insert(wakeupPipe[0]);
1309 #endif
1310 
1311  return !recv_set.empty() || !send_set.empty() || !error_set.empty();
1312 }
1313 
1314 #ifdef USE_POLL
1315 void CConnman::SocketEvents(std::set<SOCKET>& recv_set, std::set<SOCKET>& send_set, std::set<SOCKET>& error_set)
1316 {
1317  std::set<SOCKET> recv_select_set, send_select_set, error_select_set;
1318  if (!GenerateSelectSet(recv_select_set, send_select_set, error_select_set)) {
1319  interruptNet.sleep_for(std::chrono::milliseconds(SELECT_TIMEOUT_MILLISECONDS));
1320  return;
1321  }
1322 
1323  std::unordered_map<SOCKET, struct pollfd> pollfds;
1324  for (SOCKET socket_id : recv_select_set) {
1325  pollfds[socket_id].fd = socket_id;
1326  pollfds[socket_id].events |= POLLIN;
1327  }
1328 
1329  for (SOCKET socket_id : send_select_set) {
1330  pollfds[socket_id].fd = socket_id;
1331  pollfds[socket_id].events |= POLLOUT;
1332  }
1333 
1334  for (SOCKET socket_id : error_select_set) {
1335  pollfds[socket_id].fd = socket_id;
1336  // These flags are ignored, but we set them for clarity
1337  pollfds[socket_id].events |= POLLERR|POLLHUP;
1338  }
1339 
1340  std::vector<struct pollfd> vpollfds;
1341  vpollfds.reserve(pollfds.size());
1342  for (auto it : pollfds) {
1343  vpollfds.push_back(std::move(it.second));
1344  }
1345 
1346  wakeupSelectNeeded = true;
1347  int r = poll(vpollfds.data(), vpollfds.size(), SELECT_TIMEOUT_MILLISECONDS);
1348  wakeupSelectNeeded = false;
1349  if (r < 0) {
1350  return;
1351  }
1352 
1353  if (interruptNet) return;
1354 
1355  for (struct pollfd pollfd_entry : vpollfds) {
1356  if (pollfd_entry.revents & POLLIN) recv_set.insert(pollfd_entry.fd);
1357  if (pollfd_entry.revents & POLLOUT) send_set.insert(pollfd_entry.fd);
1358  if (pollfd_entry.revents & (POLLERR|POLLHUP)) error_set.insert(pollfd_entry.fd);
1359  }
1360 }
1361 #else
1362 void CConnman::SocketEvents(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set)
1363 {
1364  std::set<SOCKET> recv_select_set, send_select_set, error_select_set;
1365  if (!GenerateSelectSet(recv_select_set, send_select_set, error_select_set)) {
1366  interruptNet.sleep_for(std::chrono::milliseconds(SELECT_TIMEOUT_MILLISECONDS));
1367  return;
1368  }
1369 
1370  //
1371  // Find which sockets have data to receive
1372  //
1373  struct timeval timeout;
1374  timeout.tv_sec = 0;
1375  timeout.tv_usec = SELECT_TIMEOUT_MILLISECONDS * 1000; // frequency to poll pnode->vSend
1376 
1377  fd_set fdsetRecv;
1378  fd_set fdsetSend;
1379  fd_set fdsetError;
1380  FD_ZERO(&fdsetRecv);
1381  FD_ZERO(&fdsetSend);
1382  FD_ZERO(&fdsetError);
1383  SOCKET hSocketMax = 0;
1384 
1385  for (SOCKET hSocket : recv_select_set) {
1386  FD_SET(hSocket, &fdsetRecv);
1387  hSocketMax = std::max(hSocketMax, hSocket);
1388  }
1389 
1390  for (SOCKET hSocket : send_select_set) {
1391  FD_SET(hSocket, &fdsetSend);
1392  hSocketMax = std::max(hSocketMax, hSocket);
1393  }
1394 
1395  for (SOCKET hSocket : error_select_set) {
1396  FD_SET(hSocket, &fdsetError);
1397  hSocketMax = std::max(hSocketMax, hSocket);
1398  }
1399 
1400  wakeupSelectNeeded = true;
1401  int nSelect = select(hSocketMax + 1, &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
1402  wakeupSelectNeeded = false;
1403 
1404  if (interruptNet)
1405  return;
1406 
1407  if (nSelect == SOCKET_ERROR) {
1408  int nErr = WSAGetLastError();
1409  LogPrintf("socket select error %s\n", NetworkErrorString(nErr));
1410  for (unsigned int i = 0; i <= hSocketMax; i++)
1411  FD_SET(i, &fdsetRecv);
1412  FD_ZERO(&fdsetSend);
1413  FD_ZERO(&fdsetError);
1414  if (!interruptNet.sleep_for(std::chrono::milliseconds(SELECT_TIMEOUT_MILLISECONDS)))
1415  return;
1416  }
1417 
1418  for (SOCKET hSocket : recv_select_set) {
1419  if (FD_ISSET(hSocket, &fdsetRecv)) {
1420  recv_set.insert(hSocket);
1421  }
1422  }
1423 
1424  for (SOCKET hSocket : send_select_set) {
1425  if (FD_ISSET(hSocket, &fdsetSend)) {
1426  send_set.insert(hSocket);
1427  }
1428  }
1429 
1430  for (SOCKET hSocket : error_select_set) {
1431  if (FD_ISSET(hSocket, &fdsetError)) {
1432  error_set.insert(hSocket);
1433  }
1434  }
1435 }
1436 #endif
1437 
1439 {
1440  std::set<SOCKET> recv_set, send_set, error_set;
1441  SocketEvents(recv_set, send_set, error_set);
1442 
1443 #ifdef USE_WAKEUP_PIPE
1444  // drain the wakeup pipe
1445  if (recv_set.count(wakeupPipe[0])) {
1446  LogPrint(BCLog::NET, "woke up select()\n");
1447  char buf[128];
1448  while (true) {
1449  int r = read(wakeupPipe[0], buf, sizeof(buf));
1450  if (r <= 0) {
1451  break;
1452  }
1453  }
1454  }
1455 #endif
1456 
1457  if (interruptNet) return;
1458 
1459  //
1460  // Accept new connections
1461  //
1462  for (const ListenSocket& hListenSocket : vhListenSocket) {
1463  if (hListenSocket.socket != INVALID_SOCKET && recv_set.count(hListenSocket.socket) > 0) {
1464  AcceptConnection(hListenSocket);
1465  }
1466  }
1467 
1468  //
1469  // Service each socket
1470  //
1471  std::vector<CNode*> vNodesCopy = CopyNodeVector();
1472 
1473  for (CNode* pnode : vNodesCopy) {
1474  if (interruptNet)
1475  return;
1476 
1477  //
1478  // Receive
1479  //
1480  bool recvSet = false;
1481  bool sendSet = false;
1482  bool errorSet = false;
1483  {
1484  LOCK(pnode->cs_hSocket);
1485  if (pnode->hSocket == INVALID_SOCKET)
1486  continue;
1487  recvSet = recv_set.count(pnode->hSocket) > 0;
1488  sendSet = send_set.count(pnode->hSocket) > 0;
1489  errorSet = error_set.count(pnode->hSocket) > 0;
1490  }
1491  if (recvSet || errorSet) {
1492  // typical socket buffer is 8K-64K
1493  char pchBuf[0x10000];
1494  int nBytes = 0;
1495  {
1496  LOCK(pnode->cs_hSocket);
1497  if (pnode->hSocket == INVALID_SOCKET)
1498  continue;
1499  nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
1500  }
1501  if (nBytes > 0) {
1502  bool notify = false;
1503  if (!pnode->ReceiveMsgBytes(pchBuf, nBytes, notify))
1504  pnode->CloseSocketDisconnect();
1505  RecordBytesRecv(nBytes);
1506  if (notify) {
1507  size_t nSizeAdded = 0;
1508  auto it(pnode->vRecvMsg.begin());
1509  for (; it != pnode->vRecvMsg.end(); ++it) {
1510  if (!it->complete())
1511  break;
1512  nSizeAdded += it->vRecv.size() + CMessageHeader::HEADER_SIZE;
1513  }
1514  {
1515  LOCK(pnode->cs_vProcessMsg);
1516  pnode->vProcessMsg.splice(pnode->vProcessMsg.end(), pnode->vRecvMsg, pnode->vRecvMsg.begin(), it);
1517  pnode->nProcessQueueSize += nSizeAdded;
1519  }
1521  }
1522  } else if (nBytes == 0) {
1523  // socket closed gracefully
1524  if (!pnode->fDisconnect)
1525  LogPrint(BCLog::NET, "socket closed\n");
1526  pnode->CloseSocketDisconnect();
1527  } else if (nBytes < 0) {
1528  // error
1529  int nErr = WSAGetLastError();
1530  if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) {
1531  if (!pnode->fDisconnect)
1532  LogPrintf("socket recv error %s\n", NetworkErrorString(nErr));
1533  pnode->CloseSocketDisconnect();
1534  }
1535  }
1536  }
1537 
1538  //
1539  // Send
1540  //
1541  if (sendSet) {
1542  LOCK(pnode->cs_vSend);
1543  size_t nBytes = SocketSendData(pnode);
1544  if (nBytes)
1545  RecordBytesSent(nBytes);
1546  }
1547 
1548  InactivityCheck(pnode);
1549  }
1550  ReleaseNodeVector(vNodesCopy);
1551 }
1552 
1554 {
1555  while (!interruptNet) {
1556  DisconnectNodes();
1558  SocketHandler();
1559  }
1560 }
1561 
1563 {
1564  {
1565  std::lock_guard<std::mutex> lock(mutexMsgProc);
1566  fMsgProcWake = true;
1567  }
1568  condMsgProc.notify_one();
1569 }
1570 
1572 {
1573 #ifdef USE_WAKEUP_PIPE
1574  if (wakeupPipe[1] == -1) {
1575  return;
1576  }
1577 
1578  LogPrint(BCLog::NET, "waking up select()\n");
1579 
1580  char buf[1];
1581  if (write(wakeupPipe[1], buf, 1) != 1) {
1582  LogPrint(BCLog::NET, "write to wakeupPipe failed\n");
1583  }
1584 #endif
1585 
1586  wakeupSelectNeeded = false;
1587 }
1588 
1589 static std::string GetDNSHost(const CDNSSeedData& data, ServiceFlags* requiredServiceBits)
1590 {
1591  //use default host for non-filter-capable seeds or if we use the default service bits (NODE_NETWORK)
1592  if (!data.supportsServiceBitsFiltering || *requiredServiceBits == NODE_NETWORK) {
1593  *requiredServiceBits = NODE_NETWORK;
1594  return data.host;
1595  }
1596 
1597  return strprintf("x%x.%s", *requiredServiceBits, data.host);
1598 }
1599 
1600 
1602 {
1603  // goal: only query DNS seeds if address need is acute
1604  if ((addrman.size() > 0) &&
1605  (!gArgs.GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED))) {
1606  if (!interruptNet.sleep_for(std::chrono::seconds(11)))
1607  return;
1608 
1609  LOCK(cs_vNodes);
1610  int nRelevant = 0;
1611  for (auto pnode : vNodes) {
1612  nRelevant += pnode->fSuccessfullyConnected && !pnode->fFeeler && !pnode->fOneShot && !pnode->fAddnode && !pnode->fInbound && !pnode->m_masternode_probe_connection;
1613  }
1614  if (nRelevant >= 2) {
1615  LogPrintf("P2P peers available. Skipped DNS seeding.\n");
1616  return;
1617  }
1618  }
1619 
1620  const std::vector<CDNSSeedData>& vSeeds = Params().DNSSeeds();
1621  int found = 0;
1622 
1623  LogPrintf("Loading addresses from DNS seeds (could take a while)\n");
1624 
1625  for (const CDNSSeedData& seed : vSeeds) {
1626  if (interruptNet) {
1627  return;
1628  }
1629  if (HaveNameProxy()) {
1630  AddOneShot(seed.host);
1631  } else {
1632  std::vector<CNetAddr> vIPs;
1633  std::vector<CAddress> vAdd;
1634  ServiceFlags requiredServiceBits = nRelevantServices;
1635  std::string host = GetDNSHost(seed, &requiredServiceBits);
1636  CNetAddr resolveSource;
1637  if (!resolveSource.SetInternal(host)) {
1638  continue;
1639  }
1640  if (LookupHost(host, vIPs, 0, true)) {
1641  for (CNetAddr& ip : vIPs) {
1642  int nOneDay = 24*3600;
1643  CAddress addr = CAddress(CService(ip, Params().GetDefaultPort()), requiredServiceBits);
1644  addr.nTime = GetTime() - 3 * nOneDay - GetRand(4 * nOneDay); // use a random age between 3 and 7 days old
1645  vAdd.push_back(addr);
1646  found++;
1647  }
1648  addrman.Add(vAdd, resolveSource);
1649  }
1650  }
1651  }
1652 
1653  LogPrintf("%d addresses found from DNS seeds\n", found);
1654 }
1655 
1656 
1657 
1658 
1659 
1660 
1661 
1662 
1663 
1664 
1665 
1666 
1668 {
1669  int64_t nStart = GetTimeMillis();
1670 
1671  CAddrDB adb;
1672  adb.Write(addrman);
1673 
1674  LogPrint(BCLog::NET, "Flushed %d addresses to peers.dat %dms\n",
1675  addrman.size(), GetTimeMillis() - nStart);
1676 }
1677 
1679 {
1680  DumpAddresses();
1681  DumpBanlist();
1682 }
1683 
1685 {
1686  std::string strDest;
1687  {
1688  LOCK(cs_vOneShots);
1689  if (vOneShots.empty())
1690  return;
1691  strDest = vOneShots.front();
1692  vOneShots.pop_front();
1693  }
1694  CAddress addr;
1695  CSemaphoreGrant grant(*semOutbound, true);
1696  if (grant) {
1697  OpenNetworkConnection(addr, false, &grant, strDest.c_str(), true);
1698  }
1699 }
1700 
1701 void CConnman::ThreadOpenConnections(const std::vector<std::string> connect)
1702 {
1703  // Connect to specific addresses
1704  if (!connect.empty()) {
1705  for (int64_t nLoop = 0;; nLoop++) {
1706  ProcessOneShot();
1707  for (const std::string& strAddr : connect) {
1708  CAddress addr(CService(), NODE_NONE);
1709  OpenNetworkConnection(addr, false, nullptr, strAddr.c_str());
1710  for (int i = 0; i < 10 && i < nLoop; i++) {
1711  if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
1712  return;
1713  }
1714  }
1715  if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
1716  return;
1717  }
1718  }
1719 
1720  // Initiate network connections
1721  int64_t nStart = GetTime();
1722 
1723  // Minimum time before next feeler connection (in microseconds).
1724  int64_t nNextFeeler = PoissonNextSend(nStart * 1000 * 1000, FEELER_INTERVAL);
1725  while (!interruptNet) {
1726  ProcessOneShot();
1727 
1728  if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
1729  return;
1730 
1731  CSemaphoreGrant grant(*semOutbound);
1732  if (interruptNet)
1733  return;
1734 
1735  // Add seed nodes if DNS seeds are all down (an infrastructure attack?).
1736  if (addrman.size() == 0 && (GetTime() - nStart > 60)) {
1737  static bool done = false;
1738  if (!done) {
1739  LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n");
1740  CNetAddr local;
1741  local.SetInternal("fixedseeds");
1742  addrman.Add(ConvertSeeds(Params().FixedSeeds()), local);
1743  done = true;
1744  }
1745  }
1746 
1747  //
1748  // Choose an address to connect to based on most recently seen
1749  //
1750  CAddress addrConnect;
1751 
1752  // Only connect out to one peer per network group (/16 for IPv4).
1753  // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
1754  int nOutbound = 0;
1755  std::set<std::vector<unsigned char> > setConnected;
1756  {
1757  LOCK(cs_vNodes);
1758  for (const CNode* pnode : vNodes) {
1759  if (!pnode->fInbound && !pnode->fAddnode && !pnode->m_masternode_connection) {
1760  // Netgroups for inbound and addnode peers are not excluded because our goal here
1761  // is to not use multiple of our limited outbound slots on a single netgroup
1762  // but inbound and addnode peers do not use our outbound slots. Inbound peers
1763  // also have the added issue that they're attacker controlled and could be used
1764  // to prevent us from connecting to particular hosts if we used them here.
1765  setConnected.insert(pnode->addr.GetGroup(addrman.m_asmap));
1766  nOutbound++;
1767  }
1768  }
1769  }
1770 
1771  // Feeler Connections
1772  //
1773  // Design goals:
1774  // * Increase the number of connectable addresses in the tried table.
1775  //
1776  // Method:
1777  // * Choose a random address from new and attempt to connect to it if we can connect
1778  // successfully it is added to tried.
1779  // * Start attempting feeler connections only after node finishes making outbound
1780  // connections.
1781  // * Only make a feeler connection once every few minutes.
1782  //
1783  bool fFeeler = false;
1784  if (nOutbound >= nMaxOutbound) {
1785  int64_t nTime = GetTimeMicros(); // The current time right now (in microseconds).
1786  if (nTime > nNextFeeler) {
1787  nNextFeeler = PoissonNextSend(nTime, FEELER_INTERVAL);
1788  fFeeler = true;
1789  } else {
1790  continue;
1791  }
1792  }
1793 
1795 
1796  int64_t nANow = GetAdjustedTime();
1797  int nTries = 0;
1798  while (!interruptNet) {
1800 
1801  // SelectTriedCollision returns an invalid address if it is empty.
1802  if (!fFeeler || !addr.IsValid()) {
1803  addr = addrman.Select(fFeeler);
1804  }
1805 
1806  // Require outbound connections, other than feelers, to be to distinct network groups
1807  if (!fFeeler && setConnected.count(addr.GetGroup(addrman.m_asmap))) {
1808  break;
1809  }
1810 
1811  // if we selected an invalid or local address, restart
1812  if (!addr.IsValid() || IsLocal(addr)) {
1813  break;
1814  }
1815 
1816  // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
1817  // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
1818  // already-connected network ranges, ...) before trying new addrman addresses.
1819  nTries++;
1820  if (nTries > 100)
1821  break;
1822 
1823  if (!IsReachable(addr))
1824  continue;
1825 
1826  // only connect to full nodes
1827  if ((addr.nServices & REQUIRED_SERVICES) != REQUIRED_SERVICES)
1828  continue;
1829 
1830  // only consider very recently tried nodes after 30 failed attempts
1831  if (nANow - addr.nLastTry < 600 && nTries < 30)
1832  continue;
1833 
1834  // do not allow non-default ports, unless after 50 invalid addresses selected already
1835  if (addr.GetPort() != Params().GetDefaultPort() && nTries < 50)
1836  continue;
1837 
1838  addrConnect = addr;
1839  break;
1840  }
1841 
1842  if (addrConnect.IsValid()) {
1843  if (fFeeler) {
1844  // Add small amount of random noise before connection to avoid synchronization.
1845  int randsleep = GetRandInt(FEELER_SLEEP_WINDOW * 1000);
1846  if (!interruptNet.sleep_for(std::chrono::milliseconds(randsleep)))
1847  return;
1848  LogPrint(BCLog::NET, "Making feeler connection to %s\n", addrConnect.ToString());
1849  }
1850 
1851  OpenNetworkConnection(addrConnect, (int)setConnected.size() >= std::min(nMaxConnections - 1, 2), &grant, nullptr, false, fFeeler);
1852  }
1853  }
1854 }
1855 
1856 std::vector<AddedNodeInfo> CConnman::GetAddedNodeInfo()
1857 {
1858  std::vector<AddedNodeInfo> ret;
1859 
1860  std::list<std::string> lAddresses(0);
1861  {
1863  ret.reserve(vAddedNodes.size());
1864  std::copy(vAddedNodes.cbegin(), vAddedNodes.cend(), std::back_inserter(lAddresses));
1865  }
1866 
1867 
1868  // Build a map of all already connected addresses (by IP:port and by name) to inbound/outbound and resolved CService
1869  std::map<CService, bool> mapConnected;
1870  std::map<std::string, std::pair<bool, CService> > mapConnectedByName;
1871  {
1872  LOCK(cs_vNodes);
1873  for (const CNode* pnode : vNodes) {
1874  if (pnode->addr.IsValid()) {
1875  mapConnected[pnode->addr] = pnode->fInbound;
1876  }
1877  std::string addrName = pnode->GetAddrName();
1878  if (!addrName.empty()) {
1879  mapConnectedByName[std::move(addrName)] = std::make_pair(pnode->fInbound, static_cast<const CService&>(pnode->addr));
1880  }
1881  }
1882  }
1883 
1884  for (const std::string& strAddNode : lAddresses) {
1885  CService service(LookupNumeric(strAddNode, Params().GetDefaultPort()));
1886  AddedNodeInfo addedNode{strAddNode, CService(), false, false};
1887  if (service.IsValid()) {
1888  // strAddNode is an IP:port
1889  auto it = mapConnected.find(service);
1890  if (it != mapConnected.end()) {
1891  addedNode.resolvedAddress = service;
1892  addedNode.fConnected = true;
1893  addedNode.fInbound = it->second;
1894  }
1895  } else {
1896  // strAddNode is a name
1897  auto it = mapConnectedByName.find(strAddNode);
1898  if (it != mapConnectedByName.end()) {
1899  addedNode.resolvedAddress = it->second.second;
1900  addedNode.fConnected = true;
1901  addedNode.fInbound = it->second.first;
1902  }
1903  }
1904  ret.emplace_back(std::move(addedNode));
1905  }
1906 
1907  return ret;
1908 }
1909 
1911 {
1912  while (true) {
1913  CSemaphoreGrant grant(*semAddnode);
1914  std::vector<AddedNodeInfo> vInfo = GetAddedNodeInfo();
1915  bool tried = false;
1916  for (const AddedNodeInfo& info : vInfo) {
1917  if (!info.fConnected) {
1918  if (!grant.TryAcquire()) {
1919  // If we've used up our semaphore and need a new one, lets not wait here since while we are waiting
1920  // the addednodeinfo state might change.
1921  break;
1922  }
1923  tried = true;
1924  CAddress addr(CService(), NODE_NONE);
1925  OpenNetworkConnection(addr, false, &grant, info.strAddedNode.c_str(), false, false, true);
1926  if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
1927  return;
1928  }
1929  }
1930  // Retry every 60 seconds if a connection was attempted, otherwise two seconds
1931  if (!interruptNet.sleep_for(std::chrono::seconds(tried ? 60 : 2)))
1932  return;
1933  }
1934 }
1935 
1936 // if successful, this moves the passed grant to the constructed node
1937 void CConnman::OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant* grantOutbound, const char* pszDest, bool fOneShot, bool fFeeler, bool fAddnode, bool masternode_connection, bool masternode_probe_connection)
1938 {
1939  //
1940  // Initiate outbound network connection
1941  //
1942  if (interruptNet || !fNetworkActive) {
1943  return;
1944  }
1945  if (!pszDest) {
1946  if (IsLocal(addrConnect) ||
1947  FindNode(static_cast<CNetAddr>(addrConnect)) || IsBanned(addrConnect) ||
1948  FindNode(addrConnect.ToStringIPPort()))
1949  return;
1950  } else {
1951  CNode* pnode = FindNode(pszDest);
1952  if (pnode) {
1953  // If this is a mnauth connection and the node is already connected normally,
1954  // disconnect it and open a new connection
1955  if (masternode_connection && !pnode->m_masternode_connection) {
1956  pnode->fDisconnect = true;
1957  } else {
1958  return;
1959  }
1960  }
1961  }
1962 
1963  CNode* pnode = ConnectNode(addrConnect, pszDest, fCountFailure, fAddnode);
1964 
1965  if (!pnode)
1966  return;
1967  if (grantOutbound)
1968  grantOutbound->MoveTo(pnode->grantOutbound);
1969  if (fOneShot)
1970  pnode->fOneShot = true;
1971  if (fFeeler)
1972  pnode->fFeeler = true;
1973  if (fAddnode)
1974  pnode->fAddnode = true;
1975  if (masternode_connection)
1976  pnode->m_masternode_connection = true;
1977  if (masternode_probe_connection)
1978  pnode->m_masternode_probe_connection = true;
1979 
1980  m_msgproc->InitializeNode(pnode);
1981  {
1982  LOCK(cs_vNodes);
1983  vNodes.push_back(pnode);
1984  }
1985 }
1986 
1988 {
1989  int64_t nLastSendMessagesTimeMasternodes = 0;
1990 
1991  while (!flagInterruptMsgProc) {
1992  std::vector<CNode*> vNodesCopy = CopyNodeVector();
1993 
1994  bool fMoreWork = false;
1995 
1996  // Don't send other messages to quorum nodes too often
1997  bool fSkipSendMessagesForMasternodes = true;
1998  if (GetTimeMillis() - nLastSendMessagesTimeMasternodes >= 100) {
1999  fSkipSendMessagesForMasternodes = false;
2000  nLastSendMessagesTimeMasternodes = GetTimeMillis();
2001  }
2002 
2003  for (CNode* pnode : vNodesCopy) {
2004  if (pnode->fDisconnect)
2005  continue;
2006 
2007  // Receive messages
2008  bool fMoreNodeWork = m_msgproc->ProcessMessages(pnode, flagInterruptMsgProc);
2009  fMoreWork |= (fMoreNodeWork && !pnode->fPauseSend);
2011  return;
2012 
2013  // Send messages
2014  if (!fSkipSendMessagesForMasternodes || !pnode->m_masternode_connection) {
2015  LOCK(pnode->cs_sendProcessing);
2017  }
2018 
2020  return;
2021  }
2022 
2023 
2024  ReleaseNodeVector(vNodesCopy);
2025 
2026  std::unique_lock<std::mutex> lock(mutexMsgProc);
2027  if (!fMoreWork) {
2028  condMsgProc.wait_until(lock, std::chrono::steady_clock::now() + std::chrono::milliseconds(100), [this] { return fMsgProcWake; });
2029  }
2030  fMsgProcWake = false;
2031  }
2032 }
2033 
2034 bool CConnman::BindListenPort(const CService& addrBind, std::string& strError, bool fWhitelisted)
2035 {
2036  strError = "";
2037  int nOne = 1;
2038 
2039  // Create socket for listening for incoming connections
2040  struct sockaddr_storage sockaddr;
2041  socklen_t len = sizeof(sockaddr);
2042  if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
2043  strError = strprintf("Error: Bind address family for %s not supported", addrBind.ToString());
2044  LogPrintf("%s\n", strError);
2045  return false;
2046  }
2047 
2048  SOCKET hListenSocket = CreateSocket(addrBind);
2049  if (hListenSocket == INVALID_SOCKET) {
2050  strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError()));
2051  LogPrintf("%s\n", strError);
2052  return false;
2053  }
2054 
2055 #ifndef WIN32
2056  // Allow binding if the port is still in TIME_WAIT state after
2057  // the program was closed and restarted. Not an issue on windows!
2058  setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
2059 #endif
2060 
2061  // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
2062  // and enable it by default or not. Try to enable it, if possible.
2063  if (addrBind.IsIPv6()) {
2064 #ifdef IPV6_V6ONLY
2065  setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (sockopt_arg_type)&nOne, sizeof(int));
2066 #endif
2067 #ifdef WIN32
2068  int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED;
2069  setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, (const char*)&nProtLevel, sizeof(int));
2070 #endif
2071  }
2072 
2073  if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) {
2074  int nErr = WSAGetLastError();
2075  if (nErr == WSAEADDRINUSE)
2076  strError = strprintf(_("Unable to bind to %s on this computer. %s is probably already running."), addrBind.ToString(), PACKAGE_NAME);
2077  else
2078  strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToString(), NetworkErrorString(nErr));
2079  LogPrintf("%s\n", strError);
2080  CloseSocket(hListenSocket);
2081  return false;
2082  }
2083  LogPrintf("Bound to %s\n", addrBind.ToString());
2084 
2085  // Listen for incoming connections
2086  if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR) {
2087  strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError()));
2088  LogPrintf("%s\n", strError);
2089  CloseSocket(hListenSocket);
2090  return false;
2091  }
2092 
2093  vhListenSocket.emplace_back(hListenSocket, fWhitelisted);
2094 
2095  if (addrBind.IsRoutable() && fDiscover && !fWhitelisted)
2096  AddLocal(addrBind, LOCAL_BIND);
2097 
2098  return true;
2099 }
2100 
2101 void Discover()
2102 {
2103  if (!fDiscover)
2104  return;
2105 
2106 #ifdef WIN32
2107  // Get local host IP
2108  char pszHostName[256] = "";
2109  if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) {
2110  std::vector<CNetAddr> vaddr;
2111  if (LookupHost(pszHostName, vaddr, 0, true)) {
2112  for (const CNetAddr& addr : vaddr) {
2113  if (AddLocal(addr, LOCAL_IF))
2114  LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToString());
2115  }
2116  }
2117  }
2118 #elif (HAVE_DECL_GETIFADDRS && HAVE_DECL_FREEIFADDRS)
2119  // Get local host ip
2120  struct ifaddrs* myaddrs;
2121  if (getifaddrs(&myaddrs) == 0) {
2122  for (struct ifaddrs* ifa = myaddrs; ifa != nullptr; ifa = ifa->ifa_next) {
2123  if (ifa->ifa_addr == nullptr) continue;
2124  if ((ifa->ifa_flags & IFF_UP) == 0) continue;
2125  if (strcmp(ifa->ifa_name, "lo") == 0) continue;
2126  if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
2127  if (ifa->ifa_addr->sa_family == AF_INET) {
2128  struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
2129  CNetAddr addr(s4->sin_addr);
2130  if (AddLocal(addr, LOCAL_IF))
2131  LogPrintf("%s: IPv4 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
2132  } else if (ifa->ifa_addr->sa_family == AF_INET6) {
2133  struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
2134  CNetAddr addr(s6->sin6_addr);
2135  if (AddLocal(addr, LOCAL_IF))
2136  LogPrintf("%s: IPv6 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
2137  }
2138  }
2139  freeifaddrs(myaddrs);
2140  }
2141 #endif
2142 }
2143 
2145 {
2146  LogPrint(BCLog::NET, "SetNetworkActive: %s\n", active);
2147 
2148  if (fNetworkActive == active) {
2149  return;
2150  }
2151 
2152  fNetworkActive = active;
2153 
2155 }
2156 
2157 CConnman::CConnman(uint64_t nSeed0In, uint64_t nSeed1In) : nSeed0(nSeed0In), nSeed1(nSeed1In)
2158 {
2159  setBannedIsDirty = false;
2160  fAddressesInitialized = false;
2161  nLastNodeId = 0;
2162  nPrevNodeCount = 0;
2163  nSendBufferMaxSize = 0;
2164  nReceiveFloodSize = 0;
2165  flagInterruptMsgProc = false;
2166 
2167  Options connOptions;
2168  Init(connOptions);
2169  // init tier two connections manager
2170  m_tiertwo_conn_man = std::make_unique<TierTwoConnMan>(this);
2171 }
2172 
2174 {
2175  return nLastNodeId.fetch_add(1, std::memory_order_relaxed);
2176 }
2177 
2178 bool CConnman::Bind(const CService& addr, unsigned int flags) {
2179  if (!(flags & BF_EXPLICIT) && !IsReachable(addr))
2180  return false;
2181  std::string strError;
2182  if (!BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) {
2183  if ((flags & BF_REPORT_ERROR) && clientInterface) {
2185  }
2186  return false;
2187  }
2188  return true;
2189 }
2190 
2191 bool CConnman::InitBinds(const std::vector<CService>& binds, const std::vector<CService>& whiteBinds) {
2192  bool fBound = false;
2193  for (const auto& addrBind : binds) {
2194  fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
2195  }
2196  for (const auto& addrBind : whiteBinds) {
2197  fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
2198  }
2199  if (binds.empty() && whiteBinds.empty()) {
2200  struct in_addr inaddr_any;
2201  inaddr_any.s_addr = INADDR_ANY;
2202  fBound |= Bind(CService((in6_addr)IN6ADDR_ANY_INIT, GetListenPort()), BF_NONE);
2203  fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
2204  }
2205  return fBound;
2206 }
2207 
2208 bool CConnman::Start(CScheduler& scheduler, const Options& connOptions)
2209 {
2210  Init(connOptions);
2211 
2212  {
2214  nTotalBytesRecv = 0;
2215  }
2216  {
2218  nTotalBytesSent = 0;
2219  }
2220 
2221  if (fListen && !InitBinds(connOptions.vBinds, connOptions.vWhiteBinds)) {
2222  if (clientInterface) {
2224  _("Failed to listen on any port. Use -listen=0 if you want this."),
2226  }
2227  return false;
2228  }
2229 
2230  for (const auto& strDest : connOptions.vSeedNodes) {
2231  AddOneShot(strDest);
2232  }
2233 
2234  if (clientInterface)
2235  clientInterface->InitMessage(_("Loading addresses..."));
2236  m_msgproc = connOptions.m_msgproc;
2237  // Load addresses from peers.dat
2238  int64_t nStart = GetTimeMillis();
2239  {
2240  CAddrDB adb;
2241  if (adb.Read(addrman))
2242  LogPrintf("Loaded %i addresses from peers.dat %dms\n", addrman.size(), GetTimeMillis() - nStart);
2243  else {
2244  addrman.Clear(); // Addrman can be in an inconsistent state after failure, reset it
2245  LogPrintf("Invalid or missing peers.dat; recreating\n");
2246  DumpAddresses();
2247  }
2248  }
2249  if (clientInterface)
2250  clientInterface->InitMessage(_("Loading banlist..."));
2251  // Load addresses from banlist.dat
2252  nStart = GetTimeMillis();
2253  CBanDB bandb;
2254  banmap_t banmap;
2255  if (bandb.Read(banmap)) {
2256  SetBanned(banmap); // thread save setter
2257  SetBannedSetDirty(false); // no need to write down, just read data
2258  SweepBanned(); // sweep out unused entries
2259 
2260  LogPrint(BCLog::NET, "Loaded %d banned node ips/subnets from banlist.dat %dms\n",
2261  banmap.size(), GetTimeMillis() - nStart);
2262  } else {
2263  LogPrintf("Invalid or missing banlist.dat; recreating\n");
2264  SetBannedSetDirty(true); // force write
2265  DumpBanlist();
2266  }
2267 
2268  // Initialize random numbers. Even when rand() is only usable for trivial use-cases most nodes should have a different
2269  // seed after all the file-IO done at this point. Should be good enough even when nodes are started via scripts.
2270  srand(time(nullptr));
2271 
2272  fAddressesInitialized = true;
2273 
2274  if (semOutbound == nullptr) {
2275  // initialize semaphore
2276  semOutbound = std::make_unique<CSemaphore>(std::min((nMaxOutbound + nMaxFeeler), nMaxConnections));
2277  }
2278  if (semAddnode == nullptr) {
2279  // initialize semaphore
2280  semAddnode = std::make_unique<CSemaphore>(nMaxAddnode);
2281  }
2282 
2283  //
2284  // Start threads
2285  //
2286  assert(m_msgproc);
2287  InterruptSocks5(false);
2288  interruptNet.reset();
2289  flagInterruptMsgProc = false;
2290 
2291  {
2292  std::unique_lock<std::mutex> lock(mutexMsgProc);
2293  fMsgProcWake = false;
2294  }
2295 
2296 #ifdef USE_WAKEUP_PIPE
2297  if (pipe(wakeupPipe) != 0) {
2298  wakeupPipe[0] = wakeupPipe[1] = -1;
2299  LogPrint(BCLog::NET, "pipe() for wakeupPipe failed\n");
2300  } else {
2301  int fFlags = fcntl(wakeupPipe[0], F_GETFL, 0);
2302  if (fcntl(wakeupPipe[0], F_SETFL, fFlags | O_NONBLOCK) == -1) {
2303  LogPrint(BCLog::NET, "fcntl for O_NONBLOCK on wakeupPipe failed\n");
2304  }
2305  fFlags = fcntl(wakeupPipe[1], F_GETFL, 0);
2306  if (fcntl(wakeupPipe[1], F_SETFL, fFlags | O_NONBLOCK) == -1) {
2307  LogPrint(BCLog::NET, "fcntl for O_NONBLOCK on wakeupPipe failed\n");
2308  }
2309  }
2310 #endif
2311 
2312  // Send and receive from sockets, accept connections
2313  threadSocketHandler = std::thread(&TraceThread<std::function<void()> >, "net", std::function<void()>(std::bind(&CConnman::ThreadSocketHandler, this)));
2314 
2315  if (!gArgs.GetBoolArg("-dnsseed", true))
2316  LogPrintf("DNS seeding disabled\n");
2317  else
2318  threadDNSAddressSeed = std::thread(&TraceThread<std::function<void()> >, "dnsseed", std::function<void()>(std::bind(&CConnman::ThreadDNSAddressSeed, this)));
2319 
2320  // Initiate outbound connections from -addnode
2321  threadOpenAddedConnections = std::thread(&TraceThread<std::function<void()> >, "addcon", std::function<void()>(std::bind(&CConnman::ThreadOpenAddedConnections, this)));
2322 
2323  // Start tier two connection manager
2324  if (m_tiertwo_conn_man) {
2326  opts.m_has_specified_outgoing = !connOptions.m_specified_outgoing.empty();
2327  m_tiertwo_conn_man->start(scheduler, opts);
2328  }
2329 
2330  if (connOptions.m_use_addrman_outgoing && !connOptions.m_specified_outgoing.empty()) {
2331  if (clientInterface) {
2333  _("Cannot provide specific connections and have addrman find outgoing connections at the same."),
2335  }
2336  return false;
2337  }
2338  if (connOptions.m_use_addrman_outgoing || !connOptions.m_specified_outgoing.empty()) {
2339  threadOpenConnections = std::thread(&TraceThread<std::function<void()> >, "opencon", std::function<void()>(
2340  std::bind(&CConnman::ThreadOpenConnections, this, connOptions.m_specified_outgoing)));
2341  }
2342 
2343  // Process messages
2344  threadMessageHandler = std::thread(&TraceThread<std::function<void()> >, "msghand", std::function<void()>(std::bind(&CConnman::ThreadMessageHandler, this)));
2345 
2346  // Dump network addresses
2348 
2349  return true;
2350 }
2351 
2353 {
2354 public:
2356 
2358  {
2359 #ifdef WIN32
2360  // Shutdown Windows Sockets
2361  WSACleanup();
2362 #endif
2363  }
2364 }
2366 
2368 {
2369  // Explicit call to destructor of CNetCleanup because it's not implicitly called
2370  // when the wallet is restarted from within the wallet itself.
2371  CNetCleanup* tmp = new CNetCleanup();
2372  delete tmp; // Stroustrup's gonna kill me for that
2373 }
2374 
2376 {
2377  {
2378  std::lock_guard<std::mutex> lock(mutexMsgProc);
2379  flagInterruptMsgProc = true;
2380  }
2381  condMsgProc.notify_all();
2382 
2383  interruptNet();
2384  if (m_tiertwo_conn_man) m_tiertwo_conn_man->interrupt();
2385  InterruptSocks5(true);
2386 
2387  if (semOutbound) {
2388  for (int i=0; i<(nMaxOutbound + nMaxFeeler); i++) {
2389  semOutbound->post();
2390  }
2391  }
2392 
2393  if (semAddnode) {
2394  for (int i=0; i<nMaxAddnode; i++) {
2395  semAddnode->post();
2396  }
2397  }
2398 }
2399 
2401 {
2402  if (threadMessageHandler.joinable())
2403  threadMessageHandler.join();
2404  if (threadOpenConnections.joinable())
2405  threadOpenConnections.join();
2406  if (threadOpenAddedConnections.joinable())
2408  if (threadDNSAddressSeed.joinable())
2409  threadDNSAddressSeed.join();
2410  if (threadSocketHandler.joinable())
2411  threadSocketHandler.join();
2412  // Stop tier two connection manager
2414 
2416  {
2417  DumpData();
2418  fAddressesInitialized = false;
2419  }
2420 
2421  // Close sockets
2422  for(CNode* pnode : vNodes)
2423  pnode->CloseSocketDisconnect();
2424  for(ListenSocket& hListenSocket : vhListenSocket)
2425  if (hListenSocket.socket != INVALID_SOCKET)
2426  if (!CloseSocket(hListenSocket.socket))
2427  LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError()));
2428 
2429  // clean up some globals (to help leak detection)
2430  for(CNode* pnode : vNodes) {
2431  DeleteNode(pnode);
2432  }
2433  for(CNode* pnode : vNodesDisconnected) {
2434  DeleteNode(pnode);
2435  }
2436  vNodes.clear();
2437  vNodesDisconnected.clear();
2438  vhListenSocket.clear();
2439  semOutbound.reset();
2440  semAddnode.reset();
2441 #ifdef USE_WAKEUP_PIPE
2442  if (wakeupPipe[0] != -1) close(wakeupPipe[0]);
2443  if (wakeupPipe[1] != -1) close(wakeupPipe[1]);
2444  wakeupPipe[0] = wakeupPipe[1] = -1;
2445 #endif
2446 }
2447 
2449 {
2450  assert(pnode);
2451  bool fUpdateConnectionTime = false;
2452  m_msgproc->FinalizeNode(pnode->GetId(), fUpdateConnectionTime);
2453  if (fUpdateConnectionTime) {
2454  addrman.Connected(pnode->addr);
2455  }
2456  delete pnode;
2457 }
2458 
2460 {
2461  Interrupt();
2462  Stop();
2463 }
2464 
2465 void CConnman::SetServices(const CService &addr, ServiceFlags nServices)
2466 {
2467  addrman.SetServices(addr, nServices);
2468 }
2469 
2471 {
2472  addrman.Good(addr);
2473 }
2474 
2475 void CConnman::AddNewAddress(const CAddress& addr, const CAddress& addrFrom, int64_t nTimePenalty)
2476 {
2477  addrman.Add(addr, addrFrom, nTimePenalty);
2478 }
2479 
2480 bool CConnman::AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty)
2481 {
2482  return addrman.Add(vAddr, addrFrom, nTimePenalty);
2483 }
2484 
2485 std::vector<CAddress> CConnman::GetAddresses(size_t max_addresses, size_t max_pct, Optional<Network> network)
2486 {
2487  return addrman.GetAddr(max_addresses, max_pct, network);
2488 }
2489 
2490 bool CConnman::AddNode(const std::string& strNode)
2491 {
2493  for (const std::string& it : vAddedNodes) {
2494  if (strNode == it) return false;
2495  }
2496 
2497  vAddedNodes.push_back(strNode);
2498  return true;
2499 }
2500 
2501 bool CConnman::RemoveAddedNode(const std::string& strNode)
2502 {
2504  for(std::vector<std::string>::iterator it = vAddedNodes.begin(); it != vAddedNodes.end(); ++it) {
2505  if (strNode == *it) {
2506  vAddedNodes.erase(it);
2507  return true;
2508  }
2509  }
2510  return false;
2511 }
2512 
2514 {
2515  return nMaxOutbound;
2516 }
2517 
2519 {
2520  LOCK(cs_vNodes);
2521  if (flags == CConnman::CONNECTIONS_ALL) // Shortcut if we want total
2522  return vNodes.size();
2523 
2524  int nNum = 0;
2525  for (const auto& pnode : vNodes) {
2526  if (flags & (pnode->fInbound ? CONNECTIONS_IN : CONNECTIONS_OUT)) {
2527  nNum++;
2528  }
2529  }
2530 
2531  return nNum;
2532 }
2533 
2534 void CConnman::GetNodeStats(std::vector<CNodeStats>& vstats)
2535 {
2536  vstats.clear();
2537  LOCK(cs_vNodes);
2538  vstats.reserve(vNodes.size());
2539  for (CNode* pnode : vNodes) {
2540  vstats.emplace_back();
2541  pnode->copyStats(vstats.back(), addrman.m_asmap);
2542  }
2543 }
2544 
2545 bool CConnman::DisconnectNode(const std::string& strNode)
2546 {
2547  LOCK(cs_vNodes);
2548  if (CNode* pnode = FindNode(strNode)) {
2549  pnode->fDisconnect = true;
2550  return true;
2551  }
2552  return false;
2553 }
2554 
2556 {
2557  LOCK(cs_vNodes);
2558  for(CNode* pnode : vNodes) {
2559  if (id == pnode->GetId()) {
2560  pnode->fDisconnect = true;
2561  return true;
2562  }
2563  }
2564  return false;
2565 }
2566 
2567 void CConnman::RelayInv(CInv& inv, int minProtoVersion)
2568 {
2569  LOCK(cs_vNodes);
2570  for (CNode* pnode : vNodes){
2571  if (!pnode->fSuccessfullyConnected) continue;
2572  if ((pnode->nServices == NODE_BLOOM_WITHOUT_MN) && inv.IsMasterNodeType()) continue;
2573  if (!pnode->CanRelay()) continue;
2574  if (pnode->nVersion >= minProtoVersion)
2575  pnode->PushInventory(inv);
2576  }
2577 }
2578 
2579 void CConnman::RemoveAskFor(const uint256& invHash, int invType)
2580 {
2581  mapAlreadyAskedFor.erase(CInv(invType, invHash));
2582 
2583  LOCK(cs_vNodes);
2584  for (const auto& pnode : vNodes) {
2585  pnode->AskForInvReceived(invHash);
2586  }
2587 }
2588 
2590 {
2591  if (!pnode->m_masternode_iqr_connection && pnode->m_masternode_connection &&
2592  m_tiertwo_conn_man->isMasternodeQuorumRelayMember(WITH_LOCK(pnode->cs_mnauth, return pnode->verifiedProRegTxHash))) {
2593  pnode->m_masternode_iqr_connection = true;
2594  }
2595 }
2596 
2597 void CConnman::RecordBytesRecv(uint64_t bytes)
2598 {
2600  nTotalBytesRecv += bytes;
2601 }
2602 
2603 void CConnman::RecordBytesSent(uint64_t bytes)
2604 {
2606  nTotalBytesSent += bytes;
2607 }
2608 
2610 {
2612  return nTotalBytesRecv;
2613 }
2614 
2616 {
2618  return nTotalBytesSent;
2619 }
2620 
2622 {
2623  return nLocalServices;
2624 }
2625 
2626 void CConnman::SetBestHeight(int height)
2627 {
2628  nBestHeight.store(height, std::memory_order_release);
2629 }
2630 
2632 {
2633  return nBestHeight.load(std::memory_order_acquire);
2634 }
2635 
2636 unsigned int CConnman::GetReceiveFloodSize() const { return nReceiveFloodSize; }
2637 unsigned int CConnman::GetSendBufferSize() const{ return nSendBufferMaxSize; }
2638 
2639 CNode::CNode(NodeId idIn, ServiceFlags nLocalServicesIn, int nMyStartingHeightIn, SOCKET hSocketIn, const CAddress& addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const std::string& addrNameIn, bool fInboundIn) :
2640  nTimeConnected(GetSystemTimeInSeconds()),
2641  addr(addrIn),
2642  fInbound(fInboundIn),
2643  nKeyedNetGroup(nKeyedNetGroupIn),
2644  addrKnown(5000, 0.001),
2645  filterInventoryKnown(50000, 0.000001),
2646  id(idIn),
2647  nLocalHostNonce(nLocalHostNonceIn),
2648  nLocalServices(nLocalServicesIn),
2649  nMyStartingHeight(nMyStartingHeightIn),
2650  nSendVersion(0)
2651 {
2652  nServices = NODE_NONE;
2654  hSocket = hSocketIn;
2655  nRecvVersion = INIT_PROTO_VERSION;
2656  nLastSend = 0;
2657  nLastRecv = 0;
2658  nSendBytes = 0;
2659  nRecvBytes = 0;
2660  nTimeOffset = 0;
2661  addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
2662  nVersion = 0;
2663  strSubVer = "";
2664  fWhitelisted = false;
2665  fOneShot = false;
2666  fAddnode = false;
2667  m_masternode_connection = false;
2668  fClient = false; // set by version message
2669  fFeeler = false;
2670  fSuccessfullyConnected = false;
2671  fDisconnect = false;
2672  nRefCount = 0;
2673  nSendSize = 0;
2674  nSendOffset = 0;
2676  nStartingHeight = -1;
2678  fSendMempool = false;
2679  fGetAddr = false;
2680  fRelayTxes = false;
2681  pfilter = std::make_unique<CBloomFilter>();
2682  timeLastMempoolReq = 0;
2683  nPingNonceSent = 0;
2684  nPingUsecStart = 0;
2685  nPingUsecTime = 0;
2686  fPingQueued = false;
2687  nMinPingUsecTime = std::numeric_limits<int64_t>::max();
2688  fPauseRecv = false;
2689  fPauseSend = false;
2690  nProcessQueueSize = 0;
2691 
2692  for (const std::string &msg : getAllNetMessageTypes())
2693  mapRecvBytesPerMsgCmd[msg] = 0;
2694  mapRecvBytesPerMsgCmd[NET_MESSAGE_COMMAND_OTHER] = 0;
2695 
2696  if (fLogIPs)
2697  LogPrint(BCLog::NET, "Added connection to %s peer=%d\n", addrName, id);
2698  else
2699  LogPrint(BCLog::NET, "Added connection peer=%d\n", id);
2700 }
2701 
2703 {
2705 }
2706 
2707 void CNode::AskFor(const CInv& inv, int64_t doubleRequestDelay)
2708 {
2709  if (mapAskFor.size() > MAPASKFOR_MAX_SZ || setAskFor.size() > SETASKFOR_MAX_SZ)
2710  return;
2711  // a peer may not have multiple non-responded queue positions for a single inv item
2712  if (!setAskFor.insert(inv.hash).second)
2713  return;
2714 
2715  // We're using mapAskFor as a priority queue,
2716  // the key is the earliest time the request can be sent
2717  int64_t nRequestTime;
2719  if (it != mapAlreadyAskedFor.end())
2720  nRequestTime = it->second;
2721  else
2722  nRequestTime = 0;
2723  LogPrint(BCLog::NET, "askfor %s %d (%s) peer=%d\n", inv.ToString(), nRequestTime, FormatISO8601Time(nRequestTime / 1000000), id);
2724 
2725  // Make sure not to reuse time indexes to keep things in the same order
2726  int64_t nNow = GetTimeMicros() - 1000000;
2727  static int64_t nLastTime;
2728  ++nLastTime;
2729  nNow = std::max(nNow, nLastTime);
2730  nLastTime = nNow;
2731 
2732  // Each retry is 2 minutes after the last
2733  nRequestTime = std::max(nRequestTime + doubleRequestDelay, nNow);
2734  if (it != mapAlreadyAskedFor.end())
2735  mapAlreadyAskedFor.update(it, nRequestTime);
2736  else
2737  mapAlreadyAskedFor.insert(std::make_pair(inv, nRequestTime));
2738  mapAskFor.insert(std::make_pair(nRequestTime, inv));
2739 }
2740 
2741 void CNode::AskForInvReceived(const uint256& invHash)
2742 {
2743  setAskFor.erase(invHash);
2744  for (auto it = mapAskFor.begin(); it != mapAskFor.end();) {
2745  if (it->second.hash == invHash) {
2746  it = mapAskFor.erase(it);
2747  } else {
2748  ++it;
2749  }
2750  }
2751 }
2752 
2754 {
2755  return pnode && pnode->fSuccessfullyConnected && !pnode->fDisconnect;
2756 }
2757 
2758 void CConnman::PushMessage(CNode* pnode, CSerializedNetMsg&& msg, bool allowOptimisticSend)
2759 {
2760  size_t nMessageSize = msg.data.size();
2761  size_t nTotalSize = nMessageSize + CMessageHeader::HEADER_SIZE;
2762  LogPrint(BCLog::NET, "sending %s (%d bytes) peer=%d\n", SanitizeString(msg.command.c_str()), nMessageSize, pnode->GetId());
2763 
2764  std::vector<unsigned char> serializedHeader;
2765  serializedHeader.reserve(CMessageHeader::HEADER_SIZE);
2766  uint256 hash = Hash(msg.data.data(), msg.data.data() + nMessageSize);
2767  CMessageHeader hdr(Params().MessageStart(), msg.command.c_str(), nMessageSize);
2769 
2770  CVectorWriter{SER_NETWORK, INIT_PROTO_VERSION, serializedHeader, 0, hdr};
2771 
2772  size_t nBytesSent = 0;
2773  {
2774  LOCK(pnode->cs_vSend);
2775  bool hasPendingData = !pnode->vSendMsg.empty();
2776  bool optimisticSend(allowOptimisticSend && pnode->vSendMsg.empty());
2777 
2778  //log total amount of bytes per command
2779  pnode->mapSendBytesPerMsgCmd[msg.command] += nTotalSize;
2780  pnode->nSendSize += nTotalSize;
2781 
2782  if (pnode->nSendSize > nSendBufferMaxSize)
2783  pnode->fPauseSend = true;
2784  pnode->vSendMsg.push_back(std::move(serializedHeader));
2785  if (nMessageSize)
2786  pnode->vSendMsg.push_back(std::move(msg.data));
2787 
2788  // If write queue empty, attempt "optimistic write"
2789  if (optimisticSend == true)
2790  nBytesSent = SocketSendData(pnode);
2791  // wake up select() call in case there was no pending data before (so it was not selecting this socket for sending)
2792  else if (!hasPendingData && wakeupSelectNeeded)
2793  WakeSelect();
2794  }
2795  if (nBytesSent)
2796  RecordBytesSent(nBytesSent);
2797 }
2798 
2799 bool CConnman::ForNode(NodeId id, std::function<bool(CNode* pnode)> func)
2800 {
2801  CNode* found = nullptr;
2802  LOCK(cs_vNodes);
2803  for (auto&& pnode : vNodes) {
2804  if(pnode->GetId() == id) {
2805  found = pnode;
2806  break;
2807  }
2808  }
2809  return found != nullptr && NodeFullyConnected(found) && func(found);
2810 }
2811 
2812 bool CConnman::ForNode(const CService& addr, const std::function<bool(const CNode* pnode)>& cond, const std::function<bool(CNode* pnode)>& func)
2813 {
2814  CNode* found = nullptr;
2815  LOCK(cs_vNodes);
2816  for (auto&& pnode : vNodes) {
2817  if(static_cast<CService>(pnode->addr) == addr) {
2818  found = pnode;
2819  break;
2820  }
2821  }
2822  return found != nullptr && cond(found) && func(found);
2823 }
2824 
2826 {
2827  return FindNode(addr.ToStringIPPort());
2828 }
2829 
2831 {
2832  return ConnectNode(addrConnect, nullptr, true, true);
2833 }
2834 
2835 // valid, reachable and routable address (except for RegTest)
2836 bool validateMasternodeIP(const std::string& addrStr)
2837 {
2838  CNetAddr resolved;
2839  if (LookupHost(addrStr, resolved, false)) {
2840  return ((IsReachable(resolved) && resolved.IsRoutable()) ||
2841  (Params().IsRegTestNet() && resolved.IsValid()));
2842  }
2843  return false;
2844 }
2845 
2846 int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds) {
2847  return nNow + (int64_t)(log1p(GetRand(1ULL << 48) * -0.0000000000000035527136788 /* -1/2^48 */) * average_interval_seconds * -1000000.0 + 0.5);
2848 }
2849 
2850 std::vector<CNode*> CConnman::CopyNodeVector(std::function<bool(const CNode* pnode)> cond)
2851 {
2852  std::vector<CNode*> vecNodesCopy;
2853  LOCK(cs_vNodes);
2854  for (size_t i = 0; i < vNodes.size(); ++i) {
2855  CNode* pnode = vNodes[i];
2856  if (!cond(pnode))
2857  continue;
2858  pnode->AddRef();
2859  vecNodesCopy.push_back(pnode);
2860  }
2861  return vecNodesCopy;
2862 }
2863 
2864 std::vector<CNode*> CConnman::CopyNodeVector()
2865 {
2866  return CopyNodeVector(AllNodes);
2867 }
2868 
2869 void CConnman::ReleaseNodeVector(const std::vector<CNode*>& vecNodes)
2870 {
2871  for (size_t i = 0; i < vecNodes.size(); ++i) {
2872  CNode* pnode = vecNodes[i];
2873  pnode->Release();
2874  }
2875 }
2876 
2878 {
2879  return CSipHasher(nSeed0, nSeed1).Write(id);
2880 }
2881 
2883 {
2884  std::vector<unsigned char> vchNetGroup(ad.GetGroup(addrman.m_asmap));
2885 
2886  return GetDeterministicRandomizer(RANDOMIZER_ID_NETGROUP).Write(vchNetGroup.data(), vchNetGroup.size()).Finalize();
2887 }
2888 
CService ip(uint32_t i)
Definition: DoS_tests.cpp:39
BanReason
Definition: addrdb.h:22
@ BanReasonManuallyAdded
Definition: addrdb.h:25
std::map< CSubNet, CBanEntry > banmap_t
Definition: addrdb.h:71
const CChainParams & Params()
Return the currently selected parameters.
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:449
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:465
Access to the (IP) address database (peers.dat)
Definition: addrdb.h:75
bool Write(const CAddrMan &addr)
Definition: addrdb.cpp:143
bool Read(CAddrMan &addr)
Definition: addrdb.cpp:148
Extended statistics about a CAddress.
Definition: addrman.h:37
int64_t nLastTry
last try whatsoever by us (memory only)
Definition: addrman.h:40
bool Add(const CAddress &addr, const CNetAddr &source, int64_t nTimePenalty=0)
Add a single address.
Definition: addrman.h:623
size_t size() const
Return the number of (unique) addresses in all tables.
Definition: addrman.h:603
void Attempt(const CService &addr, bool fCountFailure, int64_t nTime=GetAdjustedTime())
Mark an entry as connection attempted to.
Definition: addrman.h:661
void Clear()
Definition: addrman.h:568
CAddrInfo Select(bool newOnly=false)
Choose an address to connect to.
Definition: addrman.h:695
void ResolveCollisions()
See if any to-be-evicted tried table entries have been tested and if so resolve the collisions.
Definition: addrman.h:670
CAddrInfo SelectTriedCollision()
Randomly select an address in tried that another address is attempting to evict.
Definition: addrman.h:679
void Connected(const CService &addr, int64_t nTime=GetAdjustedTime())
Mark an entry as currently-connected-to.
Definition: addrman.h:727
void SetServices(const CService &addr, ServiceFlags nServices)
Definition: addrman.h:735
std::vector< bool > m_asmap
Definition: addrman.h:317
void Good(const CService &addr, bool test_before_evict=true, int64_t nTime=GetAdjustedTime())
Mark an entry as accessible.
Definition: addrman.h:652
std::vector< CAddress > GetAddr(size_t max_addresses, size_t max_pct, Optional< Network > network)
Return all or many randomly selected addresses, optionally by network.
Definition: addrman.h:714
A CService with information about it as peer.
Definition: protocol.h:338
ServiceFlags nServices
Serialized as uint64_t in V1, and as CompactSize in V2.
Definition: protocol.h:430
uint32_t nTime
Always included in serialization, except in the network format on INIT_PROTO_VERSION.
Definition: protocol.h:428
Access to the banlist database (banlist.dat)
Definition: addrdb.h:88
bool Write(const banmap_t &banSet)
Definition: addrdb.cpp:128
bool Read(banmap_t &banSet)
Definition: addrdb.cpp:133
Definition: addrdb.h:29
uint8_t banReason
Definition: addrdb.h:35
int64_t nBanUntil
Definition: addrdb.h:34
void resize(size_type n, value_type c=0)
Definition: streams.h:167
size_type size() const
Definition: streams.h:165
int GetDefaultPort() const
Definition: chainparams.h:74
const std::vector< CDNSSeedData > & DNSSeeds() const
Definition: chainparams.h:92
bool IsRegTestNet() const
Definition: chainparams.h:98
boost::signals2::signal< void(const std::string &message)> InitMessage
Progress message during initialization.
Definition: guiinterface.h:87
boost::signals2::signal< void(int newNumConnections)> NotifyNumConnectionsChanged
Number of network connections changed.
Definition: guiinterface.h:90
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: guiinterface.h:84
boost::signals2::signal< void(void)> BannedListChanged
Banlist did change.
Definition: guiinterface.h:108
boost::signals2::signal< void(bool networkActive)> NotifyNetworkActiveChanged
Network activity state changed.
Definition: guiinterface.h:93
std::condition_variable condMsgProc
Definition: net.h:494
void SweepBanned()
clean unused entries (if bantime has expired)
Definition: net.cpp:586
std::thread threadMessageHandler
Definition: net.h:510
void ThreadOpenAddedConnections()
Definition: net.cpp:1910
int GetBestHeight() const
Definition: net.cpp:2631
void ReleaseNodeVector(const std::vector< CNode * > &vecNodes)
Definition: net.cpp:2869
void SocketHandler()
Definition: net.cpp:1438
void ProcessOneShot()
Definition: net.cpp:1684
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:2799
void DeleteNode(CNode *pnode)
Definition: net.cpp:2448
bool setBannedIsDirty
Definition: net.h:459
bool AddNewAddresses(const std::vector< CAddress > &vAddr, const CAddress &addrFrom, int64_t nTimePenalty=0)
Definition: net.cpp:2480
std::unique_ptr< TierTwoConnMan > m_tiertwo_conn_man
Definition: net.h:512
std::mutex mutexMsgProc
Definition: net.h:495
RecursiveMutex cs_vNodes
Definition: net.h:468
ServiceFlags nLocalServices
Services this instance offers.
Definition: net.h:473
size_t GetNodeCount(NumConnections num)
Definition: net.cpp:2518
void Stop()
Definition: net.cpp:2400
CAddrMan addrman
Definition: net.h:461
std::atomic< bool > flagInterruptMsgProc
Definition: net.h:496
unsigned int GetReceiveFloodSize() const
Definition: net.cpp:2636
std::list< CNode * > vNodesDisconnected
Definition: net.h:467
uint64_t GetTotalBytesRecv()
Definition: net.cpp:2609
void SetBestHeight(int height)
Definition: net.cpp:2626
void SocketEvents(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set)
Definition: net.cpp:1362
void AddNewAddress(const CAddress &addr, const CAddress &addrFrom, int64_t nTimePenalty=0)
Definition: net.cpp:2475
NodeId GetNewNodeId()
Definition: net.cpp:2173
CThreadInterrupt interruptNet
Definition: net.h:498
std::unique_ptr< CSemaphore > semAddnode
Definition: net.h:479
std::atomic< NodeId > nLastNodeId
Definition: net.h:469
void SetServices(const CService &addr, ServiceFlags nServices)
Definition: net.cpp:2465
void RecordBytesSent(uint64_t bytes)
Definition: net.cpp:2603
void Interrupt()
Definition: net.cpp:2375
std::thread threadDNSAddressSeed
Definition: net.h:506
bool Unban(const CNetAddr &ip)
Definition: net.cpp:551
std::vector< CAddress > GetAddresses(size_t max_addresses, size_t max_pct, Optional< Network > network)
Return all or many randomly selected addresses, optionally by network.
Definition: net.cpp:2485
std::deque< std::string > vOneShots
Definition: net.h:462
const uint64_t nSeed1
Definition: net.h:489
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound=nullptr, const char *strDest=nullptr, bool fOneShot=false, bool fFeeler=false, bool fAddnode=false, bool masternode_connection=false, bool masternode_probe_connection=false)
Definition: net.cpp:1937
unsigned int nPrevNodeCount
Definition: net.h:470
void NotifyNumConnectionsChanged()
Definition: net.cpp:1223
void SetBannedSetDirty(bool dirty=true)
set the "dirty" flag for the banlist
Definition: net.cpp:621
ServiceFlags GetLocalServices() const
Definition: net.cpp:2621
bool DisconnectNode(const std::string &node)
Definition: net.cpp:2545
size_t SocketSendData(CNode *pnode)
Definition: net.cpp:857
ServiceFlags nRelevantServices
Services this instance cares about.
Definition: net.h:476
std::vector< CNode * > CopyNodeVector()
Definition: net.cpp:2864
std::vector< ListenSocket > vhListenSocket
Definition: net.h:455
void ThreadOpenConnections(const std::vector< std::string > connect)
Definition: net.cpp:1701
void ClearBanned()
Definition: net.cpp:473
void DumpBanlist()
Definition: net.cpp:433
size_t GetMaxOutboundNodeCount()
Definition: net.cpp:2513
CClientUIInterface * clientInterface
Definition: net.h:485
void GetBanned(banmap_t &banmap)
Definition: net.cpp:571
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:478
void ThreadSocketHandler()
Definition: net.cpp:1553
RecursiveMutex cs_totalBytesSent
Definition: net.h:444
std::thread threadOpenConnections
Definition: net.h:509
NumConnections
Definition: net.h:148
@ CONNECTIONS_IN
Definition: net.h:150
@ CONNECTIONS_ALL
Definition: net.h:152
@ CONNECTIONS_OUT
Definition: net.h:151
RecursiveMutex cs_vOneShots
Definition: net.h:463
bool fMsgProcWake
flag for waking the message processor.
Definition: net.h:492
CNode * FindNode(const CNetAddr &ip)
Definition: net.cpp:284
void Init(const Options &connOptions)
Definition: net.h:177
constexpr static const CAllNodes AllNodes
Definition: net.h:222
unsigned int GetSendBufferSize() const
Definition: net.cpp:2637
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg, bool allowOptimisticSend=DEFAULT_ALLOW_OPTIMISTIC_SEND)
Definition: net.cpp:2758
void MarkAddressGood(const CAddress &addr)
Definition: net.cpp:2470
void RelayInv(CInv &inv, int minProtoVersion=ActiveProtocol())
Definition: net.cpp:2567
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition: net.h:489
unsigned int nReceiveFloodSize
Definition: net.h:453
std::atomic< bool > wakeupSelectNeeded
Definition: net.h:504
RecursiveMutex cs_totalBytesRecv
Definition: net.h:443
static bool NodeFullyConnected(const CNode *pnode)
Definition: net.cpp:2753
int nMaxConnections
Definition: net.h:480
void WakeMessageHandler()
Definition: net.cpp:1562
void SetNetworkActive(bool active)
Definition: net.cpp:2144
bool IsBanned(CNetAddr ip)
Definition: net.cpp:485
bool AttemptToEvictConnection(bool fPreferNewConnection)
Try to find a connection to evict when the node is full.
Definition: net.cpp:972
bool Start(CScheduler &scheduler, const Options &options)
Definition: net.cpp:2208
bool GenerateSelectSet(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set)
Definition: net.cpp:1260
bool Bind(const CService &addr, unsigned int flags)
Definition: net.cpp:2178
bool IsNodeConnected(const CAddress &addr)
Definition: net.cpp:2825
void ThreadDNSAddressSeed()
Definition: net.cpp:1601
int wakeupPipe[2]
a pipe which is added to select() calls to wakeup before the timeout
Definition: net.h:502
std::vector< CSubNet > vWhitelistedRange
Definition: net.h:450
void ThreadMessageHandler()
Definition: net.cpp:1987
bool fAddressesInitialized
Definition: net.h:460
uint64_t GetTotalBytesSent()
Definition: net.cpp:2615
void WakeSelect()
Interrupt the select/poll system call.
Definition: net.cpp:1571
~CConnman()
Definition: net.cpp:2459
RecursiveMutex cs_vAddedNodes
Definition: net.h:465
std::thread threadOpenAddedConnections
Definition: net.h:508
CSipHasher GetDeterministicRandomizer(uint64_t id)
Get a unique deterministic randomizer.
Definition: net.cpp:2877
int nMaxOutbound
Definition: net.h:481
void Ban(const CNetAddr &netAddr, const BanReason &reason, int64_t bantimeoffset=0, bool sinceUnixEpoch=false)
Definition: net.cpp:512
bool BannedSetIsDirty()
check is the banlist has unwritten changes
Definition: net.cpp:615
void InactivityCheck(CNode *pnode)
Definition: net.cpp:1237
std::atomic< int > nBestHeight
Definition: net.h:484
bool CheckIncomingNonce(uint64_t nonce)
Definition: net.cpp:334
banmap_t setBanned
Definition: net.h:457
int nMaxAddnode
Definition: net.h:482
bool BindListenPort(const CService &bindAddr, std::string &strError, bool fWhitelisted=false)
Definition: net.cpp:2034
void RecordBytesRecv(uint64_t bytes)
Definition: net.cpp:2597
void DumpData()
Definition: net.cpp:1678
std::vector< AddedNodeInfo > GetAddedNodeInfo()
Definition: net.cpp:1856
void GetNodeStats(std::vector< CNodeStats > &vstats)
Definition: net.cpp:2534
constexpr static const CFullyConnectedOnly FullyConnectedOnly
Definition: net.h:221
bool InitBinds(const std::vector< CService > &binds, const std::vector< CService > &whiteBinds)
Definition: net.cpp:2191
std::vector< CNode * > vNodes
Definition: net.h:466
unsigned int nSendBufferMaxSize
Definition: net.h:452
void RemoveAskFor(const uint256 &invHash, int invType)
Definition: net.cpp:2579
NetEventsInterface * m_msgproc
Definition: net.h:486
void UpdateQuorumRelayMemberIfNeeded(CNode *pnode)
Update the node to be a iqr member if needed.
Definition: net.cpp:2589
void SetBanned(const banmap_t &banmap)
Definition: net.cpp:579
std::atomic< bool > fNetworkActive
Definition: net.h:456
void DisconnectNodes()
Definition: net.cpp:1164
RecursiveMutex cs_setBanned
Definition: net.h:458
CConnman(uint64_t seed0, uint64_t seed1)
Definition: net.cpp:2157
void DumpAddresses()
Definition: net.cpp:1667
bool AddNode(const std::string &node)
Definition: net.cpp:2490
int nMaxFeeler
Definition: net.h:483
std::thread threadSocketHandler
Definition: net.h:507
uint64_t CalculateKeyedNetGroup(const CAddress &ad)
Definition: net.cpp:2882
bool RemoveAddedNode(const std::string &node)
Definition: net.cpp:2501
void AddOneShot(const std::string &strDest)
Definition: net.cpp:98
CNode * ConnectNode(const CAddress &addrConnect)
Definition: net.cpp:2830
bool IsWhitelistedRange(const CNetAddr &addr)
Definition: net.cpp:628
void AcceptConnection(const ListenSocket &hListenSocket)
Definition: net.cpp:1074
static void callCleanup()
Definition: net.cpp:2367
CHash256 & Write(const unsigned char *data, size_t len)
Definition: hash.h:52
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: hash.h:45
inv message data
Definition: protocol.h:466
std::string ToString() const
Definition: protocol.cpp:245
bool IsMasterNodeType() const
Definition: protocol.cpp:208
uint256 hash
Definition: protocol.h:480
Message header.
Definition: protocol.h:31
static constexpr size_t CHECKSUM_SIZE
Definition: protocol.h:36
char pchCommand[COMMAND_SIZE]
Definition: protocol.h:55
static constexpr size_t HEADER_SIZE
Definition: protocol.h:39
uint8_t pchChecksum[CHECKSUM_SIZE]
Definition: protocol.h:57
uint32_t nMessageSize
Definition: protocol.h:56
Network address.
Definition: netaddress.h:120
std::string ToStringIP() const
Definition: netaddress.cpp:516
void SetIP(const CNetAddr &ip)
Definition: netaddress.cpp:122
std::string ToString() const
Definition: netaddress.cpp:568
bool IsRoutable() const
Definition: netaddress.cpp:454
bool IsValid() const
Definition: netaddress.cpp:418
bool IsIPv6() const
Definition: netaddress.cpp:297
bool SetInternal(const std::string &name)
Transform an arbitrary string into a non-routable ipv6 address.
Definition: netaddress.cpp:185
std::vector< unsigned char > GetGroup(const std::vector< bool > &asmap) const
Get the canonical identifier of our network group.
Definition: netaddress.cpp:698
uint32_t GetMappedAS(const std::vector< bool > &asmap) const
Definition: netaddress.cpp:657
enum Network GetNetwork() const
Definition: netaddress.cpp:489
~CNetCleanup()
Definition: net.cpp:2357
CNetCleanup()
Definition: net.cpp:2355
CHash256 hasher
Definition: net.h:625
CDataStream vRecv
Definition: net.h:634
unsigned int nHdrPos
Definition: net.h:632
int readHeader(const char *pch, unsigned int nBytes)
Definition: net.cpp:801
unsigned int nDataPos
Definition: net.h:635
const uint256 & GetMessageHash() const
Definition: net.cpp:848
CDataStream hdrbuf
Definition: net.h:630
bool in_data
Definition: net.h:628
uint256 data_hash
Definition: net.h:626
int64_t nTime
Definition: net.h:637
int readData(const char *pch, unsigned int nBytes)
Definition: net.cpp:831
bool complete() const
Definition: net.h:647
CMessageHeader hdr
Definition: net.h:631
Information about a peer.
Definition: net.h:669
RecursiveMutex cs_vProcessMsg
Definition: net.h:684
std::atomic< int64_t > nLastSend
Definition: net.h:694
bool fAddnode
Definition: net.h:709
std::string cleanSubVer
Definition: net.h:704
size_t nSendOffset
Definition: net.h:677
CRollingBloomFilter filterInventoryKnown
Definition: net.h:765
std::atomic< int > nVersion
Definition: net.h:699
void SetSendVersion(int nVersionIn)
Definition: net.cpp:775
std::atomic< bool > m_masternode_connection
Definition: net.h:710
std::deque< std::vector< unsigned char > > vSendMsg
Definition: net.h:679
std::atomic_bool fPauseRecv
Definition: net.h:734
NodeId GetId() const
Definition: net.h:825
uint256 hashContinue
Definition: net.h:748
std::atomic< int64_t > nTimeOffset
Definition: net.h:697
CService addrLocal
Definition: net.h:822
RecursiveMutex cs_sendProcessing
Definition: net.h:688
void PushAddress(const CAddress &_addr, FastRandomContext &insecure_rand)
Definition: net.h:886
RecursiveMutex cs_inventory
Definition: net.h:775
std::atomic< bool > fPingQueued
Definition: net.h:796
int GetSendVersion() const
Definition: net.cpp:789
bool fFeeler
Definition: net.h:707
bool fOneShot
Definition: net.h:708
std::list< CNetMessage > vRecvMsg
Definition: net.h:817
mapMsgCmdSize mapRecvBytesPerMsgCmd
Definition: net.h:745
size_t nProcessQueueSize
Definition: net.h:686
std::string addrName
Definition: net.h:820
void SetAddrLocal(const CService &addrLocalIn)
May not be called more than once.
Definition: net.cpp:654
uint64_t nSendBytes
Definition: net.h:678
void AskForInvReceived(const uint256 &invHash)
Definition: net.cpp:2741
std::atomic_bool fSuccessfullyConnected
Definition: net.h:721
ServiceFlags nServicesExpected
Definition: net.h:674
bool DisconnectOldProtocol(int nVersionIn, int nVersionRequired)
Definition: net.cpp:463
uint64_t GetLocalNonce() const
Definition: net.h:830
size_t nSendSize
Definition: net.h:676
std::atomic< ServiceFlags > nServices
Definition: net.h:673
bool fGetAddr
Definition: net.h:754
uint256 verifiedProRegTxHash
Definition: net.h:802
RecursiveMutex cs_SubVer
Definition: net.h:705
const CAddress addr
Definition: net.h:698
Mutex cs_mnauth
Definition: net.h:799
RecursiveMutex cs_vSend
Definition: net.h:680
RecursiveMutex cs_addrLocal
Definition: net.h:823
CSemaphoreGrant grantOutbound
Definition: net.h:728
const int64_t nTimeConnected
Definition: net.h:696
std::string GetAddrName() const
Definition: net.cpp:637
uint256 verifiedPubKeyHash
Definition: net.h:803
mapMsgCmdSize mapSendBytesPerMsgCmd
Definition: net.h:744
RecursiveMutex cs_vRecv
Definition: net.h:682
std::atomic< int > nRefCount
Definition: net.h:731
void AskFor(const CInv &inv, int64_t doubleRequestDelay=2 *60 *1000000)
Definition: net.cpp:2707
RecursiveMutex cs_addrName
Definition: net.h:819
void CloseSocketDisconnect()
Definition: net.cpp:453
std::atomic< int > nStartingHeight
Definition: net.h:749
bool fClient
Definition: net.h:714
int GetRefCount()
Definition: net.h:838
std::atomic_bool fPauseSend
Definition: net.h:735
std::multimap< int64_t, CInv > mapAskFor
Definition: net.h:776
std::unique_ptr< CBloomFilter > pfilter
Definition: net.h:730
SOCKET hSocket
Definition: net.h:675
void PushInventory(const CInv &inv)
Definition: net.h:914
bool ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool &complete)
Definition: net.cpp:724
void copyStats(CNodeStats &stats, const std::vector< bool > &m_asmap)
Definition: net.cpp:665
void MaybeSetAddrName(const std::string &addrNameIn)
Sets the addrName only if it was not previously set.
Definition: net.cpp:642
uint64_t nRecvBytes
Definition: net.h:691
std::atomic< int64_t > timeLastMempoolReq
Definition: net.h:784
std::atomic< int64_t > nLastRecv
Definition: net.h:695
bool CanRelay() const
Definition: net.h:946
std::atomic< int64_t > nMinPingUsecTime
Definition: net.h:794
std::atomic< uint64_t > nPingNonceSent
Definition: net.h:788
RecursiveMutex cs_hSocket
Definition: net.h:681
std::set< uint256 > setAskFor
Definition: net.h:777
std::atomic< int64_t > nPingUsecStart
Definition: net.h:790
ServiceFlags GetLocalServices() const
Definition: net.h:937
CNode(NodeId id, ServiceFlags nLocalServicesIn, int nMyStartingHeightIn, SOCKET hSocketIn, const CAddress &addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const std::string &addrNameIn="", bool fInboundIn=false)
Definition: net.cpp:2639
bool fRelayTxes
Definition: net.h:727
std::atomic< int64_t > nPingUsecTime
Definition: net.h:792
int nSendVersion
Definition: net.h:816
std::atomic< bool > m_masternode_probe_connection
Definition: net.h:711
bool fSendMempool
Definition: net.h:781
~CNode()
Definition: net.cpp:2702
std::list< CNetMessage > vProcessMsg
Definition: net.h:685
bool fWhitelisted
Definition: net.h:706
std::atomic< bool > m_masternode_iqr_connection
Definition: net.h:712
const bool fInbound
Definition: net.h:715
std::atomic_bool fDisconnect
Definition: net.h:722
CService GetAddrLocal() const
Definition: net.cpp:649
std::atomic< int > nRecvVersion
Definition: net.h:692
void Release()
Definition: net.h:875
std::string strSubVer
Definition: net.h:704
CNode * AddRef()
Definition: net.h:869
std::string addrLocal
Definition: net.h:607
double dPingWait
Definition: net.h:606
std::string addrName
Definition: net.h:594
uint32_t m_mapped_as
Definition: net.h:608
double dPingTime
Definition: net.h:605
NodeId nodeid
Definition: net.h:588
void scheduleEvery(Function f, int64_t deltaMilliSeconds)
Definition: scheduler.cpp:105
RAII-style semaphore lock.
Definition: sync.h:287
void Release()
Definition: sync.h:301
bool TryAcquire()
Definition: sync.h:309
void MoveTo(CSemaphoreGrant &grant)
Definition: sync.h:316
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:484
std::string ToStringIPPort() const
Definition: netaddress.cpp:945
std::string ToString() const
Definition: netaddress.cpp:954
uint16_t GetPort() const
Definition: netaddress.cpp:882
bool SetSockAddr(const struct sockaddr *paddr)
Definition: netaddress.cpp:868
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Definition: netaddress.cpp:902
SipHash-2-4.
Definition: siphash.h:14
uint64_t Finalize() const
Compute the 64-bit SipHash-2-4 of the data written so far.
Definition: siphash.cpp:76
CSipHasher & Write(uint64_t data)
Hash a 64-bit integer worth of data It is treated as if this was the little-endian interpretation of ...
Definition: siphash.cpp:28
std::string ToString() const
bool Match(const CNetAddr &addr) const
bool sleep_for(std::chrono::milliseconds rel_time)
Fast randomness source.
Definition: random.h:107
uint64_t randbits(int bits) noexcept
Generate a random (bits)-bit integer.
Definition: random.h:159
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
Definition: random.h:174
virtual void InitializeNode(CNode *pnode)=0
virtual bool SendMessages(CNode *pnode, std::atomic< bool > &interrupt) EXCLUSIVE_LOCKS_REQUIRED(pnode -> cs_sendProcessing)=0
virtual bool ProcessMessages(CNode *pnode, std::atomic< bool > &interrupt)=0
virtual void FinalizeNode(NodeId id, bool &update_connection_time)=0
bool IsNull() const
Definition: uint256.h:36
unsigned char * begin()
Definition: uint256.h:63
STL-like map container that only keeps the N elements with the highest value.
Definition: limitedmap.h:15
std::map< K, V >::const_iterator const_iterator
Definition: limitedmap.h:20
CService proxy
Definition: netbase.h:37
256-bit opaque blob.
Definition: uint256.h:138
#define INVALID_SOCKET
Definition: compat.h:64
u_int SOCKET
Definition: compat.h:53
#define WSAEWOULDBLOCK
Definition: compat.h:58
#define SOCKET_ERROR
Definition: compat.h:65
#define WSAGetLastError()
Definition: compat.h:55
#define WSAEMSGSIZE
Definition: compat.h:59
#define MSG_NOSIGNAL
Definition: compat.h:79
void * sockopt_arg_type
Definition: compat.h:98
#define WSAEINPROGRESS
Definition: compat.h:61
#define WSAEADDRINUSE
Definition: compat.h:62
#define WSAEINTR
Definition: compat.h:60
if(!read_stdin(buffer))
Definition: fuzz.cpp:72
void * memcpy(void *a, const void *b, size_t c)
CClientUIInterface uiInterface
Definition: init.cpp:109
uint256 Hash(const T1 pbegin, const T1 pend)
Compute the 256-bit hash of an object.
Definition: hash.h:173
std::unique_ptr< CConnman > g_connman
Definition: init.cpp:90
@ LOCK
Definition: lockunlock.h:16
bool fLogIPs
Definition: logging.cpp:28
#define LogPrint(category,...)
Definition: logging.h:163
unsigned int nonce
Definition: miner_tests.cpp:28
@ NET
Definition: logging.h:41
CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
Definition: net.cpp:158
bool RemoveLocal(const CService &addr)
Definition: net.cpp:237
bool IsPeerAddrLocalGood(CNode *pnode)
Definition: net.cpp:178
std::map< CNetAddr, LocalServiceInfo > mapLocalHost
Definition: net.cpp:92
uint16_t GetListenPort()
Definition: net.cpp:104
void AdvertiseLocal(CNode *pnode)
Definition: net.cpp:186
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:278
#define DUMP_ADDRESSES_INTERVAL
Definition: net.cpp:47
BindFlags
Used to pass flags to the Bind() function.
Definition: net.cpp:68
@ BF_REPORT_ERROR
Definition: net.cpp:71
@ BF_NONE
Definition: net.cpp:69
@ BF_EXPLICIT
Definition: net.cpp:70
@ BF_WHITELIST
Definition: net.cpp:72
bool fDiscover
Definition: net.cpp:89
limitedmap< CInv, int64_t > mapAlreadyAskedFor(MAX_INV_SZ)
bool fListen
Definition: net.cpp:90
bool GetLocal(CService &addr, const CNetAddr *paddrPeer)
Definition: net.cpp:110
RecursiveMutex cs_mapLocalHost
Definition: net.cpp:91
class CNetCleanup instance_of_cnetcleanup
int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds)
Return a timestamp in the future (in microseconds) for exponentially distributed events.
Definition: net.cpp:2846
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:94
#define X(name)
Definition: net.cpp:664
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:245
bool validateMasternodeIP(const std::string &addrStr)
Definition: net.cpp:2836
bool AddLocal(const CService &addr, int nScore)
Definition: net.cpp:206
#define FEELER_SLEEP_WINDOW
Definition: net.cpp:50
void CheckOffsetDisconnectedPeers(const CNetAddr &ip)
Definition: net.cpp:908
void Discover()
Definition: net.cpp:2101
bool IsReachable(enum Network net)
Definition: net.cpp:253
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:265
int GetnScore(const CService &addr)
Definition: net.cpp:169
#define ENOUGH_CONNECTIONS
Disconnected peers are added to setOffsetDisconnectedPeers only if node has less than ENOUGH_CONNECTI...
Definition: net.h:96
@ LOCAL_NONE
Definition: net.h:535
@ LOCAL_MANUAL
Definition: net.h:539
@ LOCAL_BIND
Definition: net.h:537
@ LOCAL_IF
Definition: net.h:536
int NodeId
Definition: net.h:109
#define MAX_TIMEOFFSET_DISCONNECTIONS
Maximum number of peers added to setOffsetDisconnectedPeers before triggering a warning.
Definition: net.h:98
Network
A network type.
Definition: netaddress.h:44
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
Definition: netaddress.h:68
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
Definition: netaddress.h:46
@ NET_INTERNAL
A set of addresses that represent the hash of a string or FQDN.
Definition: netaddress.h:65
bool GetNameProxy(proxyType &nameProxyOut)
Definition: netbase.cpp:624
void SplitHostPort(std::string in, int &portOut, std::string &hostOut)
Definition: netbase.cpp:71
bool SetSocketNoDelay(SOCKET &hSocket)
Set the TCP_NODELAY flag on a socket.
Definition: netbase.cpp:784
bool HaveNameProxy()
Definition: netbase.cpp:633
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
Definition: netbase.cpp:605
bool Lookup(const std::string &name, std::vector< CService > &vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
Definition: netbase.cpp:177
CService LookupNumeric(const std::string &name, int portDefault)
Definition: netbase.cpp:209
bool ConnectThroughProxy(const proxyType &proxy, const std::string &strDest, int port, const SOCKET &hSocket, int nTimeout, bool *outProxyConnectionFailed)
Definition: netbase.cpp:649
void InterruptSocks5(bool interrupt)
Definition: netbase.cpp:791
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
Definition: netbase.cpp:724
bool LookupHost(const std::string &name, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
Definition: netbase.cpp:149
bool fNameLookup
Definition: netbase.cpp:40
int nConnectTimeout
Definition: netbase.cpp:39
bool ConnectSocketDirectly(const CService &addrConnect, const SOCKET &hSocket, int nTimeout, bool manual_connection)
Definition: netbase.cpp:535
bool CloseSocket(SOCKET &hSocket)
Close socket and set hSocket to INVALID_SOCKET.
Definition: netbase.cpp:742
SOCKET CreateSocket(const CService &addrConnect)
Definition: netbase.cpp:490
boost::optional< T > Optional
Substitute for C++17 std::optional.
Definition: optional.h:12
#define PACKAGE_NAME
Definition: pivx-config.h:366
int flags
Definition: pivx-tx.cpp:400
const std::vector< std::string > & getAllNetMessageTypes()
Definition: protocol.cpp:250
ServiceFlags
nServices flags
Definition: protocol.h:312
@ NODE_NONE
Definition: protocol.h:314
@ NODE_NETWORK
Definition: protocol.h:318
@ NODE_BLOOM_WITHOUT_MN
Definition: protocol.h:325
uint64_t GetRand(uint64_t nMax) noexcept
Definition: random.cpp:586
void RandAddEvent(const uint32_t event_info) noexcept
Gathers entropy from the low bits of the time at which events occur.
Definition: random.cpp:582
int GetRandInt(int nMax) noexcept
Definition: random.cpp:591
@ SER_NETWORK
Definition: serialize.h:174
std::vector< std::string > m_specified_outgoing
Definition: net.h:173
NetEventsInterface * m_msgproc
Definition: net.h:165
std::vector< CService > vWhiteBinds
Definition: net.h:171
std::vector< CService > vBinds
Definition: net.h:171
std::vector< std::string > vSeedNodes
Definition: net.h:169
bool m_use_addrman_outgoing
Definition: net.h:172
std::string host
Definition: chainparams.h:21
bool supportsServiceBitsFiltering
Definition: chainparams.h:22
int nScore
Definition: net.h:577
int64_t nTimeConnected
Definition: net.cpp:944
int64_t nMinPingUsecTime
Definition: net.cpp:945
uint64_t nKeyedNetGroup
Definition: net.cpp:947
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:247
#define TRY_LOCK(cs, name)
Definition: sync.h:224
ArgsManager gArgs
Definition: system.cpp:89
std::atomic< bool > fMasterNode
Definition: system.cpp:87
bool error(const char *fmt, const Args &... args)
Definition: system.h:77
std::string _(const char *psz)
Translation function: Call Translate signal on UI interface, which returns a Optional result.
Definition: system.h:65
void TraceThread(const std::string name, Callable func)
Definition: system.h:271
int64_t GetAdjustedTime()
Definition: timedata.cpp:36
#define strprintf
Definition: tinyformat.h:1056
const uint256 UINT256_ZERO
constant uint256 instances
Definition: uint256.h:175
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
int64_t GetTimeMicros()
Returns the system time (not mockable)
Definition: utiltime.cpp:74
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: utiltime.cpp:61
int64_t GetSystemTimeInSeconds()
Returns the system time (not mockable)
Definition: utiltime.cpp:69
std::string FormatISO8601Time(int64_t nTime)
Definition: utiltime.cpp:141
int64_t GetTime()
DEPRECATED Use either GetSystemTimeInSeconds (not mockable) or GetTime<T> (mockable)
Definition: utiltime.cpp:27
CScheduler scheduler