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