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