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