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