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