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 // How often to dump addresses to peers.dat
49 static constexpr std::chrono::minutes DUMP_PEERS_INTERVAL{15};
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.m_ping_usec = nPingUsecTime;
559  stats.m_min_ping_usec = nMinPingUsecTime;
560  stats.m_ping_wait_usec = nPingUsecWait;
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 void V1TransportSerializer::prepareForTransport(CSerializedNetMsg& msg, std::vector<unsigned char>& header) {
722  // create dbl-sha256 checksum
723  uint256 hash = Hash(msg.data.begin(), msg.data.end());
724 
725  // create header
726  CMessageHeader hdr(Params().MessageStart(), msg.command.c_str(), msg.data.size());
727  memcpy(hdr.pchChecksum, hash.begin(), CMessageHeader::CHECKSUM_SIZE);
728 
729  // serialize header
730  header.reserve(CMessageHeader::HEADER_SIZE);
731  CVectorWriter{SER_NETWORK, INIT_PROTO_VERSION, header, 0, hdr};
732 }
733 
734 size_t CConnman::SocketSendData(CNode *pnode) const EXCLUSIVE_LOCKS_REQUIRED(pnode->cs_vSend)
735 {
736  auto it = pnode->vSendMsg.begin();
737  size_t nSentSize = 0;
738 
739  while (it != pnode->vSendMsg.end()) {
740  const auto &data = *it;
741  assert(data.size() > pnode->nSendOffset);
742  int nBytes = 0;
743  {
744  LOCK(pnode->cs_hSocket);
745  if (pnode->hSocket == INVALID_SOCKET)
746  break;
747  nBytes = send(pnode->hSocket, reinterpret_cast<const char*>(data.data()) + pnode->nSendOffset, data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT);
748  }
749  if (nBytes > 0) {
750  pnode->nLastSend = GetSystemTimeInSeconds();
751  pnode->nSendBytes += nBytes;
752  pnode->nSendOffset += nBytes;
753  nSentSize += nBytes;
754  if (pnode->nSendOffset == data.size()) {
755  pnode->nSendOffset = 0;
756  pnode->nSendSize -= data.size();
757  pnode->fPauseSend = pnode->nSendSize > nSendBufferMaxSize;
758  it++;
759  } else {
760  // could not send full message; stop sending more
761  break;
762  }
763  } else {
764  if (nBytes < 0) {
765  // error
766  int nErr = WSAGetLastError();
767  if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
768  {
769  LogPrintf("socket send error %s\n", NetworkErrorString(nErr));
770  pnode->CloseSocketDisconnect();
771  }
772  }
773  // couldn't send anything at all
774  break;
775  }
776  }
777 
778  if (it == pnode->vSendMsg.end()) {
779  assert(pnode->nSendOffset == 0);
780  assert(pnode->nSendSize == 0);
781  }
782  pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it);
783  return nSentSize;
784 }
785 
787 {
789  int64_t nTimeConnected;
791  int64_t nLastBlockTime;
792  int64_t nLastTXTime;
797  uint64_t nKeyedNetGroup;
799 };
800 
802 {
803  return a.nMinPingUsecTime > b.nMinPingUsecTime;
804 }
805 
807 {
808  return a.nTimeConnected > b.nTimeConnected;
809 }
810 
812  return a.nKeyedNetGroup < b.nKeyedNetGroup;
813 }
814 
816 {
817  // There is a fall-through here because it is common for a node to have many peers which have not yet relayed a block.
820  return a.nTimeConnected > b.nTimeConnected;
821 }
822 
824 {
825  // 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.
826  if (a.nLastTXTime != b.nLastTXTime) return a.nLastTXTime < b.nLastTXTime;
827  if (a.fRelayTxes != b.fRelayTxes) return b.fRelayTxes;
828  if (a.fBloomFilter != b.fBloomFilter) return a.fBloomFilter;
829  return a.nTimeConnected > b.nTimeConnected;
830 }
831 
832 
834 template<typename T, typename Comparator>
835 static void EraseLastKElements(std::vector<T> &elements, Comparator comparator, size_t k)
836 {
837  std::sort(elements.begin(), elements.end(), comparator);
838  size_t eraseSize = std::min(k, elements.size());
839  elements.erase(elements.end() - eraseSize, elements.end());
840 }
841 
851 {
852  std::vector<NodeEvictionCandidate> vEvictionCandidates;
853  {
854  LOCK(cs_vNodes);
855 
856  for (const CNode* node : vNodes) {
857  if (node->HasPermission(PF_NOBAN))
858  continue;
859  if (!node->fInbound)
860  continue;
861  if (node->fDisconnect)
862  continue;
863  bool peer_relay_txes = false;
864  bool peer_filter_not_null = false;
865  if (node->m_tx_relay != nullptr) {
866  LOCK(node->m_tx_relay->cs_filter);
867  peer_relay_txes = node->m_tx_relay->fRelayTxes;
868  peer_filter_not_null = node->m_tx_relay->pfilter != nullptr;
869  }
870  NodeEvictionCandidate candidate = {node->GetId(), node->nTimeConnected, node->nMinPingUsecTime,
871  node->nLastBlockTime, node->nLastTXTime,
872  HasAllDesirableServiceFlags(node->nServices),
873  peer_relay_txes, peer_filter_not_null, node->addr, node->nKeyedNetGroup,
874  node->m_prefer_evict};
875  vEvictionCandidates.push_back(candidate);
876  }
877  }
878 
879  // Protect connections with certain characteristics
880 
881  // Deterministically select 4 peers to protect by netgroup.
882  // An attacker cannot predict which netgroups will be protected
883  EraseLastKElements(vEvictionCandidates, CompareNetGroupKeyed, 4);
884  // Protect the 8 nodes with the lowest minimum ping time.
885  // An attacker cannot manipulate this metric without physically moving nodes closer to the target.
886  EraseLastKElements(vEvictionCandidates, ReverseCompareNodeMinPingTime, 8);
887  // Protect 4 nodes that most recently sent us transactions.
888  // An attacker cannot manipulate this metric without performing useful work.
889  EraseLastKElements(vEvictionCandidates, CompareNodeTXTime, 4);
890  // Protect 4 nodes that most recently sent us blocks.
891  // An attacker cannot manipulate this metric without performing useful work.
892  EraseLastKElements(vEvictionCandidates, CompareNodeBlockTime, 4);
893  // Protect the half of the remaining nodes which have been connected the longest.
894  // This replicates the non-eviction implicit behavior, and precludes attacks that start later.
895  EraseLastKElements(vEvictionCandidates, ReverseCompareNodeTimeConnected, vEvictionCandidates.size() / 2);
896 
897  if (vEvictionCandidates.empty()) return false;
898 
899  // If any remaining peers are preferred for eviction consider only them.
900  // This happens after the other preferences since if a peer is really the best by other criteria (esp relaying blocks)
901  // then we probably don't want to evict it no matter what.
902  if (std::any_of(vEvictionCandidates.begin(),vEvictionCandidates.end(),[](NodeEvictionCandidate const &n){return n.prefer_evict;})) {
903  vEvictionCandidates.erase(std::remove_if(vEvictionCandidates.begin(),vEvictionCandidates.end(),
904  [](NodeEvictionCandidate const &n){return !n.prefer_evict;}),vEvictionCandidates.end());
905  }
906 
907  // Identify the network group with the most connections and youngest member.
908  // (vEvictionCandidates is already sorted by reverse connect time)
909  uint64_t naMostConnections;
910  unsigned int nMostConnections = 0;
911  int64_t nMostConnectionsTime = 0;
912  std::map<uint64_t, std::vector<NodeEvictionCandidate> > mapNetGroupNodes;
913  for (const NodeEvictionCandidate &node : vEvictionCandidates) {
914  std::vector<NodeEvictionCandidate> &group = mapNetGroupNodes[node.nKeyedNetGroup];
915  group.push_back(node);
916  int64_t grouptime = group[0].nTimeConnected;
917 
918  if (group.size() > nMostConnections || (group.size() == nMostConnections && grouptime > nMostConnectionsTime)) {
919  nMostConnections = group.size();
920  nMostConnectionsTime = grouptime;
921  naMostConnections = node.nKeyedNetGroup;
922  }
923  }
924 
925  // Reduce to the network group with the most connections
926  vEvictionCandidates = std::move(mapNetGroupNodes[naMostConnections]);
927 
928  // Disconnect from the network group with the most connections
929  NodeId evicted = vEvictionCandidates.front().id;
930  LOCK(cs_vNodes);
931  for (CNode* pnode : vNodes) {
932  if (pnode->GetId() == evicted) {
933  pnode->fDisconnect = true;
934  return true;
935  }
936  }
937  return false;
938 }
939 
940 void CConnman::AcceptConnection(const ListenSocket& hListenSocket) {
941  struct sockaddr_storage sockaddr;
942  socklen_t len = sizeof(sockaddr);
943  SOCKET hSocket = accept(hListenSocket.socket, (struct sockaddr*)&sockaddr, &len);
944  CAddress addr;
945  int nInbound = 0;
946  int nMaxInbound = nMaxConnections - m_max_outbound;
947 
948  if (hSocket != INVALID_SOCKET) {
949  if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr)) {
950  LogPrintf("Warning: Unknown socket family\n");
951  }
952  }
953 
955  hListenSocket.AddSocketPermissionFlags(permissionFlags);
956  AddWhitelistPermissionFlags(permissionFlags, addr);
957  bool legacyWhitelisted = false;
959  NetPermissions::ClearFlag(permissionFlags, PF_ISIMPLICIT);
960  if (gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) NetPermissions::AddFlag(permissionFlags, PF_FORCERELAY);
961  if (gArgs.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY)) NetPermissions::AddFlag(permissionFlags, PF_RELAY);
962  NetPermissions::AddFlag(permissionFlags, PF_MEMPOOL);
963  NetPermissions::AddFlag(permissionFlags, PF_NOBAN);
964  legacyWhitelisted = true;
965  }
966 
967  {
968  LOCK(cs_vNodes);
969  for (const CNode* pnode : vNodes) {
970  if (pnode->fInbound) nInbound++;
971  }
972  }
973 
974  if (hSocket == INVALID_SOCKET)
975  {
976  int nErr = WSAGetLastError();
977  if (nErr != WSAEWOULDBLOCK)
978  LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr));
979  return;
980  }
981 
982  if (!fNetworkActive) {
983  LogPrintf("connection from %s dropped: not accepting new connections\n", addr.ToString());
984  CloseSocket(hSocket);
985  return;
986  }
987 
988  if (!IsSelectableSocket(hSocket))
989  {
990  LogPrintf("connection from %s dropped: non-selectable socket\n", addr.ToString());
991  CloseSocket(hSocket);
992  return;
993  }
994 
995  // According to the internet TCP_NODELAY is not carried into accepted sockets
996  // on all platforms. Set it again here just to be sure.
997  SetSocketNoDelay(hSocket);
998 
999  int bannedlevel = m_banman ? m_banman->IsBannedLevel(addr) : 0;
1000 
1001  // Don't accept connections from banned peers, but if our inbound slots aren't almost full, accept
1002  // if the only banning reason was an automatic misbehavior ban.
1003  if (!NetPermissions::HasFlag(permissionFlags, NetPermissionFlags::PF_NOBAN) && bannedlevel > ((nInbound + 1 < nMaxInbound) ? 1 : 0))
1004  {
1005  LogPrint(BCLog::NET, "connection from %s dropped (banned)\n", addr.ToString());
1006  CloseSocket(hSocket);
1007  return;
1008  }
1009 
1010  if (nInbound >= nMaxInbound)
1011  {
1012  if (!AttemptToEvictConnection()) {
1013  // No connection to evict, disconnect the new connection
1014  LogPrint(BCLog::NET, "failed to find an eviction candidate - connection dropped (full)\n");
1015  CloseSocket(hSocket);
1016  return;
1017  }
1018  }
1019 
1020  NodeId id = GetNewNodeId();
1021  uint64_t nonce = GetDeterministicRandomizer(RANDOMIZER_ID_LOCALHOSTNONCE).Write(id).Finalize();
1022  CAddress addr_bind = GetBindAddress(hSocket);
1023 
1024  ServiceFlags nodeServices = nLocalServices;
1025  if (NetPermissions::HasFlag(permissionFlags, PF_BLOOMFILTER)) {
1026  nodeServices = static_cast<ServiceFlags>(nodeServices | NODE_BLOOM);
1027  }
1028  CNode* pnode = new CNode(id, nodeServices, GetBestHeight(), hSocket, addr, CalculateKeyedNetGroup(addr), nonce, addr_bind, "", true);
1029  pnode->AddRef();
1030  pnode->m_permissionFlags = permissionFlags;
1031  // If this flag is present, the user probably expect that RPC and QT report it as whitelisted (backward compatibility)
1032  pnode->m_legacyWhitelisted = legacyWhitelisted;
1033  pnode->m_prefer_evict = bannedlevel > 0;
1034  m_msgproc->InitializeNode(pnode);
1035 
1036  LogPrint(BCLog::NET, "connection from %s accepted\n", addr.ToString());
1037 
1038  {
1039  LOCK(cs_vNodes);
1040  vNodes.push_back(pnode);
1041  }
1042 
1043  // We received a new connection, harvest entropy from the time (and our peer count)
1044  RandAddEvent((uint32_t)id);
1045 }
1046 
1048 {
1049  {
1050  LOCK(cs_vNodes);
1051 
1052  if (!fNetworkActive) {
1053  // Disconnect any connected nodes
1054  for (CNode* pnode : vNodes) {
1055  if (!pnode->fDisconnect) {
1056  LogPrint(BCLog::NET, "Network not active, dropping peer=%d\n", pnode->GetId());
1057  pnode->fDisconnect = true;
1058  }
1059  }
1060  }
1061 
1062  // Disconnect unused nodes
1063  std::vector<CNode*> vNodesCopy = vNodes;
1064  for (CNode* pnode : vNodesCopy)
1065  {
1066  if (pnode->fDisconnect)
1067  {
1068  // remove from vNodes
1069  vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
1070 
1071  // release outbound grant (if any)
1072  pnode->grantOutbound.Release();
1073 
1074  // close socket and cleanup
1075  pnode->CloseSocketDisconnect();
1076 
1077  // hold in disconnected pool until all refs are released
1078  pnode->Release();
1079  vNodesDisconnected.push_back(pnode);
1080  }
1081  }
1082  }
1083  {
1084  // Delete disconnected nodes
1085  std::list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
1086  for (CNode* pnode : vNodesDisconnectedCopy)
1087  {
1088  // wait until threads are done using it
1089  if (pnode->GetRefCount() <= 0) {
1090  bool fDelete = false;
1091  {
1092  TRY_LOCK(pnode->cs_inventory, lockInv);
1093  if (lockInv) {
1094  TRY_LOCK(pnode->cs_vSend, lockSend);
1095  if (lockSend) {
1096  fDelete = true;
1097  }
1098  }
1099  }
1100  if (fDelete) {
1101  vNodesDisconnected.remove(pnode);
1102  DeleteNode(pnode);
1103  }
1104  }
1105  }
1106  }
1107 }
1108 
1110 {
1111  size_t vNodesSize;
1112  {
1113  LOCK(cs_vNodes);
1114  vNodesSize = vNodes.size();
1115  }
1116  if(vNodesSize != nPrevNodeCount) {
1117  nPrevNodeCount = vNodesSize;
1118  if(clientInterface)
1119  clientInterface->NotifyNumConnectionsChanged(vNodesSize);
1120  }
1121 }
1122 
1124 {
1125  int64_t nTime = GetSystemTimeInSeconds();
1126  if (nTime - pnode->nTimeConnected > m_peer_connect_timeout)
1127  {
1128  if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
1129  {
1130  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());
1131  pnode->fDisconnect = true;
1132  }
1133  else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL)
1134  {
1135  LogPrintf("socket sending timeout: %is\n", nTime - pnode->nLastSend);
1136  pnode->fDisconnect = true;
1137  }
1138  else if (nTime - pnode->nLastRecv > (pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL : 90*60))
1139  {
1140  LogPrintf("socket receive timeout: %is\n", nTime - pnode->nLastRecv);
1141  pnode->fDisconnect = true;
1142  }
1143  else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros())
1144  {
1145  LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart));
1146  pnode->fDisconnect = true;
1147  }
1148  else if (!pnode->fSuccessfullyConnected)
1149  {
1150  LogPrint(BCLog::NET, "version handshake timeout from %d\n", pnode->GetId());
1151  pnode->fDisconnect = true;
1152  }
1153  }
1154 }
1155 
1156 bool CConnman::GenerateSelectSet(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set)
1157 {
1158  for (const ListenSocket& hListenSocket : vhListenSocket) {
1159  recv_set.insert(hListenSocket.socket);
1160  }
1161 
1162  {
1163  LOCK(cs_vNodes);
1164  for (CNode* pnode : vNodes)
1165  {
1166  // Implement the following logic:
1167  // * If there is data to send, select() for sending data. As this only
1168  // happens when optimistic write failed, we choose to first drain the
1169  // write buffer in this case before receiving more. This avoids
1170  // needlessly queueing received data, if the remote peer is not themselves
1171  // receiving data. This means properly utilizing TCP flow control signalling.
1172  // * Otherwise, if there is space left in the receive buffer, select() for
1173  // receiving data.
1174  // * Hand off all complete messages to the processor, to be handled without
1175  // blocking here.
1176 
1177  bool select_recv = !pnode->fPauseRecv;
1178  bool select_send;
1179  {
1180  LOCK(pnode->cs_vSend);
1181  select_send = !pnode->vSendMsg.empty();
1182  }
1183 
1184  LOCK(pnode->cs_hSocket);
1185  if (pnode->hSocket == INVALID_SOCKET)
1186  continue;
1187 
1188  error_set.insert(pnode->hSocket);
1189  if (select_send) {
1190  send_set.insert(pnode->hSocket);
1191  continue;
1192  }
1193  if (select_recv) {
1194  recv_set.insert(pnode->hSocket);
1195  }
1196  }
1197  }
1198 
1199  return !recv_set.empty() || !send_set.empty() || !error_set.empty();
1200 }
1201 
1202 #ifdef USE_POLL
1203 void CConnman::SocketEvents(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set)
1204 {
1205  std::set<SOCKET> recv_select_set, send_select_set, error_select_set;
1206  if (!GenerateSelectSet(recv_select_set, send_select_set, error_select_set)) {
1207  interruptNet.sleep_for(std::chrono::milliseconds(SELECT_TIMEOUT_MILLISECONDS));
1208  return;
1209  }
1210 
1211  std::unordered_map<SOCKET, struct pollfd> pollfds;
1212  for (SOCKET socket_id : recv_select_set) {
1213  pollfds[socket_id].fd = socket_id;
1214  pollfds[socket_id].events |= POLLIN;
1215  }
1216 
1217  for (SOCKET socket_id : send_select_set) {
1218  pollfds[socket_id].fd = socket_id;
1219  pollfds[socket_id].events |= POLLOUT;
1220  }
1221 
1222  for (SOCKET socket_id : error_select_set) {
1223  pollfds[socket_id].fd = socket_id;
1224  // These flags are ignored, but we set them for clarity
1225  pollfds[socket_id].events |= POLLERR|POLLHUP;
1226  }
1227 
1228  std::vector<struct pollfd> vpollfds;
1229  vpollfds.reserve(pollfds.size());
1230  for (auto it : pollfds) {
1231  vpollfds.push_back(std::move(it.second));
1232  }
1233 
1234  if (poll(vpollfds.data(), vpollfds.size(), SELECT_TIMEOUT_MILLISECONDS) < 0) return;
1235 
1236  if (interruptNet) return;
1237 
1238  for (struct pollfd pollfd_entry : vpollfds) {
1239  if (pollfd_entry.revents & POLLIN) recv_set.insert(pollfd_entry.fd);
1240  if (pollfd_entry.revents & POLLOUT) send_set.insert(pollfd_entry.fd);
1241  if (pollfd_entry.revents & (POLLERR|POLLHUP)) error_set.insert(pollfd_entry.fd);
1242  }
1243 }
1244 #else
1245 void CConnman::SocketEvents(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set)
1246 {
1247  std::set<SOCKET> recv_select_set, send_select_set, error_select_set;
1248  if (!GenerateSelectSet(recv_select_set, send_select_set, error_select_set)) {
1249  interruptNet.sleep_for(std::chrono::milliseconds(SELECT_TIMEOUT_MILLISECONDS));
1250  return;
1251  }
1252 
1253  //
1254  // Find which sockets have data to receive
1255  //
1256  struct timeval timeout;
1257  timeout.tv_sec = 0;
1258  timeout.tv_usec = SELECT_TIMEOUT_MILLISECONDS * 1000; // frequency to poll pnode->vSend
1259 
1260  fd_set fdsetRecv;
1261  fd_set fdsetSend;
1262  fd_set fdsetError;
1263  FD_ZERO(&fdsetRecv);
1264  FD_ZERO(&fdsetSend);
1265  FD_ZERO(&fdsetError);
1266  SOCKET hSocketMax = 0;
1267 
1268  for (SOCKET hSocket : recv_select_set) {
1269  FD_SET(hSocket, &fdsetRecv);
1270  hSocketMax = std::max(hSocketMax, hSocket);
1271  }
1272 
1273  for (SOCKET hSocket : send_select_set) {
1274  FD_SET(hSocket, &fdsetSend);
1275  hSocketMax = std::max(hSocketMax, hSocket);
1276  }
1277 
1278  for (SOCKET hSocket : error_select_set) {
1279  FD_SET(hSocket, &fdsetError);
1280  hSocketMax = std::max(hSocketMax, hSocket);
1281  }
1282 
1283  int nSelect = select(hSocketMax + 1, &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
1284 
1285  if (interruptNet)
1286  return;
1287 
1288  if (nSelect == SOCKET_ERROR)
1289  {
1290  int nErr = WSAGetLastError();
1291  LogPrintf("socket select error %s\n", NetworkErrorString(nErr));
1292  for (unsigned int i = 0; i <= hSocketMax; i++)
1293  FD_SET(i, &fdsetRecv);
1294  FD_ZERO(&fdsetSend);
1295  FD_ZERO(&fdsetError);
1296  if (!interruptNet.sleep_for(std::chrono::milliseconds(SELECT_TIMEOUT_MILLISECONDS)))
1297  return;
1298  }
1299 
1300  for (SOCKET hSocket : recv_select_set) {
1301  if (FD_ISSET(hSocket, &fdsetRecv)) {
1302  recv_set.insert(hSocket);
1303  }
1304  }
1305 
1306  for (SOCKET hSocket : send_select_set) {
1307  if (FD_ISSET(hSocket, &fdsetSend)) {
1308  send_set.insert(hSocket);
1309  }
1310  }
1311 
1312  for (SOCKET hSocket : error_select_set) {
1313  if (FD_ISSET(hSocket, &fdsetError)) {
1314  error_set.insert(hSocket);
1315  }
1316  }
1317 }
1318 #endif
1319 
1321 {
1322  std::set<SOCKET> recv_set, send_set, error_set;
1323  SocketEvents(recv_set, send_set, error_set);
1324 
1325  if (interruptNet) return;
1326 
1327  //
1328  // Accept new connections
1329  //
1330  for (const ListenSocket& hListenSocket : vhListenSocket)
1331  {
1332  if (hListenSocket.socket != INVALID_SOCKET && recv_set.count(hListenSocket.socket) > 0)
1333  {
1334  AcceptConnection(hListenSocket);
1335  }
1336  }
1337 
1338  //
1339  // Service each socket
1340  //
1341  std::vector<CNode*> vNodesCopy;
1342  {
1343  LOCK(cs_vNodes);
1344  vNodesCopy = vNodes;
1345  for (CNode* pnode : vNodesCopy)
1346  pnode->AddRef();
1347  }
1348  for (CNode* pnode : vNodesCopy)
1349  {
1350  if (interruptNet)
1351  return;
1352 
1353  //
1354  // Receive
1355  //
1356  bool recvSet = false;
1357  bool sendSet = false;
1358  bool errorSet = false;
1359  {
1360  LOCK(pnode->cs_hSocket);
1361  if (pnode->hSocket == INVALID_SOCKET)
1362  continue;
1363  recvSet = recv_set.count(pnode->hSocket) > 0;
1364  sendSet = send_set.count(pnode->hSocket) > 0;
1365  errorSet = error_set.count(pnode->hSocket) > 0;
1366  }
1367  if (recvSet || errorSet)
1368  {
1369  // typical socket buffer is 8K-64K
1370  char pchBuf[0x10000];
1371  int nBytes = 0;
1372  {
1373  LOCK(pnode->cs_hSocket);
1374  if (pnode->hSocket == INVALID_SOCKET)
1375  continue;
1376  nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
1377  }
1378  if (nBytes > 0)
1379  {
1380  bool notify = false;
1381  if (!pnode->ReceiveMsgBytes(pchBuf, nBytes, notify))
1382  pnode->CloseSocketDisconnect();
1383  RecordBytesRecv(nBytes);
1384  if (notify) {
1385  size_t nSizeAdded = 0;
1386  auto it(pnode->vRecvMsg.begin());
1387  for (; it != pnode->vRecvMsg.end(); ++it) {
1388  // vRecvMsg contains only completed CNetMessage
1389  // the single possible partially deserialized message are held by TransportDeserializer
1390  nSizeAdded += it->m_raw_message_size;
1391  }
1392  {
1393  LOCK(pnode->cs_vProcessMsg);
1394  pnode->vProcessMsg.splice(pnode->vProcessMsg.end(), pnode->vRecvMsg, pnode->vRecvMsg.begin(), it);
1395  pnode->nProcessQueueSize += nSizeAdded;
1396  pnode->fPauseRecv = pnode->nProcessQueueSize > nReceiveFloodSize;
1397  }
1399  }
1400  }
1401  else if (nBytes == 0)
1402  {
1403  // socket closed gracefully
1404  if (!pnode->fDisconnect) {
1405  LogPrint(BCLog::NET, "socket closed for peer=%d\n", pnode->GetId());
1406  }
1407  pnode->CloseSocketDisconnect();
1408  }
1409  else if (nBytes < 0)
1410  {
1411  // error
1412  int nErr = WSAGetLastError();
1413  if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
1414  {
1415  if (!pnode->fDisconnect) {
1416  LogPrint(BCLog::NET, "socket recv error for peer=%d: %s\n", pnode->GetId(), NetworkErrorString(nErr));
1417  }
1418  pnode->CloseSocketDisconnect();
1419  }
1420  }
1421  }
1422 
1423  //
1424  // Send
1425  //
1426  if (sendSet)
1427  {
1428  LOCK(pnode->cs_vSend);
1429  size_t nBytes = SocketSendData(pnode);
1430  if (nBytes) {
1431  RecordBytesSent(nBytes);
1432  }
1433  }
1434 
1435  InactivityCheck(pnode);
1436  }
1437  {
1438  LOCK(cs_vNodes);
1439  for (CNode* pnode : vNodesCopy)
1440  pnode->Release();
1441  }
1442 }
1443 
1445 {
1446  while (!interruptNet)
1447  {
1448  DisconnectNodes();
1450  SocketHandler();
1451  }
1452 }
1453 
1455 {
1456  {
1457  std::lock_guard<std::mutex> lock(mutexMsgProc);
1458  fMsgProcWake = true;
1459  }
1460  condMsgProc.notify_one();
1461 }
1462 
1463 
1464 
1465 
1466 
1467 
1468 #ifdef USE_UPNP
1469 static CThreadInterrupt g_upnp_interrupt;
1470 static std::thread g_upnp_thread;
1471 static void ThreadMapPort()
1472 {
1473  std::string port = strprintf("%u", GetListenPort());
1474  const char * multicastif = nullptr;
1475  const char * minissdpdpath = nullptr;
1476  struct UPNPDev * devlist = nullptr;
1477  char lanaddr[64];
1478 
1479  int error = 0;
1480 #if MINIUPNPC_API_VERSION < 14
1481  devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
1482 #else
1483  devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, 2, &error);
1484 #endif
1485 
1486  struct UPNPUrls urls;
1487  struct IGDdatas data;
1488  int r;
1489 
1490  r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
1491  if (r == 1)
1492  {
1493  if (fDiscover) {
1494  char externalIPAddress[40];
1495  r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
1496  if (r != UPNPCOMMAND_SUCCESS) {
1497  LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r);
1498  } else {
1499  if (externalIPAddress[0]) {
1500  CNetAddr resolved;
1501  if (LookupHost(externalIPAddress, resolved, false)) {
1502  LogPrintf("UPnP: ExternalIPAddress = %s\n", resolved.ToString());
1503  AddLocal(resolved, LOCAL_UPNP);
1504  }
1505  } else {
1506  LogPrintf("UPnP: GetExternalIPAddress failed.\n");
1507  }
1508  }
1509  }
1510 
1511  std::string strDesc = PACKAGE_NAME " " + FormatFullVersion();
1512 
1513  do {
1514  r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
1515 
1516  if (r != UPNPCOMMAND_SUCCESS) {
1517  LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n", port, port, lanaddr, r, strupnperror(r));
1518  } else {
1519  LogPrintf("UPnP Port Mapping successful.\n");
1520  }
1521  } while (g_upnp_interrupt.sleep_for(std::chrono::minutes(20)));
1522 
1523  r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
1524  LogPrintf("UPNP_DeletePortMapping() returned: %d\n", r);
1525  freeUPNPDevlist(devlist); devlist = nullptr;
1526  FreeUPNPUrls(&urls);
1527  } else {
1528  LogPrintf("No valid UPnP IGDs found\n");
1529  freeUPNPDevlist(devlist); devlist = nullptr;
1530  if (r != 0)
1531  FreeUPNPUrls(&urls);
1532  }
1533 }
1534 
1535 void StartMapPort()
1536 {
1537  if (!g_upnp_thread.joinable()) {
1538  assert(!g_upnp_interrupt);
1539  g_upnp_thread = std::thread((std::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort)));
1540  }
1541 }
1542 
1543 void InterruptMapPort()
1544 {
1545  if(g_upnp_thread.joinable()) {
1546  g_upnp_interrupt();
1547  }
1548 }
1549 
1550 void StopMapPort()
1551 {
1552  if(g_upnp_thread.joinable()) {
1553  g_upnp_thread.join();
1554  g_upnp_interrupt.reset();
1555  }
1556 }
1557 
1558 #else
1560 {
1561  // Intentionally left blank.
1562 }
1564 {
1565  // Intentionally left blank.
1566 }
1568 {
1569  // Intentionally left blank.
1570 }
1571 #endif
1572 
1573 
1574 
1575 
1576 
1577 
1579 {
1580  FastRandomContext rng;
1581  std::vector<std::string> seeds = Params().DNSSeeds();
1582  Shuffle(seeds.begin(), seeds.end(), rng);
1583  int seeds_right_now = 0; // Number of seeds left before testing if we have enough connections
1584  int found = 0;
1585 
1586  if (gArgs.GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED)) {
1587  // When -forcednsseed is provided, query all.
1588  seeds_right_now = seeds.size();
1589  }
1590 
1591  for (const std::string& seed : seeds) {
1592  // goal: only query DNS seed if address need is acute
1593  // Avoiding DNS seeds when we don't need them improves user privacy by
1594  // creating fewer identifying DNS requests, reduces trust by giving seeds
1595  // less influence on the network topology, and reduces traffic to the seeds.
1596  if (addrman.size() > 0 && seeds_right_now == 0) {
1597  if (!interruptNet.sleep_for(std::chrono::seconds(11))) return;
1598 
1599  LOCK(cs_vNodes);
1600  int nRelevant = 0;
1601  for (const CNode* pnode : vNodes) {
1602  nRelevant += pnode->fSuccessfullyConnected && !pnode->fFeeler && !pnode->fOneShot && !pnode->m_manual_connection && !pnode->fInbound;
1603  }
1604  if (nRelevant >= 2) {
1605  LogPrintf("P2P peers available. Skipped DNS seeding.\n");
1606  return;
1607  }
1608  seeds_right_now += DNSSEEDS_TO_QUERY_AT_ONCE;
1609  }
1610 
1611  if (interruptNet) {
1612  return;
1613  }
1614  LogPrintf("Loading addresses from DNS seed %s\n", seed);
1615  if (HaveNameProxy()) {
1616  AddOneShot(seed);
1617  } else {
1618  std::vector<CNetAddr> vIPs;
1619  std::vector<CAddress> vAdd;
1620  ServiceFlags requiredServiceBits = GetDesirableServiceFlags(NODE_NONE);
1621  std::string host = strprintf("x%x.%s", requiredServiceBits, seed);
1622  CNetAddr resolveSource;
1623  if (!resolveSource.SetInternal(host)) {
1624  continue;
1625  }
1626  unsigned int nMaxIPs = 256; // Limits number of IPs learned from a DNS seed
1627  if (LookupHost(host, vIPs, nMaxIPs, true)) {
1628  for (const CNetAddr& ip : vIPs) {
1629  int nOneDay = 24*3600;
1630  CAddress addr = CAddress(CService(ip, Params().GetDefaultPort()), requiredServiceBits);
1631  addr.nTime = GetTime() - 3*nOneDay - rng.randrange(4*nOneDay); // use a random age between 3 and 7 days old
1632  vAdd.push_back(addr);
1633  found++;
1634  }
1635  addrman.Add(vAdd, resolveSource);
1636  } else {
1637  // We now avoid directly using results from DNS Seeds which do not support service bit filtering,
1638  // instead using them as a oneshot to get nodes with our desired service bits.
1639  AddOneShot(seed);
1640  }
1641  }
1642  --seeds_right_now;
1643  }
1644  LogPrintf("%d addresses found from DNS seeds\n", found);
1645 }
1646 
1647 
1648 
1649 
1650 
1651 
1652 
1653 
1654 
1655 
1656 
1657 
1659 {
1660  int64_t nStart = GetTimeMillis();
1661 
1662  CAddrDB adb;
1663  adb.Write(addrman);
1664 
1665  LogPrint(BCLog::NET, "Flushed %d addresses to peers.dat %dms\n",
1666  addrman.size(), GetTimeMillis() - nStart);
1667 }
1668 
1670 {
1671  std::string strDest;
1672  {
1673  LOCK(cs_vOneShots);
1674  if (vOneShots.empty())
1675  return;
1676  strDest = vOneShots.front();
1677  vOneShots.pop_front();
1678  }
1679  CAddress addr;
1680  CSemaphoreGrant grant(*semOutbound, true);
1681  if (grant) {
1682  OpenNetworkConnection(addr, false, &grant, strDest.c_str(), true);
1683  }
1684 }
1685 
1687 {
1689 }
1690 
1692 {
1694  LogPrint(BCLog::NET, "net: setting try another outbound peer=%s\n", flag ? "true" : "false");
1695 }
1696 
1697 // Return the number of peers we have over our outbound connection limit
1698 // Exclude peers that are marked for disconnect, or are going to be
1699 // disconnected soon (eg one-shots and feelers)
1700 // Also exclude peers that haven't finished initial connection handshake yet
1701 // (so that we don't decide we're over our desired connection limit, and then
1702 // evict some peer that has finished the handshake)
1704 {
1705  int nOutbound = 0;
1706  {
1707  LOCK(cs_vNodes);
1708  for (const CNode* pnode : vNodes) {
1709  if (!pnode->fInbound && !pnode->m_manual_connection && !pnode->fFeeler && !pnode->fDisconnect && !pnode->fOneShot && pnode->fSuccessfullyConnected) {
1710  ++nOutbound;
1711  }
1712  }
1713  }
1714  return std::max(nOutbound - m_max_outbound_full_relay - m_max_outbound_block_relay, 0);
1715 }
1716 
1717 void CConnman::ThreadOpenConnections(const std::vector<std::string> connect)
1718 {
1719  // Connect to specific addresses
1720  if (!connect.empty())
1721  {
1722  for (int64_t nLoop = 0;; nLoop++)
1723  {
1724  ProcessOneShot();
1725  for (const std::string& strAddr : connect)
1726  {
1727  CAddress addr(CService(), NODE_NONE);
1728  OpenNetworkConnection(addr, false, nullptr, strAddr.c_str(), false, false, true);
1729  for (int i = 0; i < 10 && i < nLoop; i++)
1730  {
1731  if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
1732  return;
1733  }
1734  }
1735  if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
1736  return;
1737  }
1738  }
1739 
1740  // Initiate network connections
1741  int64_t nStart = GetTime();
1742 
1743  // Minimum time before next feeler connection (in microseconds).
1744  int64_t nNextFeeler = PoissonNextSend(nStart*1000*1000, FEELER_INTERVAL);
1745  while (!interruptNet)
1746  {
1747  ProcessOneShot();
1748 
1749  if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
1750  return;
1751 
1752  CSemaphoreGrant grant(*semOutbound);
1753  if (interruptNet)
1754  return;
1755 
1756  // Add seed nodes if DNS seeds are all down (an infrastructure attack?).
1757  if (addrman.size() == 0 && (GetTime() - nStart > 60)) {
1758  static bool done = false;
1759  if (!done) {
1760  LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n");
1761  CNetAddr local;
1762  local.SetInternal("fixedseeds");
1763  addrman.Add(convertSeed6(Params().FixedSeeds()), local);
1764  done = true;
1765  }
1766  }
1767 
1768  //
1769  // Choose an address to connect to based on most recently seen
1770  //
1771  CAddress addrConnect;
1772 
1773  // Only connect out to one peer per network group (/16 for IPv4).
1774  int nOutboundFullRelay = 0;
1775  int nOutboundBlockRelay = 0;
1776  std::set<std::vector<unsigned char> > setConnected;
1777  {
1778  LOCK(cs_vNodes);
1779  for (const CNode* pnode : vNodes) {
1780  if (!pnode->fInbound && !pnode->m_manual_connection) {
1781  // Netgroups for inbound and addnode peers are not excluded because our goal here
1782  // is to not use multiple of our limited outbound slots on a single netgroup
1783  // but inbound and addnode peers do not use our outbound slots. Inbound peers
1784  // also have the added issue that they're attacker controlled and could be used
1785  // to prevent us from connecting to particular hosts if we used them here.
1786  setConnected.insert(pnode->addr.GetGroup(addrman.m_asmap));
1787  if (pnode->m_tx_relay == nullptr) {
1788  nOutboundBlockRelay++;
1789  } else if (!pnode->fFeeler) {
1790  nOutboundFullRelay++;
1791  }
1792  }
1793  }
1794  }
1795 
1796  // Feeler Connections
1797  //
1798  // Design goals:
1799  // * Increase the number of connectable addresses in the tried table.
1800  //
1801  // Method:
1802  // * Choose a random address from new and attempt to connect to it if we can connect
1803  // successfully it is added to tried.
1804  // * Start attempting feeler connections only after node finishes making outbound
1805  // connections.
1806  // * Only make a feeler connection once every few minutes.
1807  //
1808  bool fFeeler = false;
1809 
1810  if (nOutboundFullRelay >= m_max_outbound_full_relay && nOutboundBlockRelay >= m_max_outbound_block_relay && !GetTryNewOutboundPeer()) {
1811  int64_t nTime = GetTimeMicros(); // The current time right now (in microseconds).
1812  if (nTime > nNextFeeler) {
1813  nNextFeeler = PoissonNextSend(nTime, FEELER_INTERVAL);
1814  fFeeler = true;
1815  } else {
1816  continue;
1817  }
1818  }
1819 
1821 
1822  int64_t nANow = GetAdjustedTime();
1823  int nTries = 0;
1824  while (!interruptNet)
1825  {
1827 
1828  // SelectTriedCollision returns an invalid address if it is empty.
1829  if (!fFeeler || !addr.IsValid()) {
1830  addr = addrman.Select(fFeeler);
1831  }
1832 
1833  // Require outbound connections, other than feelers, to be to distinct network groups
1834  if (!fFeeler && setConnected.count(addr.GetGroup(addrman.m_asmap))) {
1835  break;
1836  }
1837 
1838  // if we selected an invalid or local address, restart
1839  if (!addr.IsValid() || IsLocal(addr)) {
1840  break;
1841  }
1842 
1843  // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
1844  // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
1845  // already-connected network ranges, ...) before trying new addrman addresses.
1846  nTries++;
1847  if (nTries > 100)
1848  break;
1849 
1850  if (!IsReachable(addr))
1851  continue;
1852 
1853  // only consider very recently tried nodes after 30 failed attempts
1854  if (nANow - addr.nLastTry < 600 && nTries < 30)
1855  continue;
1856 
1857  // for non-feelers, require all the services we'll want,
1858  // for feelers, only require they be a full node (only because most
1859  // SPV clients don't have a good address DB available)
1860  if (!fFeeler && !HasAllDesirableServiceFlags(addr.nServices)) {
1861  continue;
1862  } else if (fFeeler && !MayHaveUsefulAddressDB(addr.nServices)) {
1863  continue;
1864  }
1865 
1866  // do not allow non-default ports, unless after 50 invalid addresses selected already
1867  if (addr.GetPort() != Params().GetDefaultPort() && nTries < 50)
1868  continue;
1869 
1870  addrConnect = addr;
1871  break;
1872  }
1873 
1874  if (addrConnect.IsValid()) {
1875 
1876  if (fFeeler) {
1877  // Add small amount of random noise before connection to avoid synchronization.
1878  int randsleep = GetRandInt(FEELER_SLEEP_WINDOW * 1000);
1879  if (!interruptNet.sleep_for(std::chrono::milliseconds(randsleep)))
1880  return;
1881  LogPrint(BCLog::NET, "Making feeler connection to %s\n", addrConnect.ToString());
1882  }
1883 
1884  // Open this connection as block-relay-only if we're already at our
1885  // full-relay capacity, but not yet at our block-relay peer limit.
1886  // (It should not be possible for fFeeler to be set if we're not
1887  // also at our block-relay peer limit, but check against that as
1888  // well for sanity.)
1889  bool block_relay_only = nOutboundBlockRelay < m_max_outbound_block_relay && !fFeeler && nOutboundFullRelay >= m_max_outbound_full_relay;
1890 
1891  OpenNetworkConnection(addrConnect, (int)setConnected.size() >= std::min(nMaxConnections - 1, 2), &grant, nullptr, false, fFeeler, false, block_relay_only);
1892  }
1893  }
1894 }
1895 
1896 std::vector<AddedNodeInfo> CConnman::GetAddedNodeInfo()
1897 {
1898  std::vector<AddedNodeInfo> ret;
1899 
1900  std::list<std::string> lAddresses(0);
1901  {
1903  ret.reserve(vAddedNodes.size());
1904  std::copy(vAddedNodes.cbegin(), vAddedNodes.cend(), std::back_inserter(lAddresses));
1905  }
1906 
1907 
1908  // Build a map of all already connected addresses (by IP:port and by name) to inbound/outbound and resolved CService
1909  std::map<CService, bool> mapConnected;
1910  std::map<std::string, std::pair<bool, CService>> mapConnectedByName;
1911  {
1912  LOCK(cs_vNodes);
1913  for (const CNode* pnode : vNodes) {
1914  if (pnode->addr.IsValid()) {
1915  mapConnected[pnode->addr] = pnode->fInbound;
1916  }
1917  std::string addrName = pnode->GetAddrName();
1918  if (!addrName.empty()) {
1919  mapConnectedByName[std::move(addrName)] = std::make_pair(pnode->fInbound, static_cast<const CService&>(pnode->addr));
1920  }
1921  }
1922  }
1923 
1924  for (const std::string& strAddNode : lAddresses) {
1925  CService service(LookupNumeric(strAddNode, Params().GetDefaultPort()));
1926  AddedNodeInfo addedNode{strAddNode, CService(), false, false};
1927  if (service.IsValid()) {
1928  // strAddNode is an IP:port
1929  auto it = mapConnected.find(service);
1930  if (it != mapConnected.end()) {
1931  addedNode.resolvedAddress = service;
1932  addedNode.fConnected = true;
1933  addedNode.fInbound = it->second;
1934  }
1935  } else {
1936  // strAddNode is a name
1937  auto it = mapConnectedByName.find(strAddNode);
1938  if (it != mapConnectedByName.end()) {
1939  addedNode.resolvedAddress = it->second.second;
1940  addedNode.fConnected = true;
1941  addedNode.fInbound = it->second.first;
1942  }
1943  }
1944  ret.emplace_back(std::move(addedNode));
1945  }
1946 
1947  return ret;
1948 }
1949 
1951 {
1952  while (true)
1953  {
1954  CSemaphoreGrant grant(*semAddnode);
1955  std::vector<AddedNodeInfo> vInfo = GetAddedNodeInfo();
1956  bool tried = false;
1957  for (const AddedNodeInfo& info : vInfo) {
1958  if (!info.fConnected) {
1959  if (!grant.TryAcquire()) {
1960  // If we've used up our semaphore and need a new one, let's not wait here since while we are waiting
1961  // the addednodeinfo state might change.
1962  break;
1963  }
1964  tried = true;
1965  CAddress addr(CService(), NODE_NONE);
1966  OpenNetworkConnection(addr, false, &grant, info.strAddedNode.c_str(), false, false, true);
1967  if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
1968  return;
1969  }
1970  }
1971  // Retry every 60 seconds if a connection was attempted, otherwise two seconds
1972  if (!interruptNet.sleep_for(std::chrono::seconds(tried ? 60 : 2)))
1973  return;
1974  }
1975 }
1976 
1977 // if successful, this moves the passed grant to the constructed node
1978 void CConnman::OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *pszDest, bool fOneShot, bool fFeeler, bool manual_connection, bool block_relay_only)
1979 {
1980  //
1981  // Initiate outbound network connection
1982  //
1983  if (interruptNet) {
1984  return;
1985  }
1986  if (!fNetworkActive) {
1987  return;
1988  }
1989  if (!pszDest) {
1990  if (IsLocal(addrConnect) ||
1991  FindNode(static_cast<CNetAddr>(addrConnect)) || (m_banman && m_banman->IsBanned(addrConnect)) ||
1992  FindNode(addrConnect.ToStringIPPort()))
1993  return;
1994  } else if (FindNode(std::string(pszDest)))
1995  return;
1996 
1997  CNode* pnode = ConnectNode(addrConnect, pszDest, fCountFailure, manual_connection, block_relay_only);
1998 
1999  if (!pnode)
2000  return;
2001  if (grantOutbound)
2002  grantOutbound->MoveTo(pnode->grantOutbound);
2003  if (fOneShot)
2004  pnode->fOneShot = true;
2005  if (fFeeler)
2006  pnode->fFeeler = true;
2007  if (manual_connection)
2008  pnode->m_manual_connection = true;
2009 
2010  m_msgproc->InitializeNode(pnode);
2011  {
2012  LOCK(cs_vNodes);
2013  vNodes.push_back(pnode);
2014  }
2015 }
2016 
2018 {
2019  while (!flagInterruptMsgProc)
2020  {
2021  std::vector<CNode*> vNodesCopy;
2022  {
2023  LOCK(cs_vNodes);
2024  vNodesCopy = vNodes;
2025  for (CNode* pnode : vNodesCopy) {
2026  pnode->AddRef();
2027  }
2028  }
2029 
2030  bool fMoreWork = false;
2031 
2032  for (CNode* pnode : vNodesCopy)
2033  {
2034  if (pnode->fDisconnect)
2035  continue;
2036 
2037  // Receive messages
2038  bool fMoreNodeWork = m_msgproc->ProcessMessages(pnode, flagInterruptMsgProc);
2039  fMoreWork |= (fMoreNodeWork && !pnode->fPauseSend);
2041  return;
2042  // Send messages
2043  {
2044  LOCK(pnode->cs_sendProcessing);
2045  m_msgproc->SendMessages(pnode);
2046  }
2047 
2049  return;
2050  }
2051 
2052  {
2053  LOCK(cs_vNodes);
2054  for (CNode* pnode : vNodesCopy)
2055  pnode->Release();
2056  }
2057 
2058  WAIT_LOCK(mutexMsgProc, lock);
2059  if (!fMoreWork) {
2060  condMsgProc.wait_until(lock, std::chrono::steady_clock::now() + std::chrono::milliseconds(100), [this] { return fMsgProcWake; });
2061  }
2062  fMsgProcWake = false;
2063  }
2064 }
2065 
2066 
2067 
2068 
2069 
2070 
2071 bool CConnman::BindListenPort(const CService& addrBind, std::string& strError, NetPermissionFlags permissions)
2072 {
2073  strError = "";
2074  int nOne = 1;
2075 
2076  // Create socket for listening for incoming connections
2077  struct sockaddr_storage sockaddr;
2078  socklen_t len = sizeof(sockaddr);
2079  if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
2080  {
2081  strError = strprintf("Error: Bind address family for %s not supported", addrBind.ToString());
2082  LogPrintf("%s\n", strError);
2083  return false;
2084  }
2085 
2086  SOCKET hListenSocket = CreateSocket(addrBind);
2087  if (hListenSocket == INVALID_SOCKET)
2088  {
2089  strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError()));
2090  LogPrintf("%s\n", strError);
2091  return false;
2092  }
2093 
2094  // Allow binding if the port is still in TIME_WAIT state after
2095  // the program was closed and restarted.
2096  setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (sockopt_arg_type)&nOne, sizeof(int));
2097 
2098  // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
2099  // and enable it by default or not. Try to enable it, if possible.
2100  if (addrBind.IsIPv6()) {
2101 #ifdef IPV6_V6ONLY
2102  setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (sockopt_arg_type)&nOne, sizeof(int));
2103 #endif
2104 #ifdef WIN32
2105  int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED;
2106  setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, (const char*)&nProtLevel, sizeof(int));
2107 #endif
2108  }
2109 
2110  if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
2111  {
2112  int nErr = WSAGetLastError();
2113  if (nErr == WSAEADDRINUSE)
2114  strError = strprintf(_("Unable to bind to %s on this computer. %s is probably already running.").translated, addrBind.ToString(), PACKAGE_NAME);
2115  else
2116  strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)").translated, addrBind.ToString(), NetworkErrorString(nErr));
2117  LogPrintf("%s\n", strError);
2118  CloseSocket(hListenSocket);
2119  return false;
2120  }
2121  LogPrintf("Bound to %s\n", addrBind.ToString());
2122 
2123  // Listen for incoming connections
2124  if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
2125  {
2126  strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)").translated, NetworkErrorString(WSAGetLastError()));
2127  LogPrintf("%s\n", strError);
2128  CloseSocket(hListenSocket);
2129  return false;
2130  }
2131 
2132  vhListenSocket.push_back(ListenSocket(hListenSocket, permissions));
2133 
2134  if (addrBind.IsRoutable() && fDiscover && (permissions & PF_NOBAN) == 0)
2135  AddLocal(addrBind, LOCAL_BIND);
2136 
2137  return true;
2138 }
2139 
2140 void Discover()
2141 {
2142  if (!fDiscover)
2143  return;
2144 
2145 #ifdef WIN32
2146  // Get local host IP
2147  char pszHostName[256] = "";
2148  if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
2149  {
2150  std::vector<CNetAddr> vaddr;
2151  if (LookupHost(pszHostName, vaddr, 0, true))
2152  {
2153  for (const CNetAddr &addr : vaddr)
2154  {
2155  if (AddLocal(addr, LOCAL_IF))
2156  LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToString());
2157  }
2158  }
2159  }
2160 #elif (HAVE_DECL_GETIFADDRS && HAVE_DECL_FREEIFADDRS)
2161  // Get local host ip
2162  struct ifaddrs* myaddrs;
2163  if (getifaddrs(&myaddrs) == 0)
2164  {
2165  for (struct ifaddrs* ifa = myaddrs; ifa != nullptr; ifa = ifa->ifa_next)
2166  {
2167  if (ifa->ifa_addr == nullptr) continue;
2168  if ((ifa->ifa_flags & IFF_UP) == 0) continue;
2169  if (strcmp(ifa->ifa_name, "lo") == 0) continue;
2170  if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
2171  if (ifa->ifa_addr->sa_family == AF_INET)
2172  {
2173  struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
2174  CNetAddr addr(s4->sin_addr);
2175  if (AddLocal(addr, LOCAL_IF))
2176  LogPrintf("%s: IPv4 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
2177  }
2178  else if (ifa->ifa_addr->sa_family == AF_INET6)
2179  {
2180  struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
2181  CNetAddr addr(s6->sin6_addr);
2182  if (AddLocal(addr, LOCAL_IF))
2183  LogPrintf("%s: IPv6 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
2184  }
2185  }
2186  freeifaddrs(myaddrs);
2187  }
2188 #endif
2189 }
2190 
2192 {
2193  LogPrint(BCLog::NET, "SetNetworkActive: %s\n", active);
2194 
2195  if (fNetworkActive == active) {
2196  return;
2197  }
2198 
2199  fNetworkActive = active;
2200 
2201  uiInterface.NotifyNetworkActiveChanged(fNetworkActive);
2202 }
2203 
2204 CConnman::CConnman(uint64_t nSeed0In, uint64_t nSeed1In) : nSeed0(nSeed0In), nSeed1(nSeed1In)
2205 {
2206  SetTryNewOutboundPeer(false);
2207 
2208  Options connOptions;
2209  Init(connOptions);
2210 }
2211 
2213 {
2214  return nLastNodeId.fetch_add(1, std::memory_order_relaxed);
2215 }
2216 
2217 
2218 bool CConnman::Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions) {
2219  if (!(flags & BF_EXPLICIT) && !IsReachable(addr))
2220  return false;
2221  std::string strError;
2222  if (!BindListenPort(addr, strError, permissions)) {
2223  if ((flags & BF_REPORT_ERROR) && clientInterface) {
2224  clientInterface->ThreadSafeMessageBox(strError, "", CClientUIInterface::MSG_ERROR);
2225  }
2226  return false;
2227  }
2228  return true;
2229 }
2230 
2231 bool CConnman::InitBinds(const std::vector<CService>& binds, const std::vector<NetWhitebindPermissions>& whiteBinds)
2232 {
2233  bool fBound = false;
2234  for (const auto& addrBind : binds) {
2235  fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR), NetPermissionFlags::PF_NONE);
2236  }
2237  for (const auto& addrBind : whiteBinds) {
2238  fBound |= Bind(addrBind.m_service, (BF_EXPLICIT | BF_REPORT_ERROR), addrBind.m_flags);
2239  }
2240  if (binds.empty() && whiteBinds.empty()) {
2241  struct in_addr inaddr_any;
2242  inaddr_any.s_addr = INADDR_ANY;
2243  struct in6_addr inaddr6_any = IN6ADDR_ANY_INIT;
2244  fBound |= Bind(CService(inaddr6_any, GetListenPort()), BF_NONE, NetPermissionFlags::PF_NONE);
2245  fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE, NetPermissionFlags::PF_NONE);
2246  }
2247  return fBound;
2248 }
2249 
2250 bool CConnman::Start(CScheduler& scheduler, const Options& connOptions)
2251 {
2252  Init(connOptions);
2253 
2254  {
2256  nTotalBytesRecv = 0;
2257  }
2258  {
2260  nTotalBytesSent = 0;
2261  nMaxOutboundTotalBytesSentInCycle = 0;
2262  nMaxOutboundCycleStartTime = 0;
2263  }
2264 
2265  if (fListen && !InitBinds(connOptions.vBinds, connOptions.vWhiteBinds)) {
2266  if (clientInterface) {
2267  clientInterface->ThreadSafeMessageBox(
2268  _("Failed to listen on any port. Use -listen=0 if you want this.").translated,
2270  }
2271  return false;
2272  }
2273 
2274  for (const auto& strDest : connOptions.vSeedNodes) {
2275  AddOneShot(strDest);
2276  }
2277 
2278  if (clientInterface) {
2279  clientInterface->InitMessage(_("Loading P2P addresses...").translated);
2280  }
2281  // Load addresses from peers.dat
2282  int64_t nStart = GetTimeMillis();
2283  {
2284  CAddrDB adb;
2285  if (adb.Read(addrman))
2286  LogPrintf("Loaded %i addresses from peers.dat %dms\n", addrman.size(), GetTimeMillis() - nStart);
2287  else {
2288  addrman.Clear(); // Addrman can be in an inconsistent state after failure, reset it
2289  LogPrintf("Invalid or missing peers.dat; recreating\n");
2290  DumpAddresses();
2291  }
2292  }
2293 
2294  uiInterface.InitMessage(_("Starting network threads...").translated);
2295 
2296  fAddressesInitialized = true;
2297 
2298  if (semOutbound == nullptr) {
2299  // initialize semaphore
2300  semOutbound = MakeUnique<CSemaphore>(std::min(m_max_outbound, nMaxConnections));
2301  }
2302  if (semAddnode == nullptr) {
2303  // initialize semaphore
2304  semAddnode = MakeUnique<CSemaphore>(nMaxAddnode);
2305  }
2306 
2307  //
2308  // Start threads
2309  //
2310  assert(m_msgproc);
2311  InterruptSocks5(false);
2312  interruptNet.reset();
2313  flagInterruptMsgProc = false;
2314 
2315  {
2316  LOCK(mutexMsgProc);
2317  fMsgProcWake = false;
2318  }
2319 
2320  // Send and receive from sockets, accept connections
2321  threadSocketHandler = std::thread(&TraceThread<std::function<void()> >, "net", std::function<void()>(std::bind(&CConnman::ThreadSocketHandler, this)));
2322 
2323  if (!gArgs.GetBoolArg("-dnsseed", true))
2324  LogPrintf("DNS seeding disabled\n");
2325  else
2326  threadDNSAddressSeed = std::thread(&TraceThread<std::function<void()> >, "dnsseed", std::function<void()>(std::bind(&CConnman::ThreadDNSAddressSeed, this)));
2327 
2328  // Initiate outbound connections from -addnode
2329  threadOpenAddedConnections = std::thread(&TraceThread<std::function<void()> >, "addcon", std::function<void()>(std::bind(&CConnman::ThreadOpenAddedConnections, this)));
2330 
2331  if (connOptions.m_use_addrman_outgoing && !connOptions.m_specified_outgoing.empty()) {
2332  if (clientInterface) {
2333  clientInterface->ThreadSafeMessageBox(
2334  _("Cannot provide specific connections and have addrman find outgoing connections at the same.").translated,
2336  }
2337  return false;
2338  }
2339  if (connOptions.m_use_addrman_outgoing || !connOptions.m_specified_outgoing.empty())
2340  threadOpenConnections = std::thread(&TraceThread<std::function<void()> >, "opencon", std::function<void()>(std::bind(&CConnman::ThreadOpenConnections, this, connOptions.m_specified_outgoing)));
2341 
2342  // Process messages
2343  threadMessageHandler = std::thread(&TraceThread<std::function<void()> >, "msghand", std::function<void()>(std::bind(&CConnman::ThreadMessageHandler, this)));
2344 
2345  // Dump network addresses
2346  scheduler.scheduleEvery([this] { DumpAddresses(); }, DUMP_PEERS_INTERVAL);
2347 
2348  return true;
2349 }
2350 
2352 {
2353 public:
2355 
2357  {
2358 #ifdef WIN32
2359  // Shutdown Windows Sockets
2360  WSACleanup();
2361 #endif
2362  }
2363 };
2365 
2367 {
2368  {
2369  std::lock_guard<std::mutex> lock(mutexMsgProc);
2370  flagInterruptMsgProc = true;
2371  }
2372  condMsgProc.notify_all();
2373 
2374  interruptNet();
2375  InterruptSocks5(true);
2376 
2377  if (semOutbound) {
2378  for (int i=0; i<m_max_outbound; i++) {
2379  semOutbound->post();
2380  }
2381  }
2382 
2383  if (semAddnode) {
2384  for (int i=0; i<nMaxAddnode; i++) {
2385  semAddnode->post();
2386  }
2387  }
2388 }
2389 
2391 {
2392  if (threadMessageHandler.joinable())
2393  threadMessageHandler.join();
2394  if (threadOpenConnections.joinable())
2395  threadOpenConnections.join();
2396  if (threadOpenAddedConnections.joinable())
2398  if (threadDNSAddressSeed.joinable())
2399  threadDNSAddressSeed.join();
2400  if (threadSocketHandler.joinable())
2401  threadSocketHandler.join();
2402 
2404  {
2405  DumpAddresses();
2406  fAddressesInitialized = false;
2407  }
2408 
2409  // Close sockets
2410  for (CNode* pnode : vNodes)
2411  pnode->CloseSocketDisconnect();
2412  for (ListenSocket& hListenSocket : vhListenSocket)
2413  if (hListenSocket.socket != INVALID_SOCKET)
2414  if (!CloseSocket(hListenSocket.socket))
2415  LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError()));
2416 
2417  // clean up some globals (to help leak detection)
2418  for (CNode *pnode : vNodes) {
2419  DeleteNode(pnode);
2420  }
2421  for (CNode *pnode : vNodesDisconnected) {
2422  DeleteNode(pnode);
2423  }
2424  vNodes.clear();
2425  vNodesDisconnected.clear();
2426  vhListenSocket.clear();
2427  semOutbound.reset();
2428  semAddnode.reset();
2429 }
2430 
2432 {
2433  assert(pnode);
2434  bool fUpdateConnectionTime = false;
2435  m_msgproc->FinalizeNode(pnode->GetId(), fUpdateConnectionTime);
2436  if(fUpdateConnectionTime) {
2437  addrman.Connected(pnode->addr);
2438  }
2439  delete pnode;
2440 }
2441 
2443 {
2444  Interrupt();
2445  Stop();
2446 }
2447 
2449 {
2450  return addrman.size();
2451 }
2452 
2453 void CConnman::SetServices(const CService &addr, ServiceFlags nServices)
2454 {
2455  addrman.SetServices(addr, nServices);
2456 }
2457 
2459 {
2460  addrman.Good(addr);
2461 }
2462 
2463 void CConnman::AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty)
2464 {
2465  addrman.Add(vAddr, addrFrom, nTimePenalty);
2466 }
2467 
2468 std::vector<CAddress> CConnman::GetAddresses()
2469 {
2470  return addrman.GetAddr();
2471 }
2472 
2473 bool CConnman::AddNode(const std::string& strNode)
2474 {
2476  for (const std::string& it : vAddedNodes) {
2477  if (strNode == it) return false;
2478  }
2479 
2480  vAddedNodes.push_back(strNode);
2481  return true;
2482 }
2483 
2484 bool CConnman::RemoveAddedNode(const std::string& strNode)
2485 {
2487  for(std::vector<std::string>::iterator it = vAddedNodes.begin(); it != vAddedNodes.end(); ++it) {
2488  if (strNode == *it) {
2489  vAddedNodes.erase(it);
2490  return true;
2491  }
2492  }
2493  return false;
2494 }
2495 
2497 {
2498  LOCK(cs_vNodes);
2499  if (flags == CConnman::CONNECTIONS_ALL) // Shortcut if we want total
2500  return vNodes.size();
2501 
2502  int nNum = 0;
2503  for (const auto& pnode : vNodes) {
2504  if (flags & (pnode->fInbound ? CONNECTIONS_IN : CONNECTIONS_OUT)) {
2505  nNum++;
2506  }
2507  }
2508 
2509  return nNum;
2510 }
2511 
2512 void CConnman::GetNodeStats(std::vector<CNodeStats>& vstats)
2513 {
2514  vstats.clear();
2515  LOCK(cs_vNodes);
2516  vstats.reserve(vNodes.size());
2517  for (CNode* pnode : vNodes) {
2518  vstats.emplace_back();
2519  pnode->copyStats(vstats.back(), addrman.m_asmap);
2520  }
2521 }
2522 
2523 bool CConnman::DisconnectNode(const std::string& strNode)
2524 {
2525  LOCK(cs_vNodes);
2526  if (CNode* pnode = FindNode(strNode)) {
2527  pnode->fDisconnect = true;
2528  return true;
2529  }
2530  return false;
2531 }
2532 
2534 {
2535  bool disconnected = false;
2536  LOCK(cs_vNodes);
2537  for (CNode* pnode : vNodes) {
2538  if (subnet.Match(pnode->addr)) {
2539  pnode->fDisconnect = true;
2540  disconnected = true;
2541  }
2542  }
2543  return disconnected;
2544 }
2545 
2547 {
2548  return DisconnectNode(CSubNet(addr));
2549 }
2550 
2552 {
2553  LOCK(cs_vNodes);
2554  for(CNode* pnode : vNodes) {
2555  if (id == pnode->GetId()) {
2556  pnode->fDisconnect = true;
2557  return true;
2558  }
2559  }
2560  return false;
2561 }
2562 
2563 void CConnman::RecordBytesRecv(uint64_t bytes)
2564 {
2566  nTotalBytesRecv += bytes;
2567 }
2568 
2569 void CConnman::RecordBytesSent(uint64_t bytes)
2570 {
2572  nTotalBytesSent += bytes;
2573 
2574  uint64_t now = GetTime();
2575  if (nMaxOutboundCycleStartTime + nMaxOutboundTimeframe < now)
2576  {
2577  // timeframe expired, reset cycle
2578  nMaxOutboundCycleStartTime = now;
2579  nMaxOutboundTotalBytesSentInCycle = 0;
2580  }
2581 
2582  // TODO, exclude whitebind peers
2583  nMaxOutboundTotalBytesSentInCycle += bytes;
2584 }
2585 
2587 {
2589  nMaxOutboundLimit = limit;
2590 }
2591 
2593 {
2595  return nMaxOutboundLimit;
2596 }
2597 
2599 {
2601  return nMaxOutboundTimeframe;
2602 }
2603 
2605 {
2607  if (nMaxOutboundLimit == 0)
2608  return 0;
2609 
2610  if (nMaxOutboundCycleStartTime == 0)
2611  return nMaxOutboundTimeframe;
2612 
2613  uint64_t cycleEndTime = nMaxOutboundCycleStartTime + nMaxOutboundTimeframe;
2614  uint64_t now = GetTime();
2615  return (cycleEndTime < now) ? 0 : cycleEndTime - GetTime();
2616 }
2617 
2618 void CConnman::SetMaxOutboundTimeframe(uint64_t timeframe)
2619 {
2621  if (nMaxOutboundTimeframe != timeframe)
2622  {
2623  // reset measure-cycle in case of changing
2624  // the timeframe
2625  nMaxOutboundCycleStartTime = GetTime();
2626  }
2627  nMaxOutboundTimeframe = timeframe;
2628 }
2629 
2630 bool CConnman::OutboundTargetReached(bool historicalBlockServingLimit)
2631 {
2633  if (nMaxOutboundLimit == 0)
2634  return false;
2635 
2636  if (historicalBlockServingLimit)
2637  {
2638  // keep a large enough buffer to at least relay each block once
2639  uint64_t timeLeftInCycle = GetMaxOutboundTimeLeftInCycle();
2640  uint64_t buffer = timeLeftInCycle / 600 * MAX_BLOCK_SERIALIZED_SIZE;
2641  if (buffer >= nMaxOutboundLimit || nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit - buffer)
2642  return true;
2643  }
2644  else if (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit)
2645  return true;
2646 
2647  return false;
2648 }
2649 
2651 {
2653  if (nMaxOutboundLimit == 0)
2654  return 0;
2655 
2656  return (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit) ? 0 : nMaxOutboundLimit - nMaxOutboundTotalBytesSentInCycle;
2657 }
2658 
2660 {
2662  return nTotalBytesRecv;
2663 }
2664 
2666 {
2668  return nTotalBytesSent;
2669 }
2670 
2672 {
2673  return nLocalServices;
2674 }
2675 
2676 void CConnman::SetBestHeight(int height)
2677 {
2678  nBestHeight.store(height, std::memory_order_release);
2679 }
2680 
2682 {
2683  return nBestHeight.load(std::memory_order_acquire);
2684 }
2685 
2686 unsigned int CConnman::GetReceiveFloodSize() const { return nReceiveFloodSize; }
2687 
2688 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)
2689  : nTimeConnected(GetSystemTimeInSeconds()),
2690  addr(addrIn),
2691  addrBind(addrBindIn),
2692  fInbound(fInboundIn),
2693  nKeyedNetGroup(nKeyedNetGroupIn),
2694  // Don't relay addr messages to peers that we connect to as block-relay-only
2695  // peers (to prevent adversaries from inferring these links from addr
2696  // traffic).
2697  m_addr_known{block_relay_only ? nullptr : MakeUnique<CRollingBloomFilter>(5000, 0.001)},
2698  id(idIn),
2699  nLocalHostNonce(nLocalHostNonceIn),
2700  nLocalServices(nLocalServicesIn),
2701  nMyStartingHeight(nMyStartingHeightIn)
2702 {
2703  hSocket = hSocketIn;
2704  addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
2705  hashContinue = uint256();
2706  if (!block_relay_only) {
2707  m_tx_relay = MakeUnique<TxRelay>();
2708  }
2709 
2710  for (const std::string &msg : getAllNetMessageTypes())
2711  mapRecvBytesPerMsgCmd[msg] = 0;
2712  mapRecvBytesPerMsgCmd[NET_MESSAGE_COMMAND_OTHER] = 0;
2713 
2714  if (fLogIPs) {
2715  LogPrint(BCLog::NET, "Added connection to %s peer=%d\n", addrName, id);
2716  } else {
2717  LogPrint(BCLog::NET, "Added connection peer=%d\n", id);
2718  }
2719 
2720  m_deserializer = MakeUnique<V1TransportDeserializer>(V1TransportDeserializer(Params().MessageStart(), SER_NETWORK, INIT_PROTO_VERSION));
2721  m_serializer = MakeUnique<V1TransportSerializer>(V1TransportSerializer());
2722 }
2723 
2725 {
2726  CloseSocket(hSocket);
2727 }
2728 
2730 {
2731  return pnode && pnode->fSuccessfullyConnected && !pnode->fDisconnect;
2732 }
2733 
2735 {
2736  size_t nMessageSize = msg.data.size();
2737  LogPrint(BCLog::NET, "sending %s (%d bytes) peer=%d\n", SanitizeString(msg.command), nMessageSize, pnode->GetId());
2738 
2739  // make sure we use the appropriate network transport format
2740  std::vector<unsigned char> serializedHeader;
2741  pnode->m_serializer->prepareForTransport(msg, serializedHeader);
2742  size_t nTotalSize = nMessageSize + serializedHeader.size();
2743 
2744  size_t nBytesSent = 0;
2745  {
2746  LOCK(pnode->cs_vSend);
2747  bool optimisticSend(pnode->vSendMsg.empty());
2748 
2749  //log total amount of bytes per command
2750  pnode->mapSendBytesPerMsgCmd[msg.command] += nTotalSize;
2751  pnode->nSendSize += nTotalSize;
2752 
2753  if (pnode->nSendSize > nSendBufferMaxSize)
2754  pnode->fPauseSend = true;
2755  pnode->vSendMsg.push_back(std::move(serializedHeader));
2756  if (nMessageSize)
2757  pnode->vSendMsg.push_back(std::move(msg.data));
2758 
2759  // If write queue empty, attempt "optimistic write"
2760  if (optimisticSend == true)
2761  nBytesSent = SocketSendData(pnode);
2762  }
2763  if (nBytesSent)
2764  RecordBytesSent(nBytesSent);
2765 }
2766 
2767 bool CConnman::ForNode(NodeId id, std::function<bool(CNode* pnode)> func)
2768 {
2769  CNode* found = nullptr;
2770  LOCK(cs_vNodes);
2771  for (auto&& pnode : vNodes) {
2772  if(pnode->GetId() == id) {
2773  found = pnode;
2774  break;
2775  }
2776  }
2777  return found != nullptr && NodeFullyConnected(found) && func(found);
2778 }
2779 
2780 int64_t CConnman::PoissonNextSendInbound(int64_t now, int average_interval_seconds)
2781 {
2782  if (m_next_send_inv_to_incoming < now) {
2783  // If this function were called from multiple threads simultaneously
2784  // it would possible that both update the next send variable, and return a different result to their caller.
2785  // This is not possible in practice as only the net processing thread invokes this function.
2786  m_next_send_inv_to_incoming = PoissonNextSend(now, average_interval_seconds);
2787  }
2788  return m_next_send_inv_to_incoming;
2789 }
2790 
2791 int64_t PoissonNextSend(int64_t now, int average_interval_seconds)
2792 {
2793  return now + (int64_t)(log1p(GetRand(1ULL << 48) * -0.0000000000000035527136788 /* -1/2^48 */) * average_interval_seconds * -1000000.0 + 0.5);
2794 }
2795 
2797 {
2798  return CSipHasher(nSeed0, nSeed1).Write(id);
2799 }
2800 
2802 {
2803  std::vector<unsigned char> vchNetGroup(ad.GetGroup(addrman.m_asmap));
2804 
2805  return GetDeterministicRandomizer(RANDOMIZER_ID_NETGROUP).Write(vchNetGroup.data(), vchNetGroup.size()).Finalize();
2806 }
const std::vector< std::string > & DNSSeeds() const
Return the list of hostnames to look up for DNS seeds.
Definition: chainparams.h:83
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:486
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
uint64_t CalculateKeyedNetGroup(const CAddress &ad) const
Definition: net.cpp:2801
#define WSAEINPROGRESS
Definition: compat.h:56
unsigned short GetPort() const
Definition: netaddress.cpp:666
std::atomic< uint64_t > nPingNonceSent
Definition: net.h:851
void SocketHandler()
Definition: net.cpp:1320
void RandAddEvent(const uint32_t event_info) noexcept
Gathers entropy from the low bits of the time at which events occur.
Definition: random.cpp:581
void MoveTo(CSemaphoreGrant &grant)
Definition: sync.h:314
std::atomic_bool fPauseSend
Definition: net.h:786
Access to the (IP) address database (peers.dat)
Definition: addrdb.h:76
uint64_t GetRand(uint64_t nMax) noexcept
Definition: random.cpp:585
#define WSAEINTR
Definition: compat.h:55
void ThreadOpenAddedConnections()
Definition: net.cpp:1950
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:243
CAddrInfo Select(bool newOnly=false)
Choose an address to connect to.
Definition: addrman.h:628
std::unique_ptr< TransportSerializer > m_serializer
Definition: net.h:726
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:595
int64_t m_ping_usec
Definition: net.h:599
bool AddLocal(const CService &addr, int nScore)
Definition: net.cpp:209
CConnman(uint64_t seed0, uint64_t seed1)
Definition: net.cpp:2204
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:222
void scheduleEvery(Function f, std::chrono::milliseconds delta)
Repeat f until the scheduler is stopped.
Definition: scheduler.cpp:123
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:2448
void SetIP(const CNetAddr &ip)
Definition: netaddress.cpp:28
void WakeMessageHandler()
Definition: net.cpp:1454
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
Definition: net.cpp:2218
void SetServices(const CService &addr, ServiceFlags nServices)
Definition: net.cpp:2453
void Interrupt()
Definition: net.cpp:2366
CNetMessage GetMessage(const CMessageHeader::MessageStartChars &message_start, int64_t time) override
Definition: net.cpp:688
int64_t nLastTXTime
Definition: net.cpp:792
void SocketEvents(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set)
Definition: net.cpp:1245
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:57
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:789
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< unsigned char > data
Definition: net.h:115
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:769
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:1686
#define FEELER_SLEEP_WINDOW
Definition: net.cpp:55
int nMaxAddnode
Definition: net.h:450
RAII-style semaphore lock.
Definition: sync.h:284
uint64_t GetMaxOutboundTarget()
Definition: net.cpp:2592
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:2734
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:764
void SetMaxOutboundTimeframe(uint64_t timeframe)
set the timeframe for the max outbound target
Definition: net.cpp:2618
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:853
CAmount minFeeFilter
Definition: net.h:602
void Discover()
Definition: net.cpp:2140
CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
Definition: net.cpp:154
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:835
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:384
void SetTryNewOutboundPeer(bool flag)
Definition: net.cpp:1691
unsigned short GetListenPort()
Definition: net.cpp:99
bool InitBinds(const std::vector< CService > &binds, const std::vector< NetWhitebindPermissions > &whiteBinds)
Definition: net.cpp:2231
std::string ToString() const
Definition: netaddress.cpp:357
std::unique_ptr< TransportDeserializer > m_deserializer
Definition: net.h:725
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:1444
static bool CompareNodeBlockTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition: net.cpp:815
#define INVALID_SOCKET
Definition: compat.h:59
virtual bool SendMessages(CNode *pnode)=0
size_t GetNodeCount(NumConnections num)
Definition: net.cpp:2496
bool Add(const CAddress &addr, const CNetAddr &source, int64_t nTimePenalty=0)
Add a single address.
Definition: addrman.h:557
void PushAddress(const CAddress &_addr, FastRandomContext &insecure_rand)
Definition: net.h:956
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:73
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:823
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:1109
enum Network GetNetwork() const
Definition: netaddress.cpp:316
void SetMaxOutboundTarget(uint64_t limit)
set the max outbound target in bytes
Definition: net.cpp:2586
void RecordBytesSent(uint64_t bytes)
Definition: net.cpp:2569
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:2598
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:2767
void Stop() NO_THREAD_SAFETY_ANALYSIS
Definition: net.cpp:2390
ServiceFlags nLocalServices
Services this instance offers.
Definition: net.h:437
RecursiveMutex cs_mapLocalHost
Definition: net.cpp:88
bool IsValid() const
Definition: netaddress.cpp:253
bool DisconnectNode(const std::string &node)
Definition: net.cpp:2523
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:749
void RecordBytesRecv(uint64_t bytes)
Definition: net.cpp:2563
bool HaveNameProxy()
Definition: netbase.cpp:760
void DumpAddresses()
Definition: net.cpp:1658
bool done
std::vector< CAddress > GetAddr()
Return a bunch of addresses, selected at random.
Definition: addrman.h:641
int readData(const char *pch, unsigned int nBytes)
Definition: net.cpp:663
void StopMapPort()
Definition: net.cpp:1567
Extended statistics about a CAddress.
Definition: addrman.h:29
ServiceFlags GetLocalServices() const
Definition: net.h:1003
#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
int64_t m_ping_wait_usec
Definition: net.h:600
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:2650
bool Write(const CAddrMan &addr)
Definition: addrdb.cpp:139
static bool NodeFullyConnected(const CNode *pnode)
Definition: net.cpp:2729
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:2473
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:2604
void InactivityCheck(CNode *pnode)
Definition: net.cpp:1123
std::atomic< int64_t > nLastRecv
Definition: net.h:750
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition: net.h:460
bool fOneShot
Definition: net.h:771
static bool HasAllDesirableServiceFlags(ServiceFlags services)
A shortcut for (services & GetDesirableServiceFlags(services)) == GetDesirableServiceFlags(services)...
Definition: protocol.h:309
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:693
std::string ToStringIP() const
Definition: netaddress.cpp:333
#define LOCK(cs)
Definition: sync.h:218
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:2671
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:2780
bool OutboundTargetReached(bool historicalBlockServingLimit)
check if the outbound target is reached if param historicalBlockServingLimit is set true...
Definition: net.cpp:2630
std::vector< std::string > m_specified_outgoing
Definition: net.h:154
std::vector< CAddress > GetAddresses()
Definition: net.cpp:2468
int64_t m_peer_connect_timeout
Definition: net.h:402
void DisconnectNodes()
Definition: net.cpp:1047
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:439
void ThreadOpenConnections(std::vector< std::string > connect)
Definition: net.cpp:1717
std::thread threadMessageHandler
Definition: net.h:475
static bool HasFlag(const NetPermissionFlags &flags, NetPermissionFlags f)
bool m_manual_connection
Definition: net.h:772
void ProcessOneShot()
Definition: net.cpp:1669
const uint256 & GetMessageHash() const
Definition: net.cpp:680
A CService with information about it as peer.
Definition: protocol.h:322
bool Start(CScheduler &scheduler, const Options &options)
Definition: net.cpp:2250
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:203
uint64_t GetTotalBytesRecv()
Definition: net.cpp:2659
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:2354
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:2191
void AddNewAddresses(const std::vector< CAddress > &vAddr, const CAddress &addrFrom, int64_t nTimePenalty=0)
Definition: net.cpp:2463
int GetDefaultPort() const
Definition: chainparams.h:62
#define WAIT_LOCK(cs, name)
Definition: sync.h:223
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:902
void GetNodeStats(std::vector< CNodeStats > &vstats)
Definition: net.cpp:2512
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition: net.cpp:2796
std::atomic_bool fDisconnect
Definition: net.h:779
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:377
NetPermissionFlags
size_t nSendSize
Definition: net.h:731
bool CloseSocket(SOCKET &hSocket)
Close socket and set hSocket to INVALID_SOCKET.
Definition: netbase.cpp:899
int nConnectTimeout
Definition: netbase.cpp:34
void prepareForTransport(CSerializedNetMsg &msg, std::vector< unsigned char > &header) override
Definition: net.cpp:721
bool IsRoutable() const
Definition: netaddress.cpp:301
#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:317
unsigned int GetReceiveFloodSize() const
Definition: net.cpp:2686
unsigned char MessageStartChars[MESSAGE_START_SIZE]
Definition: protocol.h:37
~CNode()
Definition: net.cpp:2724
void DeleteNode(CNode *pnode)
Definition: net.cpp:2431
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:2688
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:754
bool Match(const CNetAddr &addr) const
Definition: netaddress.cpp:815
const int64_t nTimeConnected
Definition: net.h:751
int64_t GetTimeMicros()
Returns the system time (not mockable)
Definition: time.cpp:65
int flags
Definition: bitcoin-tx.cpp:509
#define X(name)
Definition: net.cpp:500
std::atomic< NodeId > nLastNodeId
Definition: net.h:422
bool RemoveAddedNode(const std::string &node)
Definition: net.cpp:2484
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:537
256-bit opaque blob.
Definition: uint256.h:120
int GetBestHeight() const
Definition: net.cpp:2681
~CNetCleanup()
Definition: net.cpp:2356
unsigned int nTime
Definition: protocol.h:354
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:218
int nScore
Definition: net.h:567
ServiceFlags nServices
Definition: protocol.h:351
#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:770
BanMan * m_banman
Definition: net.h:457
void Clear()
Definition: addrman.h:502
static const uint64_t SELECT_TIMEOUT_MILLISECONDS
Definition: net.cpp:76
int IsBannedLevel(CNetAddr net_addr)
Definition: banman.cpp:71
~CConnman()
Definition: net.cpp:2442
std::thread threadOpenConnections
Definition: net.h:474
bool AttemptToEvictConnection()
Try to find a connection to evict when the node is full.
Definition: net.cpp:850
static const unsigned int MAX_SIZE
Definition: serialize.h:27
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:781
bool SetSocketNoDelay(const SOCKET &hSocket)
Set the TCP_NODELAY flag on a socket.
Definition: netbase.cpp:942
uint256 hashContinue
Definition: net.h:793
void * memcpy(void *a, const void *b, size_t c)
const NodeId id
Definition: net.h:869
NodeId GetNewNodeId()
Definition: net.cpp:2212
std::string addrLocal
Definition: net.h:604
NetPermissionFlags m_permissionFlags
Definition: net.h:891
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:372
bool fAddressesInitialized
Definition: net.h:413
std::thread threadDNSAddressSeed
Definition: net.h:471
int64_t nTimeConnected
Definition: net.cpp:789
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:613
std::string ToStringIPPort() const
Definition: netaddress.cpp:741
size_t SocketSendData(CNode *pnode) const
Definition: net.cpp:734
ServiceFlags GetDesirableServiceFlags(ServiceFlags services)
Gets the set of service flags which are "desirable" for a given peer.
Definition: protocol.cpp:135
void SetSendVersion(int nVersionIn)
Definition: net.cpp:605
RecursiveMutex cs_vSend
Definition: net.h:735
std::vector< ListenSocket > vhListenSocket
Definition: net.h:411
void SetBestHeight(int height)
Definition: net.cpp:2676
SOCKET CreateSocket(const CService &addrConnect)
Try to create a socket file descriptor with specific properties in the communications domain (address...
Definition: netbase.cpp:567
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:1978
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:2791
std::string HexStr(const T itbegin, const T itend)
Definition: strencodings.h:123
ArgsManager gArgs
Definition: system.cpp:76
std::string command
Definition: net.h:116
bool fListen
Definition: net.cpp:86
std::atomic_bool fSuccessfullyConnected
Definition: net.h:776
SipHash-2-4.
Definition: siphash.h:13
void ThreadMessageHandler()
Definition: net.cpp:2017
void ResolveCollisions()
See if any to-be-evicted tried table entries have been tested and if so resolve the collisions...
Definition: addrman.h:604
std::atomic< int > nVersion
Definition: net.h:757
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:790
const uint64_t nLocalHostNonce
Definition: net.h:870
static constexpr std::chrono::minutes DUMP_PEERS_INTERVAL
Definition: net.cpp:49
std::vector< bool > m_asmap
Definition: addrman.h:287
static constexpr size_t HEADER_SIZE
Definition: protocol.h:36
std::string ToString() const
Definition: netaddress.cpp:750
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:887
int GetExtraOutboundCount()
Definition: net.cpp:1703
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:586
BindFlags
Used to pass flags to the Bind() function.
Definition: net.cpp:68
void SetServices(const CService &addr, ServiceFlags nServices)
Definition: addrman.h:662
uint64_t GetTotalBytesSent()
Definition: net.cpp:2665
bool GenerateSelectSet(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set)
Definition: net.cpp:1156
void AcceptConnection(const ListenSocket &hListenSocket)
Definition: net.cpp:940
bool m_valid_header
Definition: net.h:623
CClientUIInterface uiInterface
void MarkAddressGood(const CAddress &addr)
Definition: net.cpp:2458
Definition: net.h:529
static bool CompareNetGroupKeyed(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition: net.cpp:811
Information about a peer.
Definition: net.h:721
static CNetCleanup instance_of_cnetcleanup
Definition: net.cpp:2364
bool SetSockAddr(const struct sockaddr *paddr)
Definition: netaddress.cpp:652
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:797
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:307
void Connected(const CService &addr, int64_t nTime=GetAdjustedTime())
Mark an entry as currently-connected-to.
Definition: addrman.h:654
int64_t GetTime()
Return system time (or mocked time, if set)
Definition: time.cpp:23
auto it
Definition: validation.cpp:361
CNode * AddRef()
Definition: net.h:937
std::unique_ptr< CSemaphore > semAddnode
Definition: net.h:440
void Init(const Options &connOptions)
Definition: net.h:159
CThreadInterrupt interruptNet
Definition: net.h:469
int GetRandInt(int nMax) noexcept
Definition: random.cpp:595
static bool ReverseCompareNodeMinPingTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition: net.cpp:801
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:177
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:1896
bool fNameLookup
Definition: netbase.cpp:35
void StartMapPort()
Definition: net.cpp:1559
void InterruptMapPort()
Definition: net.cpp:1563
int64_t nLastBlockTime
Definition: net.cpp:791
int64_t m_min_ping_usec
Definition: net.h:601
const int nMyStartingHeight
Definition: net.h:889
virtual bool ProcessMessages(CNode *pnode, std::atomic< bool > &interrupt)=0
int64_t nLastTry
last try whatsoever by us (memory only)
Definition: addrman.h:33
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:793
bool BindListenPort(const CService &bindAddr, std::string &strError, NetPermissionFlags permissions)
Definition: net.cpp:2071
std::unique_ptr< TxRelay > m_tx_relay
Definition: net.h:840
Message header.
Definition: protocol.h:27
void SplitHostPort(std::string in, int &portOut, std::string &hostOut)
void ThreadDNSAddressSeed()
Definition: net.cpp:1578
static bool ReverseCompareNodeTimeConnected(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition: net.cpp:806