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