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