Bitcoin Core  22.0.0
P2P Digital Currency
net.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-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 <clientversion.h>
14 #include <compat.h>
15 #include <consensus/consensus.h>
16 #include <crypto/sha256.h>
17 #include <i2p.h>
18 #include <net_permissions.h>
19 #include <netaddress.h>
20 #include <netbase.h>
21 #include <node/ui_interface.h>
22 #include <protocol.h>
23 #include <random.h>
24 #include <scheduler.h>
25 #include <util/sock.h>
26 #include <util/strencodings.h>
27 #include <util/thread.h>
28 #include <util/translation.h>
29 
30 #ifdef WIN32
31 #include <string.h>
32 #else
33 #include <fcntl.h>
34 #endif
35 
36 #if HAVE_DECL_GETIFADDRS && HAVE_DECL_FREEIFADDRS
37 #include <ifaddrs.h>
38 #endif
39 
40 #ifdef USE_POLL
41 #include <poll.h>
42 #endif
43 
44 #include <algorithm>
45 #include <array>
46 #include <cstdint>
47 #include <functional>
48 #include <optional>
49 #include <unordered_map>
50 
51 #include <math.h>
52 
54 static constexpr size_t MAX_BLOCK_RELAY_ONLY_ANCHORS = 2;
55 static_assert (MAX_BLOCK_RELAY_ONLY_ANCHORS <= static_cast<size_t>(MAX_BLOCK_RELAY_ONLY_CONNECTIONS), "MAX_BLOCK_RELAY_ONLY_ANCHORS must not exceed MAX_BLOCK_RELAY_ONLY_CONNECTIONS.");
57 const char* const ANCHORS_DATABASE_FILENAME = "anchors.dat";
58 
59 // How often to dump addresses to peers.dat
60 static constexpr std::chrono::minutes DUMP_PEERS_INTERVAL{15};
61 
63 static constexpr int DNSSEEDS_TO_QUERY_AT_ONCE = 3;
64 
74 static constexpr std::chrono::seconds DNSSEEDS_DELAY_FEW_PEERS{11};
75 static constexpr std::chrono::minutes DNSSEEDS_DELAY_MANY_PEERS{5};
76 static constexpr int DNSSEEDS_DELAY_PEER_THRESHOLD = 1000; // "many" vs "few" peers
77 
79 static constexpr std::chrono::seconds MAX_UPLOAD_TIMEFRAME{60 * 60 * 24};
80 
81 // We add a random period time (0 to 1 seconds) to feeler connections to prevent synchronization.
82 #define FEELER_SLEEP_WINDOW 1
83 
85 enum BindFlags {
86  BF_NONE = 0,
87  BF_EXPLICIT = (1U << 0),
88  BF_REPORT_ERROR = (1U << 1),
93  BF_DONT_ADVERTISE = (1U << 2),
94 };
95 
96 // The set of sockets cannot be modified while waiting
97 // The sleep time needs to be small to avoid new sockets stalling
98 static const uint64_t SELECT_TIMEOUT_MILLISECONDS = 50;
99 
100 const std::string NET_MESSAGE_COMMAND_OTHER = "*other*";
101 
102 static const uint64_t RANDOMIZER_ID_NETGROUP = 0x6c0edd8036ef4036ULL; // SHA256("netgroup")[0:8]
103 static const uint64_t RANDOMIZER_ID_LOCALHOSTNONCE = 0xd93e69e2bbfa5735ULL; // SHA256("localhostnonce")[0:8]
104 static const uint64_t RANDOMIZER_ID_ADDRCACHE = 0x1cf2e4ddd306dda9ULL; // SHA256("addrcache")[0:8]
105 //
106 // Global state variables
107 //
108 bool fDiscover = true;
109 bool fListen = true;
111 std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(cs_mapLocalHost);
112 static bool vfLimited[NET_MAX] GUARDED_BY(cs_mapLocalHost) = {};
113 std::string strSubVersion;
114 
115 void CConnman::AddAddrFetch(const std::string& strDest)
116 {
118  m_addr_fetches.push_back(strDest);
119 }
120 
121 uint16_t GetListenPort()
122 {
123  return static_cast<uint16_t>(gArgs.GetArg("-port", Params().GetDefaultPort()));
124 }
125 
126 // find 'best' local address for a particular peer
127 bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
128 {
129  if (!fListen)
130  return false;
131 
132  int nBestScore = -1;
133  int nBestReachability = -1;
134  {
136  for (const auto& entry : mapLocalHost)
137  {
138  int nScore = entry.second.nScore;
139  int nReachability = entry.first.GetReachabilityFrom(paddrPeer);
140  if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
141  {
142  addr = CService(entry.first, entry.second.nPort);
143  nBestReachability = nReachability;
144  nBestScore = nScore;
145  }
146  }
147  }
148  return nBestScore >= 0;
149 }
150 
152 static std::vector<CAddress> ConvertSeeds(const std::vector<uint8_t> &vSeedsIn)
153 {
154  // It'll only connect to one or two seed nodes because once it connects,
155  // it'll get a pile of addresses with newer timestamps.
156  // Seed nodes are given a random 'last seen time' of between one and two
157  // weeks ago.
158  const int64_t nOneWeek = 7*24*60*60;
159  std::vector<CAddress> vSeedsOut;
160  FastRandomContext rng;
162  while (!s.eof()) {
163  CService endpoint;
164  s >> endpoint;
166  addr.nTime = GetTime() - rng.randrange(nOneWeek) - nOneWeek;
167  LogPrint(BCLog::NET, "Added hardcoded seed: %s\n", addr.ToString());
168  vSeedsOut.push_back(addr);
169  }
170  return vSeedsOut;
171 }
172 
173 // get best local address for a particular peer as a CAddress
174 // Otherwise, return the unroutable 0.0.0.0 but filled in with
175 // the normal parameters, since the IP may be changed to a useful
176 // one by discovery.
177 CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
178 {
179  CAddress ret(CService(CNetAddr(),GetListenPort()), nLocalServices);
180  CService addr;
181  if (GetLocal(addr, paddrPeer))
182  {
183  ret = CAddress(addr, nLocalServices);
184  }
185  ret.nTime = GetAdjustedTime();
186  return ret;
187 }
188 
189 static int GetnScore(const CService& addr)
190 {
192  if (mapLocalHost.count(addr) == 0) return 0;
193  return mapLocalHost[addr].nScore;
194 }
195 
196 // Is our peer's addrLocal potentially useful as an external IP source?
198 {
199  CService addrLocal = pnode->GetAddrLocal();
200  return fDiscover && pnode->addr.IsRoutable() && addrLocal.IsRoutable() &&
201  IsReachable(addrLocal.GetNetwork());
202 }
203 
204 std::optional<CAddress> GetLocalAddrForPeer(CNode *pnode)
205 {
206  CAddress addrLocal = GetLocalAddress(&pnode->addr, pnode->GetLocalServices());
207  if (gArgs.GetBoolArg("-addrmantest", false)) {
208  // use IPv4 loopback during addrmantest
209  addrLocal = CAddress(CService(LookupNumeric("127.0.0.1", GetListenPort())), pnode->GetLocalServices());
210  }
211  // If discovery is enabled, sometimes give our peer the address it
212  // tells us that it sees us as in case it has a better idea of our
213  // address than we do.
214  FastRandomContext rng;
215  if (IsPeerAddrLocalGood(pnode) && (!addrLocal.IsRoutable() ||
216  rng.randbits((GetnScore(addrLocal) > LOCAL_MANUAL) ? 3 : 1) == 0))
217  {
218  addrLocal.SetIP(pnode->GetAddrLocal());
219  }
220  if (addrLocal.IsRoutable() || gArgs.GetBoolArg("-addrmantest", false))
221  {
222  LogPrint(BCLog::NET, "Advertising address %s to peer=%d\n", addrLocal.ToString(), pnode->GetId());
223  return addrLocal;
224  }
225  // Address is unroutable. Don't advertise.
226  return std::nullopt;
227 }
228 
229 // learn a new local address
230 bool AddLocal(const CService& addr, int nScore)
231 {
232  if (!addr.IsRoutable())
233  return false;
234 
235  if (!fDiscover && nScore < LOCAL_MANUAL)
236  return false;
237 
238  if (!IsReachable(addr))
239  return false;
240 
241  LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore);
242 
243  {
245  bool fAlready = mapLocalHost.count(addr) > 0;
246  LocalServiceInfo &info = mapLocalHost[addr];
247  if (!fAlready || nScore >= info.nScore) {
248  info.nScore = nScore + (fAlready ? 1 : 0);
249  info.nPort = addr.GetPort();
250  }
251  }
252 
253  return true;
254 }
255 
256 bool AddLocal(const CNetAddr &addr, int nScore)
257 {
258  return AddLocal(CService(addr, GetListenPort()), nScore);
259 }
260 
261 void RemoveLocal(const CService& addr)
262 {
264  LogPrintf("RemoveLocal(%s)\n", addr.ToString());
265  mapLocalHost.erase(addr);
266 }
267 
268 void SetReachable(enum Network net, bool reachable)
269 {
270  if (net == NET_UNROUTABLE || net == NET_INTERNAL)
271  return;
273  vfLimited[net] = !reachable;
274 }
275 
276 bool IsReachable(enum Network net)
277 {
279  return !vfLimited[net];
280 }
281 
282 bool IsReachable(const CNetAddr &addr)
283 {
284  return IsReachable(addr.GetNetwork());
285 }
286 
288 bool SeenLocal(const CService& addr)
289 {
290  {
292  if (mapLocalHost.count(addr) == 0)
293  return false;
294  mapLocalHost[addr].nScore++;
295  }
296  return true;
297 }
298 
299 
301 bool IsLocal(const CService& addr)
302 {
304  return mapLocalHost.count(addr) > 0;
305 }
306 
308 {
309  LOCK(cs_vNodes);
310  for (CNode* pnode : vNodes) {
311  if (static_cast<CNetAddr>(pnode->addr) == ip) {
312  return pnode;
313  }
314  }
315  return nullptr;
316 }
317 
319 {
320  LOCK(cs_vNodes);
321  for (CNode* pnode : vNodes) {
322  if (subNet.Match(static_cast<CNetAddr>(pnode->addr))) {
323  return pnode;
324  }
325  }
326  return nullptr;
327 }
328 
329 CNode* CConnman::FindNode(const std::string& addrName)
330 {
331  LOCK(cs_vNodes);
332  for (CNode* pnode : vNodes) {
333  if (pnode->GetAddrName() == addrName) {
334  return pnode;
335  }
336  }
337  return nullptr;
338 }
339 
341 {
342  LOCK(cs_vNodes);
343  for (CNode* pnode : vNodes) {
344  if (static_cast<CService>(pnode->addr) == addr) {
345  return pnode;
346  }
347  }
348  return nullptr;
349 }
350 
352 {
353  return FindNode(static_cast<CNetAddr>(addr)) || FindNode(addr.ToStringIPPort());
354 }
355 
356 bool CConnman::CheckIncomingNonce(uint64_t nonce)
357 {
358  LOCK(cs_vNodes);
359  for (const CNode* pnode : vNodes) {
360  if (!pnode->fSuccessfullyConnected && !pnode->IsInboundConn() && pnode->GetLocalNonce() == nonce)
361  return false;
362  }
363  return true;
364 }
365 
368 {
369  CAddress addr_bind;
370  struct sockaddr_storage sockaddr_bind;
371  socklen_t sockaddr_bind_len = sizeof(sockaddr_bind);
372  if (sock != INVALID_SOCKET) {
373  if (!getsockname(sock, (struct sockaddr*)&sockaddr_bind, &sockaddr_bind_len)) {
374  addr_bind.SetSockAddr((const struct sockaddr*)&sockaddr_bind);
375  } else {
376  LogPrint(BCLog::NET, "Warning: getsockname failed\n");
377  }
378  }
379  return addr_bind;
380 }
381 
382 CNode* CConnman::ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type)
383 {
384  assert(conn_type != ConnectionType::INBOUND);
385 
386  if (pszDest == nullptr) {
387  if (IsLocal(addrConnect))
388  return nullptr;
389 
390  // Look for an existing connection
391  CNode* pnode = FindNode(static_cast<CService>(addrConnect));
392  if (pnode)
393  {
394  LogPrintf("Failed to open new connection, already connected\n");
395  return nullptr;
396  }
397  }
398 
400  LogPrint(BCLog::NET, "trying connection %s lastseen=%.1fhrs\n",
401  pszDest ? pszDest : addrConnect.ToString(),
402  pszDest ? 0.0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
403 
404  // Resolve
405  const uint16_t default_port{pszDest != nullptr ? Params().GetDefaultPort(pszDest) :
406  Params().GetDefaultPort()};
407  if (pszDest) {
408  std::vector<CService> resolved;
409  if (Lookup(pszDest, resolved, default_port, fNameLookup && !HaveNameProxy(), 256) && !resolved.empty()) {
410  addrConnect = CAddress(resolved[GetRand(resolved.size())], NODE_NONE);
411  if (!addrConnect.IsValid()) {
412  LogPrint(BCLog::NET, "Resolver returned invalid address %s for %s\n", addrConnect.ToString(), pszDest);
413  return nullptr;
414  }
415  // It is possible that we already have a connection to the IP/port pszDest resolved to.
416  // In that case, drop the connection that was just created, and return the existing CNode instead.
417  // Also store the name we used to connect in that CNode, so that future FindNode() calls to that
418  // name catch this early.
419  LOCK(cs_vNodes);
420  CNode* pnode = FindNode(static_cast<CService>(addrConnect));
421  if (pnode)
422  {
423  pnode->MaybeSetAddrName(std::string(pszDest));
424  LogPrintf("Failed to open new connection, already connected\n");
425  return nullptr;
426  }
427  }
428  }
429 
430  // Connect
431  bool connected = false;
432  std::unique_ptr<Sock> sock;
433  proxyType proxy;
434  CAddress addr_bind;
435  assert(!addr_bind.IsValid());
436 
437  if (addrConnect.IsValid()) {
438  bool proxyConnectionFailed = false;
439 
440  if (addrConnect.GetNetwork() == NET_I2P && m_i2p_sam_session.get() != nullptr) {
441  i2p::Connection conn;
442  if (m_i2p_sam_session->Connect(addrConnect, conn, proxyConnectionFailed)) {
443  connected = true;
444  sock = std::move(conn.sock);
445  addr_bind = CAddress{conn.me, NODE_NONE};
446  }
447  } else if (GetProxy(addrConnect.GetNetwork(), proxy)) {
448  sock = CreateSock(proxy.proxy);
449  if (!sock) {
450  return nullptr;
451  }
452  connected = ConnectThroughProxy(proxy, addrConnect.ToStringIP(), addrConnect.GetPort(),
453  *sock, nConnectTimeout, proxyConnectionFailed);
454  } else {
455  // no proxy needed (none set for target network)
456  sock = CreateSock(addrConnect);
457  if (!sock) {
458  return nullptr;
459  }
460  connected = ConnectSocketDirectly(addrConnect, *sock, nConnectTimeout,
461  conn_type == ConnectionType::MANUAL);
462  }
463  if (!proxyConnectionFailed) {
464  // If a connection to the node was attempted, and failure (if any) is not caused by a problem connecting to
465  // the proxy, mark this as an attempt.
466  addrman.Attempt(addrConnect, fCountFailure);
467  }
468  } else if (pszDest && GetNameProxy(proxy)) {
469  sock = CreateSock(proxy.proxy);
470  if (!sock) {
471  return nullptr;
472  }
473  std::string host;
474  uint16_t port{default_port};
475  SplitHostPort(std::string(pszDest), port, host);
476  bool proxyConnectionFailed;
477  connected = ConnectThroughProxy(proxy, host, port, *sock, nConnectTimeout,
478  proxyConnectionFailed);
479  }
480  if (!connected) {
481  return nullptr;
482  }
483 
484  // Add node
485  NodeId id = GetNewNodeId();
487  if (!addr_bind.IsValid()) {
488  addr_bind = GetBindAddress(sock->Get());
489  }
490  CNode* pnode = new CNode(id, nLocalServices, sock->Release(), addrConnect, CalculateKeyedNetGroup(addrConnect), nonce, addr_bind, pszDest ? pszDest : "", conn_type, /* inbound_onion */ false);
491  pnode->AddRef();
492 
493  // We're making a new connection, harvest entropy from the time (and our peer count)
494  RandAddEvent((uint32_t)id);
495 
496  return pnode;
497 }
498 
500 {
501  fDisconnect = true;
502  LOCK(cs_hSocket);
503  if (hSocket != INVALID_SOCKET)
504  {
505  LogPrint(BCLog::NET, "disconnecting peer=%d\n", id);
506  CloseSocket(hSocket);
507  }
508 }
509 
511  for (const auto& subnet : vWhitelistedRange) {
512  if (subnet.m_subnet.Match(addr)) NetPermissions::AddFlag(flags, subnet.m_flags);
513  }
514 }
515 
517 {
518  switch (conn_type) {
520  return "inbound";
522  return "manual";
524  return "feeler";
526  return "outbound-full-relay";
528  return "block-relay-only";
530  return "addr-fetch";
531  } // no default case, so the compiler can warn about missing cases
532 
533  assert(false);
534 }
535 
536 std::string CNode::GetAddrName() const {
537  LOCK(cs_addrName);
538  return addrName;
539 }
540 
541 void CNode::MaybeSetAddrName(const std::string& addrNameIn) {
542  LOCK(cs_addrName);
543  if (addrName.empty()) {
544  addrName = addrNameIn;
545  }
546 }
547 
550  return addrLocal;
551 }
552 
553 void CNode::SetAddrLocal(const CService& addrLocalIn) {
555  if (addrLocal.IsValid()) {
556  error("Addr local already set for node: %i. Refusing to change from %s to %s", id, addrLocal.ToString(), addrLocalIn.ToString());
557  } else {
558  addrLocal = addrLocalIn;
559  }
560 }
561 
563 {
565 }
566 
567 #undef X
568 #define X(name) stats.name = name
569 void CNode::copyStats(CNodeStats &stats, const std::vector<bool> &m_asmap)
570 {
571  stats.nodeid = this->GetId();
572  X(nServices);
573  X(addr);
574  X(addrBind);
576  stats.m_mapped_as = addr.GetMappedAS(m_asmap);
577  if (m_tx_relay != nullptr) {
578  LOCK(m_tx_relay->cs_filter);
579  stats.fRelayTxes = m_tx_relay->fRelayTxes;
580  } else {
581  stats.fRelayTxes = false;
582  }
583  X(nLastSend);
584  X(nLastRecv);
585  X(nLastTXTime);
586  X(nLastBlockTime);
587  X(nTimeConnected);
588  X(nTimeOffset);
589  stats.addrName = GetAddrName();
590  X(nVersion);
591  {
592  LOCK(cs_SubVer);
593  X(cleanSubVer);
594  }
595  stats.fInbound = IsInboundConn();
598  {
599  LOCK(cs_vSend);
600  X(mapSendBytesPerMsgCmd);
601  X(nSendBytes);
602  }
603  {
604  LOCK(cs_vRecv);
605  X(mapRecvBytesPerMsgCmd);
606  X(nRecvBytes);
607  }
609  if (m_tx_relay != nullptr) {
610  stats.minFeeFilter = m_tx_relay->minFeeFilter;
611  } else {
612  stats.minFeeFilter = 0;
613  }
614 
617 
618  // Leave string empty if addrLocal invalid (not filled in yet)
619  CService addrLocalUnlocked = GetAddrLocal();
620  stats.addrLocal = addrLocalUnlocked.IsValid() ? addrLocalUnlocked.ToString() : "";
621 
622  X(m_conn_type);
623 }
624 #undef X
625 
626 bool CNode::ReceiveMsgBytes(Span<const uint8_t> msg_bytes, bool& complete)
627 {
628  complete = false;
629  const auto time = GetTime<std::chrono::microseconds>();
630  LOCK(cs_vRecv);
631  nLastRecv = std::chrono::duration_cast<std::chrono::seconds>(time).count();
632  nRecvBytes += msg_bytes.size();
633  while (msg_bytes.size() > 0) {
634  // absorb network data
635  int handled = m_deserializer->Read(msg_bytes);
636  if (handled < 0) {
637  // Serious header problem, disconnect from the peer.
638  return false;
639  }
640 
641  if (m_deserializer->Complete()) {
642  // decompose a transport agnostic CNetMessage from the deserializer
643  uint32_t out_err_raw_size{0};
644  std::optional<CNetMessage> result{m_deserializer->GetMessage(time, out_err_raw_size)};
645  if (!result) {
646  // Message deserialization failed. Drop the message but don't disconnect the peer.
647  // store the size of the corrupt message
648  mapRecvBytesPerMsgCmd.find(NET_MESSAGE_COMMAND_OTHER)->second += out_err_raw_size;
649  continue;
650  }
651 
652  //store received bytes per message command
653  //to prevent a memory DOS, only allow valid commands
654  mapMsgCmdSize::iterator i = mapRecvBytesPerMsgCmd.find(result->m_command);
655  if (i == mapRecvBytesPerMsgCmd.end())
656  i = mapRecvBytesPerMsgCmd.find(NET_MESSAGE_COMMAND_OTHER);
657  assert(i != mapRecvBytesPerMsgCmd.end());
658  i->second += result->m_raw_message_size;
659 
660  // push the message to the process queue,
661  vRecvMsg.push_back(std::move(*result));
662 
663  complete = true;
664  }
665  }
666 
667  return true;
668 }
669 
671 {
672  // copy data to temporary parsing buffer
673  unsigned int nRemaining = CMessageHeader::HEADER_SIZE - nHdrPos;
674  unsigned int nCopy = std::min<unsigned int>(nRemaining, msg_bytes.size());
675 
676  memcpy(&hdrbuf[nHdrPos], msg_bytes.data(), nCopy);
677  nHdrPos += nCopy;
678 
679  // if header incomplete, exit
681  return nCopy;
682 
683  // deserialize to CMessageHeader
684  try {
685  hdrbuf >> hdr;
686  }
687  catch (const std::exception&) {
688  LogPrint(BCLog::NET, "Header error: Unable to deserialize, peer=%d\n", m_node_id);
689  return -1;
690  }
691 
692  // Check start string, network magic
694  LogPrint(BCLog::NET, "Header error: Wrong MessageStart %s received, peer=%d\n", HexStr(hdr.pchMessageStart), m_node_id);
695  return -1;
696  }
697 
698  // reject messages larger than MAX_SIZE or MAX_PROTOCOL_MESSAGE_LENGTH
700  LogPrint(BCLog::NET, "Header error: Size too large (%s, %u bytes), peer=%d\n", SanitizeString(hdr.GetCommand()), hdr.nMessageSize, m_node_id);
701  return -1;
702  }
703 
704  // switch state to reading message data
705  in_data = true;
706 
707  return nCopy;
708 }
709 
711 {
712  unsigned int nRemaining = hdr.nMessageSize - nDataPos;
713  unsigned int nCopy = std::min<unsigned int>(nRemaining, msg_bytes.size());
714 
715  if (vRecv.size() < nDataPos + nCopy) {
716  // Allocate up to 256 KiB ahead, but never more than the total message size.
717  vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024));
718  }
719 
720  hasher.Write(msg_bytes.first(nCopy));
721  memcpy(&vRecv[nDataPos], msg_bytes.data(), nCopy);
722  nDataPos += nCopy;
723 
724  return nCopy;
725 }
726 
728 {
729  assert(Complete());
730  if (data_hash.IsNull())
732  return data_hash;
733 }
734 
735 std::optional<CNetMessage> V1TransportDeserializer::GetMessage(const std::chrono::microseconds time, uint32_t& out_err_raw_size)
736 {
737  // decompose a single CNetMessage from the TransportDeserializer
738  std::optional<CNetMessage> msg(std::move(vRecv));
739 
740  // store command string, time, and sizes
741  msg->m_command = hdr.GetCommand();
742  msg->m_time = time;
743  msg->m_message_size = hdr.nMessageSize;
744  msg->m_raw_message_size = hdr.nMessageSize + CMessageHeader::HEADER_SIZE;
745 
746  uint256 hash = GetMessageHash();
747 
748  // We just received a message off the wire, harvest entropy from the time (and the message checksum)
749  RandAddEvent(ReadLE32(hash.begin()));
750 
751  // Check checksum and header command string
752  if (memcmp(hash.begin(), hdr.pchChecksum, CMessageHeader::CHECKSUM_SIZE) != 0) {
753  LogPrint(BCLog::NET, "Header error: Wrong checksum (%s, %u bytes), expected %s was %s, peer=%d\n",
754  SanitizeString(msg->m_command), msg->m_message_size,
757  m_node_id);
758  out_err_raw_size = msg->m_raw_message_size;
759  msg = std::nullopt;
760  } else if (!hdr.IsCommandValid()) {
761  LogPrint(BCLog::NET, "Header error: Invalid message type (%s, %u bytes), peer=%d\n",
762  SanitizeString(hdr.GetCommand()), msg->m_message_size, m_node_id);
763  out_err_raw_size = msg->m_raw_message_size;
764  msg.reset();
765  }
766 
767  // Always reset the network deserializer (prepare for the next message)
768  Reset();
769  return msg;
770 }
771 
772 void V1TransportSerializer::prepareForTransport(CSerializedNetMsg& msg, std::vector<unsigned char>& header) {
773  // create dbl-sha256 checksum
774  uint256 hash = Hash(msg.data);
775 
776  // create header
777  CMessageHeader hdr(Params().MessageStart(), msg.m_type.c_str(), msg.data.size());
778  memcpy(hdr.pchChecksum, hash.begin(), CMessageHeader::CHECKSUM_SIZE);
779 
780  // serialize header
781  header.reserve(CMessageHeader::HEADER_SIZE);
782  CVectorWriter{SER_NETWORK, INIT_PROTO_VERSION, header, 0, hdr};
783 }
784 
786 {
787  auto it = node.vSendMsg.begin();
788  size_t nSentSize = 0;
789 
790  while (it != node.vSendMsg.end()) {
791  const auto& data = *it;
792  assert(data.size() > node.nSendOffset);
793  int nBytes = 0;
794  {
795  LOCK(node.cs_hSocket);
796  if (node.hSocket == INVALID_SOCKET)
797  break;
798  nBytes = send(node.hSocket, reinterpret_cast<const char*>(data.data()) + node.nSendOffset, data.size() - node.nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT);
799  }
800  if (nBytes > 0) {
801  node.nLastSend = GetTimeSeconds();
802  node.nSendBytes += nBytes;
803  node.nSendOffset += nBytes;
804  nSentSize += nBytes;
805  if (node.nSendOffset == data.size()) {
806  node.nSendOffset = 0;
807  node.nSendSize -= data.size();
808  node.fPauseSend = node.nSendSize > nSendBufferMaxSize;
809  it++;
810  } else {
811  // could not send full message; stop sending more
812  break;
813  }
814  } else {
815  if (nBytes < 0) {
816  // error
817  int nErr = WSAGetLastError();
818  if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) {
819  LogPrint(BCLog::NET, "socket send error for peer=%d: %s\n", node.GetId(), NetworkErrorString(nErr));
820  node.CloseSocketDisconnect();
821  }
822  }
823  // couldn't send anything at all
824  break;
825  }
826  }
827 
828  if (it == node.vSendMsg.end()) {
829  assert(node.nSendOffset == 0);
830  assert(node.nSendSize == 0);
831  }
832  node.vSendMsg.erase(node.vSendMsg.begin(), it);
833  return nSentSize;
834 }
835 
837 {
838  return a.m_min_ping_time > b.m_min_ping_time;
839 }
840 
842 {
843  return a.nTimeConnected > b.nTimeConnected;
844 }
845 
847  return a.nKeyedNetGroup < b.nKeyedNetGroup;
848 }
849 
851 {
852  // There is a fall-through here because it is common for a node to have many peers which have not yet relayed a block.
855  return a.nTimeConnected > b.nTimeConnected;
856 }
857 
859 {
860  // 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.
861  if (a.nLastTXTime != b.nLastTXTime) return a.nLastTXTime < b.nLastTXTime;
862  if (a.fRelayTxes != b.fRelayTxes) return b.fRelayTxes;
863  if (a.fBloomFilter != b.fBloomFilter) return a.fBloomFilter;
864  return a.nTimeConnected > b.nTimeConnected;
865 }
866 
867 // Pick out the potential block-relay only peers, and sort them by last block time.
869 {
870  if (a.fRelayTxes != b.fRelayTxes) return a.fRelayTxes;
873  return a.nTimeConnected > b.nTimeConnected;
874 }
875 
885  const bool m_is_local;
887  CompareNodeNetworkTime(bool is_local, Network network) : m_is_local(is_local), m_network(network) {}
889  {
890  if (m_is_local && a.m_is_local != b.m_is_local) return b.m_is_local;
891  if ((a.m_network == m_network) != (b.m_network == m_network)) return b.m_network == m_network;
892  return a.nTimeConnected > b.nTimeConnected;
893  };
894 };
895 
897 template <typename T, typename Comparator>
898 static void EraseLastKElements(
899  std::vector<T>& elements, Comparator comparator, size_t k,
900  std::function<bool(const NodeEvictionCandidate&)> predicate = [](const NodeEvictionCandidate& n) { return true; })
901 {
902  std::sort(elements.begin(), elements.end(), comparator);
903  size_t eraseSize = std::min(k, elements.size());
904  elements.erase(std::remove_if(elements.end() - eraseSize, elements.end(), predicate), elements.end());
905 }
906 
907 void ProtectEvictionCandidatesByRatio(std::vector<NodeEvictionCandidate>& eviction_candidates)
908 {
909  // Protect the half of the remaining nodes which have been connected the longest.
910  // This replicates the non-eviction implicit behavior, and precludes attacks that start later.
911  // To favorise the diversity of our peer connections, reserve up to half of these protected
912  // spots for Tor/onion, localhost and I2P peers, even if they're not longest uptime overall.
913  // This helps protect these higher-latency peers that tend to be otherwise
914  // disadvantaged under our eviction criteria.
915  const size_t initial_size = eviction_candidates.size();
916  const size_t total_protect_size{initial_size / 2};
917 
918  // Disadvantaged networks to protect: I2P, localhost, Tor/onion. In case of equal counts, earlier
919  // array members have first opportunity to recover unused slots from the previous iteration.
920  struct Net { bool is_local; Network id; size_t count; };
921  std::array<Net, 3> networks{
922  {{false, NET_I2P, 0}, {/* localhost */ true, NET_MAX, 0}, {false, NET_ONION, 0}}};
923 
924  // Count and store the number of eviction candidates per network.
925  for (Net& n : networks) {
926  n.count = std::count_if(eviction_candidates.cbegin(), eviction_candidates.cend(),
927  [&n](const NodeEvictionCandidate& c) {
928  return n.is_local ? c.m_is_local : c.m_network == n.id;
929  });
930  }
931  // Sort `networks` by ascending candidate count, to give networks having fewer candidates
932  // the first opportunity to recover unused protected slots from the previous iteration.
933  std::stable_sort(networks.begin(), networks.end(), [](Net a, Net b) { return a.count < b.count; });
934 
935  // Protect up to 25% of the eviction candidates by disadvantaged network.
936  const size_t max_protect_by_network{total_protect_size / 2};
937  size_t num_protected{0};
938 
939  while (num_protected < max_protect_by_network) {
940  // Count the number of disadvantaged networks from which we have peers to protect.
941  auto num_networks = std::count_if(networks.begin(), networks.end(), [](const Net& n) { return n.count; });
942  if (num_networks == 0) {
943  break;
944  }
945  const size_t disadvantaged_to_protect{max_protect_by_network - num_protected};
946  const size_t protect_per_network{std::max(disadvantaged_to_protect / num_networks, static_cast<size_t>(1))};
947  // Early exit flag if there are no remaining candidates by disadvantaged network.
948  bool protected_at_least_one{false};
949 
950  for (Net& n : networks) {
951  if (n.count == 0) continue;
952  const size_t before = eviction_candidates.size();
953  EraseLastKElements(eviction_candidates, CompareNodeNetworkTime(n.is_local, n.id),
954  protect_per_network, [&n](const NodeEvictionCandidate& c) {
955  return n.is_local ? c.m_is_local : c.m_network == n.id;
956  });
957  const size_t after = eviction_candidates.size();
958  if (before > after) {
959  protected_at_least_one = true;
960  const size_t delta{before - after};
961  num_protected += delta;
962  if (num_protected >= max_protect_by_network) {
963  break;
964  }
965  n.count -= delta;
966  }
967  }
968  if (!protected_at_least_one) {
969  break;
970  }
971  }
972 
973  // Calculate how many we removed, and update our total number of peers that
974  // we want to protect based on uptime accordingly.
975  assert(num_protected == initial_size - eviction_candidates.size());
976  const size_t remaining_to_protect{total_protect_size - num_protected};
977  EraseLastKElements(eviction_candidates, ReverseCompareNodeTimeConnected, remaining_to_protect);
978 }
979 
980 [[nodiscard]] std::optional<NodeId> SelectNodeToEvict(std::vector<NodeEvictionCandidate>&& vEvictionCandidates)
981 {
982  // Protect connections with certain characteristics
983 
984  // Deterministically select 4 peers to protect by netgroup.
985  // An attacker cannot predict which netgroups will be protected
986  EraseLastKElements(vEvictionCandidates, CompareNetGroupKeyed, 4);
987  // Protect the 8 nodes with the lowest minimum ping time.
988  // An attacker cannot manipulate this metric without physically moving nodes closer to the target.
989  EraseLastKElements(vEvictionCandidates, ReverseCompareNodeMinPingTime, 8);
990  // Protect 4 nodes that most recently sent us novel transactions accepted into our mempool.
991  // An attacker cannot manipulate this metric without performing useful work.
992  EraseLastKElements(vEvictionCandidates, CompareNodeTXTime, 4);
993  // Protect up to 8 non-tx-relay peers that have sent us novel blocks.
994  EraseLastKElements(vEvictionCandidates, CompareNodeBlockRelayOnlyTime, 8,
995  [](const NodeEvictionCandidate& n) { return !n.fRelayTxes && n.fRelevantServices; });
996 
997  // Protect 4 nodes that most recently sent us novel blocks.
998  // An attacker cannot manipulate this metric without performing useful work.
999  EraseLastKElements(vEvictionCandidates, CompareNodeBlockTime, 4);
1000 
1001  // Protect some of the remaining eviction candidates by ratios of desirable
1002  // or disadvantaged characteristics.
1003  ProtectEvictionCandidatesByRatio(vEvictionCandidates);
1004 
1005  if (vEvictionCandidates.empty()) return std::nullopt;
1006 
1007  // If any remaining peers are preferred for eviction consider only them.
1008  // This happens after the other preferences since if a peer is really the best by other criteria (esp relaying blocks)
1009  // then we probably don't want to evict it no matter what.
1010  if (std::any_of(vEvictionCandidates.begin(),vEvictionCandidates.end(),[](NodeEvictionCandidate const &n){return n.prefer_evict;})) {
1011  vEvictionCandidates.erase(std::remove_if(vEvictionCandidates.begin(),vEvictionCandidates.end(),
1012  [](NodeEvictionCandidate const &n){return !n.prefer_evict;}),vEvictionCandidates.end());
1013  }
1014 
1015  // Identify the network group with the most connections and youngest member.
1016  // (vEvictionCandidates is already sorted by reverse connect time)
1017  uint64_t naMostConnections;
1018  unsigned int nMostConnections = 0;
1019  int64_t nMostConnectionsTime = 0;
1020  std::map<uint64_t, std::vector<NodeEvictionCandidate> > mapNetGroupNodes;
1021  for (const NodeEvictionCandidate &node : vEvictionCandidates) {
1022  std::vector<NodeEvictionCandidate> &group = mapNetGroupNodes[node.nKeyedNetGroup];
1023  group.push_back(node);
1024  const int64_t grouptime = group[0].nTimeConnected;
1025 
1026  if (group.size() > nMostConnections || (group.size() == nMostConnections && grouptime > nMostConnectionsTime)) {
1027  nMostConnections = group.size();
1028  nMostConnectionsTime = grouptime;
1029  naMostConnections = node.nKeyedNetGroup;
1030  }
1031  }
1032 
1033  // Reduce to the network group with the most connections
1034  vEvictionCandidates = std::move(mapNetGroupNodes[naMostConnections]);
1035 
1036  // Disconnect from the network group with the most connections
1037  return vEvictionCandidates.front().id;
1038 }
1039 
1049 {
1050  std::vector<NodeEvictionCandidate> vEvictionCandidates;
1051  {
1052 
1053  LOCK(cs_vNodes);
1054  for (const CNode* node : vNodes) {
1055  if (node->HasPermission(NetPermissionFlags::NoBan))
1056  continue;
1057  if (!node->IsInboundConn())
1058  continue;
1059  if (node->fDisconnect)
1060  continue;
1061  bool peer_relay_txes = false;
1062  bool peer_filter_not_null = false;
1063  if (node->m_tx_relay != nullptr) {
1064  LOCK(node->m_tx_relay->cs_filter);
1065  peer_relay_txes = node->m_tx_relay->fRelayTxes;
1066  peer_filter_not_null = node->m_tx_relay->pfilter != nullptr;
1067  }
1068  NodeEvictionCandidate candidate = {node->GetId(), node->nTimeConnected, node->m_min_ping_time,
1069  node->nLastBlockTime, node->nLastTXTime,
1070  HasAllDesirableServiceFlags(node->nServices),
1071  peer_relay_txes, peer_filter_not_null, node->nKeyedNetGroup,
1072  node->m_prefer_evict, node->addr.IsLocal(),
1073  node->ConnectedThroughNetwork()};
1074  vEvictionCandidates.push_back(candidate);
1075  }
1076  }
1077  const std::optional<NodeId> node_id_to_evict = SelectNodeToEvict(std::move(vEvictionCandidates));
1078  if (!node_id_to_evict) {
1079  return false;
1080  }
1081  LOCK(cs_vNodes);
1082  for (CNode* pnode : vNodes) {
1083  if (pnode->GetId() == *node_id_to_evict) {
1084  LogPrint(BCLog::NET, "selected %s connection for eviction peer=%d; disconnecting\n", pnode->ConnectionTypeAsString(), pnode->GetId());
1085  pnode->fDisconnect = true;
1086  return true;
1087  }
1088  }
1089  return false;
1090 }
1091 
1092 void CConnman::AcceptConnection(const ListenSocket& hListenSocket) {
1093  struct sockaddr_storage sockaddr;
1094  socklen_t len = sizeof(sockaddr);
1095  SOCKET hSocket = accept(hListenSocket.socket, (struct sockaddr*)&sockaddr, &len);
1096  CAddress addr;
1097 
1098  if (hSocket == INVALID_SOCKET) {
1099  const int nErr = WSAGetLastError();
1100  if (nErr != WSAEWOULDBLOCK) {
1101  LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr));
1102  }
1103  return;
1104  }
1105 
1106  if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr)) {
1107  LogPrintf("Warning: Unknown socket family\n");
1108  }
1109 
1110  const CAddress addr_bind = GetBindAddress(hSocket);
1111 
1112  NetPermissionFlags permissionFlags = NetPermissionFlags::None;
1113  hListenSocket.AddSocketPermissionFlags(permissionFlags);
1114 
1115  CreateNodeFromAcceptedSocket(hSocket, permissionFlags, addr_bind, addr);
1116 }
1117 
1119  NetPermissionFlags permissionFlags,
1120  const CAddress& addr_bind,
1121  const CAddress& addr)
1122 {
1123  int nInbound = 0;
1124  int nMaxInbound = nMaxConnections - m_max_outbound;
1125 
1126  AddWhitelistPermissionFlags(permissionFlags, addr);
1127  if (NetPermissions::HasFlag(permissionFlags, NetPermissionFlags::Implicit)) {
1133  }
1134 
1135  {
1136  LOCK(cs_vNodes);
1137  for (const CNode* pnode : vNodes) {
1138  if (pnode->IsInboundConn()) nInbound++;
1139  }
1140  }
1141 
1142  if (!fNetworkActive) {
1143  LogPrint(BCLog::NET, "connection from %s dropped: not accepting new connections\n", addr.ToString());
1144  CloseSocket(hSocket);
1145  return;
1146  }
1147 
1148  if (!IsSelectableSocket(hSocket))
1149  {
1150  LogPrintf("connection from %s dropped: non-selectable socket\n", addr.ToString());
1151  CloseSocket(hSocket);
1152  return;
1153  }
1154 
1155  // According to the internet TCP_NODELAY is not carried into accepted sockets
1156  // on all platforms. Set it again here just to be sure.
1157  SetSocketNoDelay(hSocket);
1158 
1159  // Don't accept connections from banned peers.
1160  bool banned = m_banman && m_banman->IsBanned(addr);
1161  if (!NetPermissions::HasFlag(permissionFlags, NetPermissionFlags::NoBan) && banned)
1162  {
1163  LogPrint(BCLog::NET, "connection from %s dropped (banned)\n", addr.ToString());
1164  CloseSocket(hSocket);
1165  return;
1166  }
1167 
1168  // Only accept connections from discouraged peers if our inbound slots aren't (almost) full.
1169  bool discouraged = m_banman && m_banman->IsDiscouraged(addr);
1170  if (!NetPermissions::HasFlag(permissionFlags, NetPermissionFlags::NoBan) && nInbound + 1 >= nMaxInbound && discouraged)
1171  {
1172  LogPrint(BCLog::NET, "connection from %s dropped (discouraged)\n", addr.ToString());
1173  CloseSocket(hSocket);
1174  return;
1175  }
1176 
1177  if (nInbound >= nMaxInbound)
1178  {
1179  if (!AttemptToEvictConnection()) {
1180  // No connection to evict, disconnect the new connection
1181  LogPrint(BCLog::NET, "failed to find an eviction candidate - connection dropped (full)\n");
1182  CloseSocket(hSocket);
1183  return;
1184  }
1185  }
1186 
1187  NodeId id = GetNewNodeId();
1189 
1190  ServiceFlags nodeServices = nLocalServices;
1192  nodeServices = static_cast<ServiceFlags>(nodeServices | NODE_BLOOM);
1193  }
1194 
1195  const bool inbound_onion = std::find(m_onion_binds.begin(), m_onion_binds.end(), addr_bind) != m_onion_binds.end();
1196  CNode* pnode = new CNode(id, nodeServices, hSocket, addr, CalculateKeyedNetGroup(addr), nonce, addr_bind, "", ConnectionType::INBOUND, inbound_onion);
1197  pnode->AddRef();
1198  pnode->m_permissionFlags = permissionFlags;
1199  pnode->m_prefer_evict = discouraged;
1200  m_msgproc->InitializeNode(pnode);
1201 
1202  LogPrint(BCLog::NET, "connection from %s accepted\n", addr.ToString());
1203 
1204  {
1205  LOCK(cs_vNodes);
1206  vNodes.push_back(pnode);
1207  }
1208 
1209  // We received a new connection, harvest entropy from the time (and our peer count)
1210  RandAddEvent((uint32_t)id);
1211 }
1212 
1213 bool CConnman::AddConnection(const std::string& address, ConnectionType conn_type)
1214 {
1215  std::optional<int> max_connections;
1216  switch (conn_type) {
1220  return false;
1222  max_connections = m_max_outbound_full_relay;
1223  break;
1225  max_connections = m_max_outbound_block_relay;
1226  break;
1227  // no limit for ADDR_FETCH because -seednode has no limit either
1229  break;
1230  } // no default case, so the compiler can warn about missing cases
1231 
1232  // Count existing connections
1233  int existing_connections = WITH_LOCK(cs_vNodes,
1234  return std::count_if(vNodes.begin(), vNodes.end(), [conn_type](CNode* node) { return node->m_conn_type == conn_type; }););
1235 
1236  // Max connections of specified type already exist
1237  if (max_connections != std::nullopt && existing_connections >= max_connections) return false;
1238 
1239  // Max total outbound connections already exist
1240  CSemaphoreGrant grant(*semOutbound, true);
1241  if (!grant) return false;
1242 
1243  OpenNetworkConnection(CAddress(), false, &grant, address.c_str(), conn_type);
1244  return true;
1245 }
1246 
1248 {
1249  {
1250  LOCK(cs_vNodes);
1251 
1252  if (!fNetworkActive) {
1253  // Disconnect any connected nodes
1254  for (CNode* pnode : vNodes) {
1255  if (!pnode->fDisconnect) {
1256  LogPrint(BCLog::NET, "Network not active, dropping peer=%d\n", pnode->GetId());
1257  pnode->fDisconnect = true;
1258  }
1259  }
1260  }
1261 
1262  // Disconnect unused nodes
1263  std::vector<CNode*> vNodesCopy = vNodes;
1264  for (CNode* pnode : vNodesCopy)
1265  {
1266  if (pnode->fDisconnect)
1267  {
1268  // remove from vNodes
1269  vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
1270 
1271  // release outbound grant (if any)
1272  pnode->grantOutbound.Release();
1273 
1274  // close socket and cleanup
1275  pnode->CloseSocketDisconnect();
1276 
1277  // hold in disconnected pool until all refs are released
1278  pnode->Release();
1279  vNodesDisconnected.push_back(pnode);
1280  }
1281  }
1282  }
1283  {
1284  // Delete disconnected nodes
1285  std::list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
1286  for (CNode* pnode : vNodesDisconnectedCopy)
1287  {
1288  // Destroy the object only after other threads have stopped using it.
1289  if (pnode->GetRefCount() <= 0) {
1290  vNodesDisconnected.remove(pnode);
1291  DeleteNode(pnode);
1292  }
1293  }
1294  }
1295 }
1296 
1298 {
1299  size_t vNodesSize;
1300  {
1301  LOCK(cs_vNodes);
1302  vNodesSize = vNodes.size();
1303  }
1304  if(vNodesSize != nPrevNodeCount) {
1305  nPrevNodeCount = vNodesSize;
1306  if(clientInterface)
1307  clientInterface->NotifyNumConnectionsChanged(vNodesSize);
1308  }
1309 }
1310 
1311 bool CConnman::ShouldRunInactivityChecks(const CNode& node, std::optional<int64_t> now_in) const
1312 {
1313  const int64_t now = now_in ? now_in.value() : GetTimeSeconds();
1314  return node.nTimeConnected + m_peer_connect_timeout < now;
1315 }
1316 
1318 {
1319  // Use non-mockable system time (otherwise these timers will pop when we
1320  // use setmocktime in the tests).
1321  int64_t now = GetTimeSeconds();
1322 
1323  if (!ShouldRunInactivityChecks(node, now)) return false;
1324 
1325  if (node.nLastRecv == 0 || node.nLastSend == 0) {
1326  LogPrint(BCLog::NET, "socket no message in first %i seconds, %d %d peer=%d\n", m_peer_connect_timeout, node.nLastRecv != 0, node.nLastSend != 0, node.GetId());
1327  return true;
1328  }
1329 
1330  if (now > node.nLastSend + TIMEOUT_INTERVAL) {
1331  LogPrint(BCLog::NET, "socket sending timeout: %is peer=%d\n", now - node.nLastSend, node.GetId());
1332  return true;
1333  }
1334 
1335  if (now > node.nLastRecv + TIMEOUT_INTERVAL) {
1336  LogPrint(BCLog::NET, "socket receive timeout: %is peer=%d\n", now - node.nLastRecv, node.GetId());
1337  return true;
1338  }
1339 
1340  if (!node.fSuccessfullyConnected) {
1341  LogPrint(BCLog::NET, "version handshake timeout peer=%d\n", node.GetId());
1342  return true;
1343  }
1344 
1345  return false;
1346 }
1347 
1348 bool CConnman::GenerateSelectSet(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set)
1349 {
1350  for (const ListenSocket& hListenSocket : vhListenSocket) {
1351  recv_set.insert(hListenSocket.socket);
1352  }
1353 
1354  {
1355  LOCK(cs_vNodes);
1356  for (CNode* pnode : vNodes)
1357  {
1358  // Implement the following logic:
1359  // * If there is data to send, select() for sending data. As this only
1360  // happens when optimistic write failed, we choose to first drain the
1361  // write buffer in this case before receiving more. This avoids
1362  // needlessly queueing received data, if the remote peer is not themselves
1363  // receiving data. This means properly utilizing TCP flow control signalling.
1364  // * Otherwise, if there is space left in the receive buffer, select() for
1365  // receiving data.
1366  // * Hand off all complete messages to the processor, to be handled without
1367  // blocking here.
1368 
1369  bool select_recv = !pnode->fPauseRecv;
1370  bool select_send;
1371  {
1372  LOCK(pnode->cs_vSend);
1373  select_send = !pnode->vSendMsg.empty();
1374  }
1375 
1376  LOCK(pnode->cs_hSocket);
1377  if (pnode->hSocket == INVALID_SOCKET)
1378  continue;
1379 
1380  error_set.insert(pnode->hSocket);
1381  if (select_send) {
1382  send_set.insert(pnode->hSocket);
1383  continue;
1384  }
1385  if (select_recv) {
1386  recv_set.insert(pnode->hSocket);
1387  }
1388  }
1389  }
1390 
1391  return !recv_set.empty() || !send_set.empty() || !error_set.empty();
1392 }
1393 
1394 #ifdef USE_POLL
1395 void CConnman::SocketEvents(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set)
1396 {
1397  std::set<SOCKET> recv_select_set, send_select_set, error_select_set;
1398  if (!GenerateSelectSet(recv_select_set, send_select_set, error_select_set)) {
1399  interruptNet.sleep_for(std::chrono::milliseconds(SELECT_TIMEOUT_MILLISECONDS));
1400  return;
1401  }
1402 
1403  std::unordered_map<SOCKET, struct pollfd> pollfds;
1404  for (SOCKET socket_id : recv_select_set) {
1405  pollfds[socket_id].fd = socket_id;
1406  pollfds[socket_id].events |= POLLIN;
1407  }
1408 
1409  for (SOCKET socket_id : send_select_set) {
1410  pollfds[socket_id].fd = socket_id;
1411  pollfds[socket_id].events |= POLLOUT;
1412  }
1413 
1414  for (SOCKET socket_id : error_select_set) {
1415  pollfds[socket_id].fd = socket_id;
1416  // These flags are ignored, but we set them for clarity
1417  pollfds[socket_id].events |= POLLERR|POLLHUP;
1418  }
1419 
1420  std::vector<struct pollfd> vpollfds;
1421  vpollfds.reserve(pollfds.size());
1422  for (auto it : pollfds) {
1423  vpollfds.push_back(std::move(it.second));
1424  }
1425 
1426  if (poll(vpollfds.data(), vpollfds.size(), SELECT_TIMEOUT_MILLISECONDS) < 0) return;
1427 
1428  if (interruptNet) return;
1429 
1430  for (struct pollfd pollfd_entry : vpollfds) {
1431  if (pollfd_entry.revents & POLLIN) recv_set.insert(pollfd_entry.fd);
1432  if (pollfd_entry.revents & POLLOUT) send_set.insert(pollfd_entry.fd);
1433  if (pollfd_entry.revents & (POLLERR|POLLHUP)) error_set.insert(pollfd_entry.fd);
1434  }
1435 }
1436 #else
1437 void CConnman::SocketEvents(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set)
1438 {
1439  std::set<SOCKET> recv_select_set, send_select_set, error_select_set;
1440  if (!GenerateSelectSet(recv_select_set, send_select_set, error_select_set)) {
1441  interruptNet.sleep_for(std::chrono::milliseconds(SELECT_TIMEOUT_MILLISECONDS));
1442  return;
1443  }
1444 
1445  //
1446  // Find which sockets have data to receive
1447  //
1448  struct timeval timeout;
1449  timeout.tv_sec = 0;
1450  timeout.tv_usec = SELECT_TIMEOUT_MILLISECONDS * 1000; // frequency to poll pnode->vSend
1451 
1452  fd_set fdsetRecv;
1453  fd_set fdsetSend;
1454  fd_set fdsetError;
1455  FD_ZERO(&fdsetRecv);
1456  FD_ZERO(&fdsetSend);
1457  FD_ZERO(&fdsetError);
1458  SOCKET hSocketMax = 0;
1459 
1460  for (SOCKET hSocket : recv_select_set) {
1461  FD_SET(hSocket, &fdsetRecv);
1462  hSocketMax = std::max(hSocketMax, hSocket);
1463  }
1464 
1465  for (SOCKET hSocket : send_select_set) {
1466  FD_SET(hSocket, &fdsetSend);
1467  hSocketMax = std::max(hSocketMax, hSocket);
1468  }
1469 
1470  for (SOCKET hSocket : error_select_set) {
1471  FD_SET(hSocket, &fdsetError);
1472  hSocketMax = std::max(hSocketMax, hSocket);
1473  }
1474 
1475  int nSelect = select(hSocketMax + 1, &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
1476 
1477  if (interruptNet)
1478  return;
1479 
1480  if (nSelect == SOCKET_ERROR)
1481  {
1482  int nErr = WSAGetLastError();
1483  LogPrintf("socket select error %s\n", NetworkErrorString(nErr));
1484  for (unsigned int i = 0; i <= hSocketMax; i++)
1485  FD_SET(i, &fdsetRecv);
1486  FD_ZERO(&fdsetSend);
1487  FD_ZERO(&fdsetError);
1488  if (!interruptNet.sleep_for(std::chrono::milliseconds(SELECT_TIMEOUT_MILLISECONDS)))
1489  return;
1490  }
1491 
1492  for (SOCKET hSocket : recv_select_set) {
1493  if (FD_ISSET(hSocket, &fdsetRecv)) {
1494  recv_set.insert(hSocket);
1495  }
1496  }
1497 
1498  for (SOCKET hSocket : send_select_set) {
1499  if (FD_ISSET(hSocket, &fdsetSend)) {
1500  send_set.insert(hSocket);
1501  }
1502  }
1503 
1504  for (SOCKET hSocket : error_select_set) {
1505  if (FD_ISSET(hSocket, &fdsetError)) {
1506  error_set.insert(hSocket);
1507  }
1508  }
1509 }
1510 #endif
1511 
1513 {
1514  std::set<SOCKET> recv_set, send_set, error_set;
1515  SocketEvents(recv_set, send_set, error_set);
1516 
1517  if (interruptNet) return;
1518 
1519  //
1520  // Accept new connections
1521  //
1522  for (const ListenSocket& hListenSocket : vhListenSocket)
1523  {
1524  if (hListenSocket.socket != INVALID_SOCKET && recv_set.count(hListenSocket.socket) > 0)
1525  {
1526  AcceptConnection(hListenSocket);
1527  }
1528  }
1529 
1530  //
1531  // Service each socket
1532  //
1533  std::vector<CNode*> vNodesCopy;
1534  {
1535  LOCK(cs_vNodes);
1536  vNodesCopy = vNodes;
1537  for (CNode* pnode : vNodesCopy)
1538  pnode->AddRef();
1539  }
1540  for (CNode* pnode : vNodesCopy)
1541  {
1542  if (interruptNet)
1543  return;
1544 
1545  //
1546  // Receive
1547  //
1548  bool recvSet = false;
1549  bool sendSet = false;
1550  bool errorSet = false;
1551  {
1552  LOCK(pnode->cs_hSocket);
1553  if (pnode->hSocket == INVALID_SOCKET)
1554  continue;
1555  recvSet = recv_set.count(pnode->hSocket) > 0;
1556  sendSet = send_set.count(pnode->hSocket) > 0;
1557  errorSet = error_set.count(pnode->hSocket) > 0;
1558  }
1559  if (recvSet || errorSet)
1560  {
1561  // typical socket buffer is 8K-64K
1562  uint8_t pchBuf[0x10000];
1563  int nBytes = 0;
1564  {
1565  LOCK(pnode->cs_hSocket);
1566  if (pnode->hSocket == INVALID_SOCKET)
1567  continue;
1568  nBytes = recv(pnode->hSocket, (char*)pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
1569  }
1570  if (nBytes > 0)
1571  {
1572  bool notify = false;
1573  if (!pnode->ReceiveMsgBytes(Span<const uint8_t>(pchBuf, nBytes), notify))
1574  pnode->CloseSocketDisconnect();
1575  RecordBytesRecv(nBytes);
1576  if (notify) {
1577  size_t nSizeAdded = 0;
1578  auto it(pnode->vRecvMsg.begin());
1579  for (; it != pnode->vRecvMsg.end(); ++it) {
1580  // vRecvMsg contains only completed CNetMessage
1581  // the single possible partially deserialized message are held by TransportDeserializer
1582  nSizeAdded += it->m_raw_message_size;
1583  }
1584  {
1585  LOCK(pnode->cs_vProcessMsg);
1586  pnode->vProcessMsg.splice(pnode->vProcessMsg.end(), pnode->vRecvMsg, pnode->vRecvMsg.begin(), it);
1587  pnode->nProcessQueueSize += nSizeAdded;
1588  pnode->fPauseRecv = pnode->nProcessQueueSize > nReceiveFloodSize;
1589  }
1591  }
1592  }
1593  else if (nBytes == 0)
1594  {
1595  // socket closed gracefully
1596  if (!pnode->fDisconnect) {
1597  LogPrint(BCLog::NET, "socket closed for peer=%d\n", pnode->GetId());
1598  }
1599  pnode->CloseSocketDisconnect();
1600  }
1601  else if (nBytes < 0)
1602  {
1603  // error
1604  int nErr = WSAGetLastError();
1605  if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
1606  {
1607  if (!pnode->fDisconnect) {
1608  LogPrint(BCLog::NET, "socket recv error for peer=%d: %s\n", pnode->GetId(), NetworkErrorString(nErr));
1609  }
1610  pnode->CloseSocketDisconnect();
1611  }
1612  }
1613  }
1614 
1615  if (sendSet) {
1616  // Send data
1617  size_t bytes_sent = WITH_LOCK(pnode->cs_vSend, return SocketSendData(*pnode));
1618  if (bytes_sent) RecordBytesSent(bytes_sent);
1619  }
1620 
1621  if (InactivityCheck(*pnode)) pnode->fDisconnect = true;
1622  }
1623  {
1624  LOCK(cs_vNodes);
1625  for (CNode* pnode : vNodesCopy)
1626  pnode->Release();
1627  }
1628 }
1629 
1631 {
1632  while (!interruptNet)
1633  {
1634  DisconnectNodes();
1636  SocketHandler();
1637  }
1638 }
1639 
1641 {
1642  {
1643  LOCK(mutexMsgProc);
1644  fMsgProcWake = true;
1645  }
1646  condMsgProc.notify_one();
1647 }
1648 
1650 {
1651  FastRandomContext rng;
1652  std::vector<std::string> seeds = Params().DNSSeeds();
1653  Shuffle(seeds.begin(), seeds.end(), rng);
1654  int seeds_right_now = 0; // Number of seeds left before testing if we have enough connections
1655  int found = 0;
1656 
1657  if (gArgs.GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED)) {
1658  // When -forcednsseed is provided, query all.
1659  seeds_right_now = seeds.size();
1660  } else if (addrman.size() == 0) {
1661  // If we have no known peers, query all.
1662  // This will occur on the first run, or if peers.dat has been
1663  // deleted.
1664  seeds_right_now = seeds.size();
1665  }
1666 
1667  // goal: only query DNS seed if address need is acute
1668  // * If we have a reasonable number of peers in addrman, spend
1669  // some time trying them first. This improves user privacy by
1670  // creating fewer identifying DNS requests, reduces trust by
1671  // giving seeds less influence on the network topology, and
1672  // reduces traffic to the seeds.
1673  // * When querying DNS seeds query a few at once, this ensures
1674  // that we don't give DNS seeds the ability to eclipse nodes
1675  // that query them.
1676  // * If we continue having problems, eventually query all the
1677  // DNS seeds, and if that fails too, also try the fixed seeds.
1678  // (done in ThreadOpenConnections)
1679  const std::chrono::seconds seeds_wait_time = (addrman.size() >= DNSSEEDS_DELAY_PEER_THRESHOLD ? DNSSEEDS_DELAY_MANY_PEERS : DNSSEEDS_DELAY_FEW_PEERS);
1680 
1681  for (const std::string& seed : seeds) {
1682  if (seeds_right_now == 0) {
1683  seeds_right_now += DNSSEEDS_TO_QUERY_AT_ONCE;
1684 
1685  if (addrman.size() > 0) {
1686  LogPrintf("Waiting %d seconds before querying DNS seeds.\n", seeds_wait_time.count());
1687  std::chrono::seconds to_wait = seeds_wait_time;
1688  while (to_wait.count() > 0) {
1689  // if sleeping for the MANY_PEERS interval, wake up
1690  // early to see if we have enough peers and can stop
1691  // this thread entirely freeing up its resources
1692  std::chrono::seconds w = std::min(DNSSEEDS_DELAY_FEW_PEERS, to_wait);
1693  if (!interruptNet.sleep_for(w)) return;
1694  to_wait -= w;
1695 
1696  int nRelevant = 0;
1697  {
1698  LOCK(cs_vNodes);
1699  for (const CNode* pnode : vNodes) {
1700  if (pnode->fSuccessfullyConnected && pnode->IsFullOutboundConn()) ++nRelevant;
1701  }
1702  }
1703  if (nRelevant >= 2) {
1704  if (found > 0) {
1705  LogPrintf("%d addresses found from DNS seeds\n", found);
1706  LogPrintf("P2P peers available. Finished DNS seeding.\n");
1707  } else {
1708  LogPrintf("P2P peers available. Skipped DNS seeding.\n");
1709  }
1710  return;
1711  }
1712  }
1713  }
1714  }
1715 
1716  if (interruptNet) return;
1717 
1718  // hold off on querying seeds if P2P network deactivated
1719  if (!fNetworkActive) {
1720  LogPrintf("Waiting for network to be reactivated before querying DNS seeds.\n");
1721  do {
1722  if (!interruptNet.sleep_for(std::chrono::seconds{1})) return;
1723  } while (!fNetworkActive);
1724  }
1725 
1726  LogPrintf("Loading addresses from DNS seed %s\n", seed);
1727  if (HaveNameProxy()) {
1728  AddAddrFetch(seed);
1729  } else {
1730  std::vector<CNetAddr> vIPs;
1731  std::vector<CAddress> vAdd;
1732  ServiceFlags requiredServiceBits = GetDesirableServiceFlags(NODE_NONE);
1733  std::string host = strprintf("x%x.%s", requiredServiceBits, seed);
1734  CNetAddr resolveSource;
1735  if (!resolveSource.SetInternal(host)) {
1736  continue;
1737  }
1738  unsigned int nMaxIPs = 256; // Limits number of IPs learned from a DNS seed
1739  if (LookupHost(host, vIPs, nMaxIPs, true)) {
1740  for (const CNetAddr& ip : vIPs) {
1741  int nOneDay = 24*3600;
1742  CAddress addr = CAddress(CService(ip, Params().GetDefaultPort()), requiredServiceBits);
1743  addr.nTime = GetTime() - 3*nOneDay - rng.randrange(4*nOneDay); // use a random age between 3 and 7 days old
1744  vAdd.push_back(addr);
1745  found++;
1746  }
1747  addrman.Add(vAdd, resolveSource);
1748  } else {
1749  // We now avoid directly using results from DNS Seeds which do not support service bit filtering,
1750  // instead using them as a addrfetch to get nodes with our desired service bits.
1751  AddAddrFetch(seed);
1752  }
1753  }
1754  --seeds_right_now;
1755  }
1756  LogPrintf("%d addresses found from DNS seeds\n", found);
1757 }
1758 
1760 {
1761  int64_t nStart = GetTimeMillis();
1762 
1763  CAddrDB adb;
1764  adb.Write(addrman);
1765 
1766  LogPrint(BCLog::NET, "Flushed %d addresses to peers.dat %dms\n",
1767  addrman.size(), GetTimeMillis() - nStart);
1768 }
1769 
1771 {
1772  std::string strDest;
1773  {
1775  if (m_addr_fetches.empty())
1776  return;
1777  strDest = m_addr_fetches.front();
1778  m_addr_fetches.pop_front();
1779  }
1780  CAddress addr;
1781  CSemaphoreGrant grant(*semOutbound, true);
1782  if (grant) {
1783  OpenNetworkConnection(addr, false, &grant, strDest.c_str(), ConnectionType::ADDR_FETCH);
1784  }
1785 }
1786 
1788 {
1790 }
1791 
1793 {
1795  LogPrint(BCLog::NET, "net: setting try another outbound peer=%s\n", flag ? "true" : "false");
1796 }
1797 
1798 // Return the number of peers we have over our outbound connection limit
1799 // Exclude peers that are marked for disconnect, or are going to be
1800 // disconnected soon (eg ADDR_FETCH and FEELER)
1801 // Also exclude peers that haven't finished initial connection handshake yet
1802 // (so that we don't decide we're over our desired connection limit, and then
1803 // evict some peer that has finished the handshake)
1805 {
1806  int full_outbound_peers = 0;
1807  {
1808  LOCK(cs_vNodes);
1809  for (const CNode* pnode : vNodes) {
1810  if (pnode->fSuccessfullyConnected && !pnode->fDisconnect && pnode->IsFullOutboundConn()) {
1811  ++full_outbound_peers;
1812  }
1813  }
1814  }
1815  return std::max(full_outbound_peers - m_max_outbound_full_relay, 0);
1816 }
1817 
1819 {
1820  int block_relay_peers = 0;
1821  {
1822  LOCK(cs_vNodes);
1823  for (const CNode* pnode : vNodes) {
1824  if (pnode->fSuccessfullyConnected && !pnode->fDisconnect && pnode->IsBlockOnlyConn()) {
1825  ++block_relay_peers;
1826  }
1827  }
1828  }
1829  return std::max(block_relay_peers - m_max_outbound_block_relay, 0);
1830 }
1831 
1832 void CConnman::ThreadOpenConnections(const std::vector<std::string> connect)
1833 {
1834  // Connect to specific addresses
1835  if (!connect.empty())
1836  {
1837  for (int64_t nLoop = 0;; nLoop++)
1838  {
1839  ProcessAddrFetch();
1840  for (const std::string& strAddr : connect)
1841  {
1842  CAddress addr(CService(), NODE_NONE);
1843  OpenNetworkConnection(addr, false, nullptr, strAddr.c_str(), ConnectionType::MANUAL);
1844  for (int i = 0; i < 10 && i < nLoop; i++)
1845  {
1846  if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
1847  return;
1848  }
1849  }
1850  if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
1851  return;
1852  }
1853  }
1854 
1855  // Initiate network connections
1856  auto start = GetTime<std::chrono::microseconds>();
1857 
1858  // Minimum time before next feeler connection (in microseconds).
1859  auto next_feeler = PoissonNextSend(start, FEELER_INTERVAL);
1860  auto next_extra_block_relay = PoissonNextSend(start, EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL);
1861  const bool dnsseed = gArgs.GetBoolArg("-dnsseed", DEFAULT_DNSSEED);
1862  bool add_fixed_seeds = gArgs.GetBoolArg("-fixedseeds", DEFAULT_FIXEDSEEDS);
1863 
1864  if (!add_fixed_seeds) {
1865  LogPrintf("Fixed seeds are disabled\n");
1866  }
1867 
1868  while (!interruptNet)
1869  {
1870  ProcessAddrFetch();
1871 
1872  if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
1873  return;
1874 
1875  CSemaphoreGrant grant(*semOutbound);
1876  if (interruptNet)
1877  return;
1878 
1879  if (add_fixed_seeds && addrman.size() == 0) {
1880  // When the node starts with an empty peers.dat, there are a few other sources of peers before
1881  // we fallback on to fixed seeds: -dnsseed, -seednode, -addnode
1882  // If none of those are available, we fallback on to fixed seeds immediately, else we allow
1883  // 60 seconds for any of those sources to populate addrman.
1884  bool add_fixed_seeds_now = false;
1885  // It is cheapest to check if enough time has passed first.
1886  if (GetTime<std::chrono::seconds>() > start + std::chrono::minutes{1}) {
1887  add_fixed_seeds_now = true;
1888  LogPrintf("Adding fixed seeds as 60 seconds have passed and addrman is empty\n");
1889  }
1890 
1891  // Checking !dnsseed is cheaper before locking 2 mutexes.
1892  if (!add_fixed_seeds_now && !dnsseed) {
1894  if (m_addr_fetches.empty() && vAddedNodes.empty()) {
1895  add_fixed_seeds_now = true;
1896  LogPrintf("Adding fixed seeds as -dnsseed=0, -addnode is not provided and all -seednode(s) attempted\n");
1897  }
1898  }
1899 
1900  if (add_fixed_seeds_now) {
1901  CNetAddr local;
1902  local.SetInternal("fixedseeds");
1903  addrman.Add(ConvertSeeds(Params().FixedSeeds()), local);
1904  add_fixed_seeds = false;
1905  }
1906  }
1907 
1908  //
1909  // Choose an address to connect to based on most recently seen
1910  //
1911  CAddress addrConnect;
1912 
1913  // Only connect out to one peer per network group (/16 for IPv4).
1914  int nOutboundFullRelay = 0;
1915  int nOutboundBlockRelay = 0;
1916  std::set<std::vector<unsigned char> > setConnected;
1917 
1918  {
1919  LOCK(cs_vNodes);
1920  for (const CNode* pnode : vNodes) {
1921  if (pnode->IsFullOutboundConn()) nOutboundFullRelay++;
1922  if (pnode->IsBlockOnlyConn()) nOutboundBlockRelay++;
1923 
1924  // Netgroups for inbound and manual peers are not excluded because our goal here
1925  // is to not use multiple of our limited outbound slots on a single netgroup
1926  // but inbound and manual peers do not use our outbound slots. Inbound peers
1927  // also have the added issue that they could be attacker controlled and used
1928  // to prevent us from connecting to particular hosts if we used them here.
1929  switch (pnode->m_conn_type) {
1932  break;
1937  setConnected.insert(pnode->addr.GetGroup(addrman.m_asmap));
1938  } // no default case, so the compiler can warn about missing cases
1939  }
1940  }
1941 
1943  auto now = GetTime<std::chrono::microseconds>();
1944  bool anchor = false;
1945  bool fFeeler = false;
1946 
1947  // Determine what type of connection to open. Opening
1948  // BLOCK_RELAY connections to addresses from anchors.dat gets the highest
1949  // priority. Then we open OUTBOUND_FULL_RELAY priority until we
1950  // meet our full-relay capacity. Then we open BLOCK_RELAY connection
1951  // until we hit our block-relay-only peer limit.
1952  // GetTryNewOutboundPeer() gets set when a stale tip is detected, so we
1953  // try opening an additional OUTBOUND_FULL_RELAY connection. If none of
1954  // these conditions are met, check to see if it's time to try an extra
1955  // block-relay-only peer (to confirm our tip is current, see below) or the next_feeler
1956  // timer to decide if we should open a FEELER.
1957 
1958  if (!m_anchors.empty() && (nOutboundBlockRelay < m_max_outbound_block_relay)) {
1959  conn_type = ConnectionType::BLOCK_RELAY;
1960  anchor = true;
1961  } else if (nOutboundFullRelay < m_max_outbound_full_relay) {
1962  // OUTBOUND_FULL_RELAY
1963  } else if (nOutboundBlockRelay < m_max_outbound_block_relay) {
1964  conn_type = ConnectionType::BLOCK_RELAY;
1965  } else if (GetTryNewOutboundPeer()) {
1966  // OUTBOUND_FULL_RELAY
1967  } else if (now > next_extra_block_relay && m_start_extra_block_relay_peers) {
1968  // Periodically connect to a peer (using regular outbound selection
1969  // methodology from addrman) and stay connected long enough to sync
1970  // headers, but not much else.
1971  //
1972  // Then disconnect the peer, if we haven't learned anything new.
1973  //
1974  // The idea is to make eclipse attacks very difficult to pull off,
1975  // because every few minutes we're finding a new peer to learn headers
1976  // from.
1977  //
1978  // This is similar to the logic for trying extra outbound (full-relay)
1979  // peers, except:
1980  // - we do this all the time on a poisson timer, rather than just when
1981  // our tip is stale
1982  // - we potentially disconnect our next-youngest block-relay-only peer, if our
1983  // newest block-relay-only peer delivers a block more recently.
1984  // See the eviction logic in net_processing.cpp.
1985  //
1986  // Because we can promote these connections to block-relay-only
1987  // connections, they do not get their own ConnectionType enum
1988  // (similar to how we deal with extra outbound peers).
1989  next_extra_block_relay = PoissonNextSend(now, EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL);
1990  conn_type = ConnectionType::BLOCK_RELAY;
1991  } else if (now > next_feeler) {
1992  next_feeler = PoissonNextSend(now, FEELER_INTERVAL);
1993  conn_type = ConnectionType::FEELER;
1994  fFeeler = true;
1995  } else {
1996  // skip to next iteration of while loop
1997  continue;
1998  }
1999 
2001 
2002  int64_t nANow = GetAdjustedTime();
2003  int nTries = 0;
2004  while (!interruptNet)
2005  {
2006  if (anchor && !m_anchors.empty()) {
2007  const CAddress addr = m_anchors.back();
2008  m_anchors.pop_back();
2009  if (!addr.IsValid() || IsLocal(addr) || !IsReachable(addr) ||
2011  setConnected.count(addr.GetGroup(addrman.m_asmap))) continue;
2012  addrConnect = addr;
2013  LogPrint(BCLog::NET, "Trying to make an anchor connection to %s\n", addrConnect.ToString());
2014  break;
2015  }
2016 
2017  // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
2018  // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
2019  // already-connected network ranges, ...) before trying new addrman addresses.
2020  nTries++;
2021  if (nTries > 100)
2022  break;
2023 
2024  CAddrInfo addr;
2025 
2026  if (fFeeler) {
2027  // First, try to get a tried table collision address. This returns
2028  // an empty (invalid) address if there are no collisions to try.
2029  addr = addrman.SelectTriedCollision();
2030 
2031  if (!addr.IsValid()) {
2032  // No tried table collisions. Select a new table address
2033  // for our feeler.
2034  addr = addrman.Select(true);
2035  } else if (AlreadyConnectedToAddress(addr)) {
2036  // If test-before-evict logic would have us connect to a
2037  // peer that we're already connected to, just mark that
2038  // address as Good(). We won't be able to initiate the
2039  // connection anyway, so this avoids inadvertently evicting
2040  // a currently-connected peer.
2041  addrman.Good(addr);
2042  // Select a new table address for our feeler instead.
2043  addr = addrman.Select(true);
2044  }
2045  } else {
2046  // Not a feeler
2047  addr = addrman.Select();
2048  }
2049 
2050  // Require outbound connections, other than feelers, to be to distinct network groups
2051  if (!fFeeler && setConnected.count(addr.GetGroup(addrman.m_asmap))) {
2052  break;
2053  }
2054 
2055  // if we selected an invalid or local address, restart
2056  if (!addr.IsValid() || IsLocal(addr)) {
2057  break;
2058  }
2059 
2060  if (!IsReachable(addr))
2061  continue;
2062 
2063  // only consider very recently tried nodes after 30 failed attempts
2064  if (nANow - addr.nLastTry < 600 && nTries < 30)
2065  continue;
2066 
2067  // for non-feelers, require all the services we'll want,
2068  // for feelers, only require they be a full node (only because most
2069  // SPV clients don't have a good address DB available)
2070  if (!fFeeler && !HasAllDesirableServiceFlags(addr.nServices)) {
2071  continue;
2072  } else if (fFeeler && !MayHaveUsefulAddressDB(addr.nServices)) {
2073  continue;
2074  }
2075 
2076  // Do not allow non-default ports, unless after 50 invalid
2077  // addresses selected already. This is to prevent malicious peers
2078  // from advertising themselves as a service on another host and
2079  // port, causing a DoS attack as nodes around the network attempt
2080  // to connect to it fruitlessly.
2081  if (addr.GetPort() != Params().GetDefaultPort(addr.GetNetwork()) && nTries < 50) {
2082  continue;
2083  }
2084 
2085  addrConnect = addr;
2086  break;
2087  }
2088 
2089  if (addrConnect.IsValid()) {
2090 
2091  if (fFeeler) {
2092  // Add small amount of random noise before connection to avoid synchronization.
2093  int randsleep = GetRandInt(FEELER_SLEEP_WINDOW * 1000);
2094  if (!interruptNet.sleep_for(std::chrono::milliseconds(randsleep)))
2095  return;
2096  LogPrint(BCLog::NET, "Making feeler connection to %s\n", addrConnect.ToString());
2097  }
2098 
2099  OpenNetworkConnection(addrConnect, (int)setConnected.size() >= std::min(nMaxConnections - 1, 2), &grant, nullptr, conn_type);
2100  }
2101  }
2102 }
2103 
2104 std::vector<CAddress> CConnman::GetCurrentBlockRelayOnlyConns() const
2105 {
2106  std::vector<CAddress> ret;
2107  LOCK(cs_vNodes);
2108  for (const CNode* pnode : vNodes) {
2109  if (pnode->IsBlockOnlyConn()) {
2110  ret.push_back(pnode->addr);
2111  }
2112  }
2113 
2114  return ret;
2115 }
2116 
2117 std::vector<AddedNodeInfo> CConnman::GetAddedNodeInfo() const
2118 {
2119  std::vector<AddedNodeInfo> ret;
2120 
2121  std::list<std::string> lAddresses(0);
2122  {
2124  ret.reserve(vAddedNodes.size());
2125  std::copy(vAddedNodes.cbegin(), vAddedNodes.cend(), std::back_inserter(lAddresses));
2126  }
2127 
2128 
2129  // Build a map of all already connected addresses (by IP:port and by name) to inbound/outbound and resolved CService
2130  std::map<CService, bool> mapConnected;
2131  std::map<std::string, std::pair<bool, CService>> mapConnectedByName;
2132  {
2133  LOCK(cs_vNodes);
2134  for (const CNode* pnode : vNodes) {
2135  if (pnode->addr.IsValid()) {
2136  mapConnected[pnode->addr] = pnode->IsInboundConn();
2137  }
2138  std::string addrName = pnode->GetAddrName();
2139  if (!addrName.empty()) {
2140  mapConnectedByName[std::move(addrName)] = std::make_pair(pnode->IsInboundConn(), static_cast<const CService&>(pnode->addr));
2141  }
2142  }
2143  }
2144 
2145  for (const std::string& strAddNode : lAddresses) {
2146  CService service(LookupNumeric(strAddNode, Params().GetDefaultPort(strAddNode)));
2147  AddedNodeInfo addedNode{strAddNode, CService(), false, false};
2148  if (service.IsValid()) {
2149  // strAddNode is an IP:port
2150  auto it = mapConnected.find(service);
2151  if (it != mapConnected.end()) {
2152  addedNode.resolvedAddress = service;
2153  addedNode.fConnected = true;
2154  addedNode.fInbound = it->second;
2155  }
2156  } else {
2157  // strAddNode is a name
2158  auto it = mapConnectedByName.find(strAddNode);
2159  if (it != mapConnectedByName.end()) {
2160  addedNode.resolvedAddress = it->second.second;
2161  addedNode.fConnected = true;
2162  addedNode.fInbound = it->second.first;
2163  }
2164  }
2165  ret.emplace_back(std::move(addedNode));
2166  }
2167 
2168  return ret;
2169 }
2170 
2172 {
2173  while (true)
2174  {
2175  CSemaphoreGrant grant(*semAddnode);
2176  std::vector<AddedNodeInfo> vInfo = GetAddedNodeInfo();
2177  bool tried = false;
2178  for (const AddedNodeInfo& info : vInfo) {
2179  if (!info.fConnected) {
2180  if (!grant.TryAcquire()) {
2181  // If we've used up our semaphore and need a new one, let's not wait here since while we are waiting
2182  // the addednodeinfo state might change.
2183  break;
2184  }
2185  tried = true;
2186  CAddress addr(CService(), NODE_NONE);
2187  OpenNetworkConnection(addr, false, &grant, info.strAddedNode.c_str(), ConnectionType::MANUAL);
2188  if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
2189  return;
2190  }
2191  }
2192  // Retry every 60 seconds if a connection was attempted, otherwise two seconds
2193  if (!interruptNet.sleep_for(std::chrono::seconds(tried ? 60 : 2)))
2194  return;
2195  }
2196 }
2197 
2198 // if successful, this moves the passed grant to the constructed node
2199 void CConnman::OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *pszDest, ConnectionType conn_type)
2200 {
2201  assert(conn_type != ConnectionType::INBOUND);
2202 
2203  //
2204  // Initiate outbound network connection
2205  //
2206  if (interruptNet) {
2207  return;
2208  }
2209  if (!fNetworkActive) {
2210  return;
2211  }
2212  if (!pszDest) {
2213  bool banned_or_discouraged = m_banman && (m_banman->IsDiscouraged(addrConnect) || m_banman->IsBanned(addrConnect));
2214  if (IsLocal(addrConnect) || banned_or_discouraged || AlreadyConnectedToAddress(addrConnect)) {
2215  return;
2216  }
2217  } else if (FindNode(std::string(pszDest)))
2218  return;
2219 
2220  CNode* pnode = ConnectNode(addrConnect, pszDest, fCountFailure, conn_type);
2221 
2222  if (!pnode)
2223  return;
2224  if (grantOutbound)
2225  grantOutbound->MoveTo(pnode->grantOutbound);
2226 
2227  m_msgproc->InitializeNode(pnode);
2228  {
2229  LOCK(cs_vNodes);
2230  vNodes.push_back(pnode);
2231  }
2232 }
2233 
2235 {
2236  FastRandomContext rng;
2237  while (!flagInterruptMsgProc)
2238  {
2239  std::vector<CNode*> vNodesCopy;
2240  {
2241  LOCK(cs_vNodes);
2242  vNodesCopy = vNodes;
2243  for (CNode* pnode : vNodesCopy) {
2244  pnode->AddRef();
2245  }
2246  }
2247 
2248  bool fMoreWork = false;
2249 
2250  // Randomize the order in which we process messages from/to our peers.
2251  // This prevents attacks in which an attacker exploits having multiple
2252  // consecutive connections in the vNodes list.
2253  Shuffle(vNodesCopy.begin(), vNodesCopy.end(), rng);
2254 
2255  for (CNode* pnode : vNodesCopy)
2256  {
2257  if (pnode->fDisconnect)
2258  continue;
2259 
2260  // Receive messages
2261  bool fMoreNodeWork = m_msgproc->ProcessMessages(pnode, flagInterruptMsgProc);
2262  fMoreWork |= (fMoreNodeWork && !pnode->fPauseSend);
2264  return;
2265  // Send messages
2266  {
2267  LOCK(pnode->cs_sendProcessing);
2268  m_msgproc->SendMessages(pnode);
2269  }
2270 
2272  return;
2273  }
2274 
2275  {
2276  LOCK(cs_vNodes);
2277  for (CNode* pnode : vNodesCopy)
2278  pnode->Release();
2279  }
2280 
2281  WAIT_LOCK(mutexMsgProc, lock);
2282  if (!fMoreWork) {
2283  condMsgProc.wait_until(lock, std::chrono::steady_clock::now() + std::chrono::milliseconds(100), [this]() EXCLUSIVE_LOCKS_REQUIRED(mutexMsgProc) { return fMsgProcWake; });
2284  }
2285  fMsgProcWake = false;
2286  }
2287 }
2288 
2290 {
2291  static constexpr auto err_wait_begin = 1s;
2292  static constexpr auto err_wait_cap = 5min;
2293  auto err_wait = err_wait_begin;
2294 
2295  bool advertising_listen_addr = false;
2296  i2p::Connection conn;
2297 
2298  while (!interruptNet) {
2299 
2300  if (!m_i2p_sam_session->Listen(conn)) {
2301  if (advertising_listen_addr && conn.me.IsValid()) {
2302  RemoveLocal(conn.me);
2303  advertising_listen_addr = false;
2304  }
2305 
2306  interruptNet.sleep_for(err_wait);
2307  if (err_wait < err_wait_cap) {
2308  err_wait *= 2;
2309  }
2310 
2311  continue;
2312  }
2313 
2314  if (!advertising_listen_addr) {
2315  AddLocal(conn.me, LOCAL_MANUAL);
2316  advertising_listen_addr = true;
2317  }
2318 
2319  if (!m_i2p_sam_session->Accept(conn)) {
2320  continue;
2321  }
2322 
2324  CAddress{conn.me, NODE_NONE}, CAddress{conn.peer, NODE_NONE});
2325  }
2326 }
2327 
2328 bool CConnman::BindListenPort(const CService& addrBind, bilingual_str& strError, NetPermissionFlags permissions)
2329 {
2330  int nOne = 1;
2331 
2332  // Create socket for listening for incoming connections
2333  struct sockaddr_storage sockaddr;
2334  socklen_t len = sizeof(sockaddr);
2335  if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
2336  {
2337  strError = strprintf(Untranslated("Error: Bind address family for %s not supported"), addrBind.ToString());
2338  LogPrintf("%s\n", strError.original);
2339  return false;
2340  }
2341 
2342  std::unique_ptr<Sock> sock = CreateSock(addrBind);
2343  if (!sock) {
2344  strError = strprintf(Untranslated("Error: Couldn't open socket for incoming connections (socket returned error %s)"), NetworkErrorString(WSAGetLastError()));
2345  LogPrintf("%s\n", strError.original);
2346  return false;
2347  }
2348 
2349  // Allow binding if the port is still in TIME_WAIT state after
2350  // the program was closed and restarted.
2351  setsockopt(sock->Get(), SOL_SOCKET, SO_REUSEADDR, (sockopt_arg_type)&nOne, sizeof(int));
2352 
2353  // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
2354  // and enable it by default or not. Try to enable it, if possible.
2355  if (addrBind.IsIPv6()) {
2356 #ifdef IPV6_V6ONLY
2357  setsockopt(sock->Get(), IPPROTO_IPV6, IPV6_V6ONLY, (sockopt_arg_type)&nOne, sizeof(int));
2358 #endif
2359 #ifdef WIN32
2360  int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED;
2361  setsockopt(sock->Get(), IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, (const char*)&nProtLevel, sizeof(int));
2362 #endif
2363  }
2364 
2365  if (::bind(sock->Get(), (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
2366  {
2367  int nErr = WSAGetLastError();
2368  if (nErr == WSAEADDRINUSE)
2369  strError = strprintf(_("Unable to bind to %s on this computer. %s is probably already running."), addrBind.ToString(), PACKAGE_NAME);
2370  else
2371  strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToString(), NetworkErrorString(nErr));
2372  LogPrintf("%s\n", strError.original);
2373  return false;
2374  }
2375  LogPrintf("Bound to %s\n", addrBind.ToString());
2376 
2377  // Listen for incoming connections
2378  if (listen(sock->Get(), SOMAXCONN) == SOCKET_ERROR)
2379  {
2380  strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError()));
2381  LogPrintf("%s\n", strError.original);
2382  return false;
2383  }
2384 
2385  vhListenSocket.push_back(ListenSocket(sock->Release(), permissions));
2386  return true;
2387 }
2388 
2389 void Discover()
2390 {
2391  if (!fDiscover)
2392  return;
2393 
2394 #ifdef WIN32
2395  // Get local host IP
2396  char pszHostName[256] = "";
2397  if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
2398  {
2399  std::vector<CNetAddr> vaddr;
2400  if (LookupHost(pszHostName, vaddr, 0, true))
2401  {
2402  for (const CNetAddr &addr : vaddr)
2403  {
2404  if (AddLocal(addr, LOCAL_IF))
2405  LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToString());
2406  }
2407  }
2408  }
2409 #elif (HAVE_DECL_GETIFADDRS && HAVE_DECL_FREEIFADDRS)
2410  // Get local host ip
2411  struct ifaddrs* myaddrs;
2412  if (getifaddrs(&myaddrs) == 0)
2413  {
2414  for (struct ifaddrs* ifa = myaddrs; ifa != nullptr; ifa = ifa->ifa_next)
2415  {
2416  if (ifa->ifa_addr == nullptr) continue;
2417  if ((ifa->ifa_flags & IFF_UP) == 0) continue;
2418  if (strcmp(ifa->ifa_name, "lo") == 0) continue;
2419  if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
2420  if (ifa->ifa_addr->sa_family == AF_INET)
2421  {
2422  struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
2423  CNetAddr addr(s4->sin_addr);
2424  if (AddLocal(addr, LOCAL_IF))
2425  LogPrintf("%s: IPv4 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
2426  }
2427  else if (ifa->ifa_addr->sa_family == AF_INET6)
2428  {
2429  struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
2430  CNetAddr addr(s6->sin6_addr);
2431  if (AddLocal(addr, LOCAL_IF))
2432  LogPrintf("%s: IPv6 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
2433  }
2434  }
2435  freeifaddrs(myaddrs);
2436  }
2437 #endif
2438 }
2439 
2441 {
2442  LogPrintf("%s: %s\n", __func__, active);
2443 
2444  if (fNetworkActive == active) {
2445  return;
2446  }
2447 
2448  fNetworkActive = active;
2449 
2450  uiInterface.NotifyNetworkActiveChanged(fNetworkActive);
2451 }
2452 
2453 CConnman::CConnman(uint64_t nSeed0In, uint64_t nSeed1In, CAddrMan& addrman_in, bool network_active)
2454  : addrman(addrman_in), nSeed0(nSeed0In), nSeed1(nSeed1In)
2455 {
2456  SetTryNewOutboundPeer(false);
2457 
2458  Options connOptions;
2459  Init(connOptions);
2460  SetNetworkActive(network_active);
2461 }
2462 
2464 {
2465  return nLastNodeId.fetch_add(1, std::memory_order_relaxed);
2466 }
2467 
2468 
2469 bool CConnman::Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions) {
2470  if (!(flags & BF_EXPLICIT) && !IsReachable(addr)) {
2471  return false;
2472  }
2473  bilingual_str strError;
2474  if (!BindListenPort(addr, strError, permissions)) {
2475  if ((flags & BF_REPORT_ERROR) && clientInterface) {
2476  clientInterface->ThreadSafeMessageBox(strError, "", CClientUIInterface::MSG_ERROR);
2477  }
2478  return false;
2479  }
2480 
2482  AddLocal(addr, LOCAL_BIND);
2483  }
2484 
2485  return true;
2486 }
2487 
2488 bool CConnman::InitBinds(const Options& options)
2489 {
2490  bool fBound = false;
2491  for (const auto& addrBind : options.vBinds) {
2492  fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR), NetPermissionFlags::None);
2493  }
2494  for (const auto& addrBind : options.vWhiteBinds) {
2495  fBound |= Bind(addrBind.m_service, (BF_EXPLICIT | BF_REPORT_ERROR), addrBind.m_flags);
2496  }
2497  for (const auto& addr_bind : options.onion_binds) {
2499  }
2500  if (options.bind_on_any) {
2501  struct in_addr inaddr_any;
2502  inaddr_any.s_addr = htonl(INADDR_ANY);
2503  struct in6_addr inaddr6_any = IN6ADDR_ANY_INIT;
2504  fBound |= Bind(CService(inaddr6_any, GetListenPort()), BF_NONE, NetPermissionFlags::None);
2505  fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE, NetPermissionFlags::None);
2506  }
2507  return fBound;
2508 }
2509 
2510 bool CConnman::Start(CScheduler& scheduler, const Options& connOptions)
2511 {
2512  Init(connOptions);
2513 
2514  if (fListen && !InitBinds(connOptions)) {
2515  if (clientInterface) {
2516  clientInterface->ThreadSafeMessageBox(
2517  _("Failed to listen on any port. Use -listen=0 if you want this."),
2519  }
2520  return false;
2521  }
2522 
2523  proxyType i2p_sam;
2524  if (GetProxy(NET_I2P, i2p_sam)) {
2525  m_i2p_sam_session = std::make_unique<i2p::sam::Session>(gArgs.GetDataDirNet() / "i2p_private_key",
2526  i2p_sam.proxy, &interruptNet);
2527  }
2528 
2529  for (const auto& strDest : connOptions.vSeedNodes) {
2530  AddAddrFetch(strDest);
2531  }
2532 
2533  if (clientInterface) {
2534  clientInterface->InitMessage(_("Loading P2P addresses…").translated);
2535  }
2536  // Load addresses from peers.dat
2537  int64_t nStart = GetTimeMillis();
2538  {
2539  CAddrDB adb;
2540  if (adb.Read(addrman))
2541  LogPrintf("Loaded %i addresses from peers.dat %dms\n", addrman.size(), GetTimeMillis() - nStart);
2542  else {
2543  addrman.Clear(); // Addrman can be in an inconsistent state after failure, reset it
2544  LogPrintf("Recreating peers.dat\n");
2545  DumpAddresses();
2546  }
2547  }
2548 
2549  if (m_use_addrman_outgoing) {
2550  // Load addresses from anchors.dat
2552  if (m_anchors.size() > MAX_BLOCK_RELAY_ONLY_ANCHORS) {
2554  }
2555  LogPrintf("%i block-relay-only anchors will be tried for connections.\n", m_anchors.size());
2556  }
2557 
2558  uiInterface.InitMessage(_("Starting network threads…").translated);
2559 
2560  fAddressesInitialized = true;
2561 
2562  if (semOutbound == nullptr) {
2563  // initialize semaphore
2564  semOutbound = std::make_unique<CSemaphore>(std::min(m_max_outbound, nMaxConnections));
2565  }
2566  if (semAddnode == nullptr) {
2567  // initialize semaphore
2568  semAddnode = std::make_unique<CSemaphore>(nMaxAddnode);
2569  }
2570 
2571  //
2572  // Start threads
2573  //
2574  assert(m_msgproc);
2575  InterruptSocks5(false);
2576  interruptNet.reset();
2577  flagInterruptMsgProc = false;
2578 
2579  {
2580  LOCK(mutexMsgProc);
2581  fMsgProcWake = false;
2582  }
2583 
2584  // Send and receive from sockets, accept connections
2585  threadSocketHandler = std::thread(&util::TraceThread, "net", [this] { ThreadSocketHandler(); });
2586 
2587  if (!gArgs.GetBoolArg("-dnsseed", DEFAULT_DNSSEED))
2588  LogPrintf("DNS seeding disabled\n");
2589  else
2590  threadDNSAddressSeed = std::thread(&util::TraceThread, "dnsseed", [this] { ThreadDNSAddressSeed(); });
2591 
2592  // Initiate manual connections
2593  threadOpenAddedConnections = std::thread(&util::TraceThread, "addcon", [this] { ThreadOpenAddedConnections(); });
2594 
2595  if (connOptions.m_use_addrman_outgoing && !connOptions.m_specified_outgoing.empty()) {
2596  if (clientInterface) {
2597  clientInterface->ThreadSafeMessageBox(
2598  _("Cannot provide specific connections and have addrman find outgoing connections at the same."),
2600  }
2601  return false;
2602  }
2603  if (connOptions.m_use_addrman_outgoing || !connOptions.m_specified_outgoing.empty()) {
2604  threadOpenConnections = std::thread(
2605  &util::TraceThread, "opencon",
2606  [this, connect = connOptions.m_specified_outgoing] { ThreadOpenConnections(connect); });
2607  }
2608 
2609  // Process messages
2610  threadMessageHandler = std::thread(&util::TraceThread, "msghand", [this] { ThreadMessageHandler(); });
2611 
2612  if (connOptions.m_i2p_accept_incoming && m_i2p_sam_session.get() != nullptr) {
2614  std::thread(&util::TraceThread, "i2paccept", [this] { ThreadI2PAcceptIncoming(); });
2615  }
2616 
2617  // Dump network addresses
2618  scheduler.scheduleEvery([this] { DumpAddresses(); }, DUMP_PEERS_INTERVAL);
2619 
2620  return true;
2621 }
2622 
2624 {
2625 public:
2627 
2629  {
2630 #ifdef WIN32
2631  // Shutdown Windows Sockets
2632  WSACleanup();
2633 #endif
2634  }
2635 };
2637 
2639 {
2640  {
2641  LOCK(mutexMsgProc);
2642  flagInterruptMsgProc = true;
2643  }
2644  condMsgProc.notify_all();
2645 
2646  interruptNet();
2647  InterruptSocks5(true);
2648 
2649  if (semOutbound) {
2650  for (int i=0; i<m_max_outbound; i++) {
2651  semOutbound->post();
2652  }
2653  }
2654 
2655  if (semAddnode) {
2656  for (int i=0; i<nMaxAddnode; i++) {
2657  semAddnode->post();
2658  }
2659  }
2660 }
2661 
2663 {
2664  if (threadI2PAcceptIncoming.joinable()) {
2665  threadI2PAcceptIncoming.join();
2666  }
2667  if (threadMessageHandler.joinable())
2668  threadMessageHandler.join();
2669  if (threadOpenConnections.joinable())
2670  threadOpenConnections.join();
2671  if (threadOpenAddedConnections.joinable())
2673  if (threadDNSAddressSeed.joinable())
2674  threadDNSAddressSeed.join();
2675  if (threadSocketHandler.joinable())
2676  threadSocketHandler.join();
2677 }
2678 
2680 {
2681  if (fAddressesInitialized) {
2682  DumpAddresses();
2683  fAddressesInitialized = false;
2684 
2685  if (m_use_addrman_outgoing) {
2686  // Anchor connections are only dumped during clean shutdown.
2687  std::vector<CAddress> anchors_to_dump = GetCurrentBlockRelayOnlyConns();
2688  if (anchors_to_dump.size() > MAX_BLOCK_RELAY_ONLY_ANCHORS) {
2689  anchors_to_dump.resize(MAX_BLOCK_RELAY_ONLY_ANCHORS);
2690  }
2692  }
2693  }
2694 
2695  // Delete peer connections.
2696  std::vector<CNode*> nodes;
2697  WITH_LOCK(cs_vNodes, nodes.swap(vNodes));
2698  for (CNode* pnode : nodes) {
2699  pnode->CloseSocketDisconnect();
2700  DeleteNode(pnode);
2701  }
2702 
2703  // Close listening sockets.
2704  for (ListenSocket& hListenSocket : vhListenSocket) {
2705  if (hListenSocket.socket != INVALID_SOCKET) {
2706  if (!CloseSocket(hListenSocket.socket)) {
2707  LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError()));
2708  }
2709  }
2710  }
2711 
2712  for (CNode* pnode : vNodesDisconnected) {
2713  DeleteNode(pnode);
2714  }
2715  vNodesDisconnected.clear();
2716  vhListenSocket.clear();
2717  semOutbound.reset();
2718  semAddnode.reset();
2719 }
2720 
2722 {
2723  assert(pnode);
2724  m_msgproc->FinalizeNode(*pnode);
2725  delete pnode;
2726 }
2727 
2729 {
2730  Interrupt();
2731  Stop();
2732 }
2733 
2734 std::vector<CAddress> CConnman::GetAddresses(size_t max_addresses, size_t max_pct, std::optional<Network> network) const
2735 {
2736  std::vector<CAddress> addresses = addrman.GetAddr(max_addresses, max_pct, network);
2737  if (m_banman) {
2738  addresses.erase(std::remove_if(addresses.begin(), addresses.end(),
2739  [this](const CAddress& addr){return m_banman->IsDiscouraged(addr) || m_banman->IsBanned(addr);}),
2740  addresses.end());
2741  }
2742  return addresses;
2743 }
2744 
2745 std::vector<CAddress> CConnman::GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct)
2746 {
2747  auto local_socket_bytes = requestor.addrBind.GetAddrBytes();
2749  .Write(requestor.addr.GetNetwork())
2750  .Write(local_socket_bytes.data(), local_socket_bytes.size())
2751  .Finalize();
2752  const auto current_time = GetTime<std::chrono::microseconds>();
2753  auto r = m_addr_response_caches.emplace(cache_id, CachedAddrResponse{});
2754  CachedAddrResponse& cache_entry = r.first->second;
2755  if (cache_entry.m_cache_entry_expiration < current_time) { // If emplace() added new one it has expiration 0.
2756  cache_entry.m_addrs_response_cache = GetAddresses(max_addresses, max_pct, /* network */ std::nullopt);
2757  // Choosing a proper cache lifetime is a trade-off between the privacy leak minimization
2758  // and the usefulness of ADDR responses to honest users.
2759  //
2760  // Longer cache lifetime makes it more difficult for an attacker to scrape
2761  // enough AddrMan data to maliciously infer something useful.
2762  // By the time an attacker scraped enough AddrMan records, most of
2763  // the records should be old enough to not leak topology info by
2764  // e.g. analyzing real-time changes in timestamps.
2765  //
2766  // It takes only several hundred requests to scrape everything from an AddrMan containing 100,000 nodes,
2767  // so ~24 hours of cache lifetime indeed makes the data less inferable by the time
2768  // most of it could be scraped (considering that timestamps are updated via
2769  // ADDR self-announcements and when nodes communicate).
2770  // We also should be robust to those attacks which may not require scraping *full* victim's AddrMan
2771  // (because even several timestamps of the same handful of nodes may leak privacy).
2772  //
2773  // On the other hand, longer cache lifetime makes ADDR responses
2774  // outdated and less useful for an honest requestor, e.g. if most nodes
2775  // in the ADDR response are no longer active.
2776  //
2777  // However, the churn in the network is known to be rather low. Since we consider
2778  // nodes to be "terrible" (see IsTerrible()) if the timestamps are older than 30 days,
2779  // max. 24 hours of "penalty" due to cache shouldn't make any meaningful difference
2780  // in terms of the freshness of the response.
2781  cache_entry.m_cache_entry_expiration = current_time + std::chrono::hours(21) + GetRandMillis(std::chrono::hours(6));
2782  }
2783  return cache_entry.m_addrs_response_cache;
2784 }
2785 
2786 bool CConnman::AddNode(const std::string& strNode)
2787 {
2789  for (const std::string& it : vAddedNodes) {
2790  if (strNode == it) return false;
2791  }
2792 
2793  vAddedNodes.push_back(strNode);
2794  return true;
2795 }
2796 
2797 bool CConnman::RemoveAddedNode(const std::string& strNode)
2798 {
2800  for(std::vector<std::string>::iterator it = vAddedNodes.begin(); it != vAddedNodes.end(); ++it) {
2801  if (strNode == *it) {
2802  vAddedNodes.erase(it);
2803  return true;
2804  }
2805  }
2806  return false;
2807 }
2808 
2810 {
2811  LOCK(cs_vNodes);
2812  if (flags == ConnectionDirection::Both) // Shortcut if we want total
2813  return vNodes.size();
2814 
2815  int nNum = 0;
2816  for (const auto& pnode : vNodes) {
2817  if (flags & (pnode->IsInboundConn() ? ConnectionDirection::In : ConnectionDirection::Out)) {
2818  nNum++;
2819  }
2820  }
2821 
2822  return nNum;
2823 }
2824 
2825 void CConnman::GetNodeStats(std::vector<CNodeStats>& vstats) const
2826 {
2827  vstats.clear();
2828  LOCK(cs_vNodes);
2829  vstats.reserve(vNodes.size());
2830  for (CNode* pnode : vNodes) {
2831  vstats.emplace_back();
2832  pnode->copyStats(vstats.back(), addrman.m_asmap);
2833  }
2834 }
2835 
2836 bool CConnman::DisconnectNode(const std::string& strNode)
2837 {
2838  LOCK(cs_vNodes);
2839  if (CNode* pnode = FindNode(strNode)) {
2840  LogPrint(BCLog::NET, "disconnect by address%s matched peer=%d; disconnecting\n", (fLogIPs ? strprintf("=%s", strNode) : ""), pnode->GetId());
2841  pnode->fDisconnect = true;
2842  return true;
2843  }
2844  return false;
2845 }
2846 
2848 {
2849  bool disconnected = false;
2850  LOCK(cs_vNodes);
2851  for (CNode* pnode : vNodes) {
2852  if (subnet.Match(pnode->addr)) {
2853  LogPrint(BCLog::NET, "disconnect by subnet%s matched peer=%d; disconnecting\n", (fLogIPs ? strprintf("=%s", subnet.ToString()) : ""), pnode->GetId());
2854  pnode->fDisconnect = true;
2855  disconnected = true;
2856  }
2857  }
2858  return disconnected;
2859 }
2860 
2862 {
2863  return DisconnectNode(CSubNet(addr));
2864 }
2865 
2867 {
2868  LOCK(cs_vNodes);
2869  for(CNode* pnode : vNodes) {
2870  if (id == pnode->GetId()) {
2871  LogPrint(BCLog::NET, "disconnect by id peer=%d; disconnecting\n", pnode->GetId());
2872  pnode->fDisconnect = true;
2873  return true;
2874  }
2875  }
2876  return false;
2877 }
2878 
2879 void CConnman::RecordBytesRecv(uint64_t bytes)
2880 {
2882  nTotalBytesRecv += bytes;
2883 }
2884 
2885 void CConnman::RecordBytesSent(uint64_t bytes)
2886 {
2888  nTotalBytesSent += bytes;
2889 
2890  const auto now = GetTime<std::chrono::seconds>();
2891  if (nMaxOutboundCycleStartTime + MAX_UPLOAD_TIMEFRAME < now)
2892  {
2893  // timeframe expired, reset cycle
2894  nMaxOutboundCycleStartTime = now;
2895  nMaxOutboundTotalBytesSentInCycle = 0;
2896  }
2897 
2898  // TODO, exclude peers with download permission
2899  nMaxOutboundTotalBytesSentInCycle += bytes;
2900 }
2901 
2903 {
2905  return nMaxOutboundLimit;
2906 }
2907 
2908 std::chrono::seconds CConnman::GetMaxOutboundTimeframe() const
2909 {
2910  return MAX_UPLOAD_TIMEFRAME;
2911 }
2912 
2913 std::chrono::seconds CConnman::GetMaxOutboundTimeLeftInCycle() const
2914 {
2916  if (nMaxOutboundLimit == 0)
2917  return 0s;
2918 
2919  if (nMaxOutboundCycleStartTime.count() == 0)
2920  return MAX_UPLOAD_TIMEFRAME;
2921 
2922  const std::chrono::seconds cycleEndTime = nMaxOutboundCycleStartTime + MAX_UPLOAD_TIMEFRAME;
2923  const auto now = GetTime<std::chrono::seconds>();
2924  return (cycleEndTime < now) ? 0s : cycleEndTime - now;
2925 }
2926 
2927 bool CConnman::OutboundTargetReached(bool historicalBlockServingLimit) const
2928 {
2930  if (nMaxOutboundLimit == 0)
2931  return false;
2932 
2933  if (historicalBlockServingLimit)
2934  {
2935  // keep a large enough buffer to at least relay each block once
2936  const std::chrono::seconds timeLeftInCycle = GetMaxOutboundTimeLeftInCycle();
2937  const uint64_t buffer = timeLeftInCycle / std::chrono::minutes{10} * MAX_BLOCK_SERIALIZED_SIZE;
2938  if (buffer >= nMaxOutboundLimit || nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit - buffer)
2939  return true;
2940  }
2941  else if (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit)
2942  return true;
2943 
2944  return false;
2945 }
2946 
2948 {
2950  if (nMaxOutboundLimit == 0)
2951  return 0;
2952 
2953  return (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit) ? 0 : nMaxOutboundLimit - nMaxOutboundTotalBytesSentInCycle;
2954 }
2955 
2957 {
2959  return nTotalBytesRecv;
2960 }
2961 
2963 {
2965  return nTotalBytesSent;
2966 }
2967 
2969 {
2970  return nLocalServices;
2971 }
2972 
2973 unsigned int CConnman::GetReceiveFloodSize() const { return nReceiveFloodSize; }
2974 
2975 CNode::CNode(NodeId idIn, ServiceFlags nLocalServicesIn, SOCKET hSocketIn, const CAddress& addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const CAddress& addrBindIn, const std::string& addrNameIn, ConnectionType conn_type_in, bool inbound_onion)
2976  : nTimeConnected(GetTimeSeconds()),
2977  addr(addrIn),
2978  addrBind(addrBindIn),
2979  m_inbound_onion(inbound_onion),
2980  nKeyedNetGroup(nKeyedNetGroupIn),
2981  id(idIn),
2982  nLocalHostNonce(nLocalHostNonceIn),
2983  m_conn_type(conn_type_in),
2984  nLocalServices(nLocalServicesIn)
2985 {
2986  if (inbound_onion) assert(conn_type_in == ConnectionType::INBOUND);
2987  hSocket = hSocketIn;
2988  addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
2989  if (conn_type_in != ConnectionType::BLOCK_RELAY) {
2990  m_tx_relay = std::make_unique<TxRelay>();
2991  }
2992 
2993  for (const std::string &msg : getAllNetMessageTypes())
2994  mapRecvBytesPerMsgCmd[msg] = 0;
2995  mapRecvBytesPerMsgCmd[NET_MESSAGE_COMMAND_OTHER] = 0;
2996 
2997  if (fLogIPs) {
2998  LogPrint(BCLog::NET, "Added connection to %s peer=%d\n", addrName, id);
2999  } else {
3000  LogPrint(BCLog::NET, "Added connection peer=%d\n", id);
3001  }
3002 
3003  m_deserializer = std::make_unique<V1TransportDeserializer>(V1TransportDeserializer(Params(), GetId(), SER_NETWORK, INIT_PROTO_VERSION));
3004  m_serializer = std::make_unique<V1TransportSerializer>(V1TransportSerializer());
3005 }
3006 
3008 {
3009  CloseSocket(hSocket);
3010 }
3011 
3013 {
3014  return pnode && pnode->fSuccessfullyConnected && !pnode->fDisconnect;
3015 }
3016 
3018 {
3019  size_t nMessageSize = msg.data.size();
3020  LogPrint(BCLog::NET, "sending %s (%d bytes) peer=%d\n", SanitizeString(msg.m_type), nMessageSize, pnode->GetId());
3021  if (gArgs.GetBoolArg("-capturemessages", false)) {
3022  CaptureMessage(pnode->addr, msg.m_type, msg.data, /* incoming */ false);
3023  }
3024 
3025  // make sure we use the appropriate network transport format
3026  std::vector<unsigned char> serializedHeader;
3027  pnode->m_serializer->prepareForTransport(msg, serializedHeader);
3028  size_t nTotalSize = nMessageSize + serializedHeader.size();
3029 
3030  size_t nBytesSent = 0;
3031  {
3032  LOCK(pnode->cs_vSend);
3033  bool optimisticSend(pnode->vSendMsg.empty());
3034 
3035  //log total amount of bytes per message type
3036  pnode->mapSendBytesPerMsgCmd[msg.m_type] += nTotalSize;
3037  pnode->nSendSize += nTotalSize;
3038 
3039  if (pnode->nSendSize > nSendBufferMaxSize) pnode->fPauseSend = true;
3040  pnode->vSendMsg.push_back(std::move(serializedHeader));
3041  if (nMessageSize) pnode->vSendMsg.push_back(std::move(msg.data));
3042 
3043  // If write queue empty, attempt "optimistic write"
3044  if (optimisticSend) nBytesSent = SocketSendData(*pnode);
3045  }
3046  if (nBytesSent) RecordBytesSent(nBytesSent);
3047 }
3048 
3049 bool CConnman::ForNode(NodeId id, std::function<bool(CNode* pnode)> func)
3050 {
3051  CNode* found = nullptr;
3052  LOCK(cs_vNodes);
3053  for (auto&& pnode : vNodes) {
3054  if(pnode->GetId() == id) {
3055  found = pnode;
3056  break;
3057  }
3058  }
3059  return found != nullptr && NodeFullyConnected(found) && func(found);
3060 }
3061 
3062 std::chrono::microseconds CConnman::PoissonNextSendInbound(std::chrono::microseconds now, std::chrono::seconds average_interval)
3063 {
3064  if (m_next_send_inv_to_incoming.load() < now) {
3065  // If this function were called from multiple threads simultaneously
3066  // it would possible that both update the next send variable, and return a different result to their caller.
3067  // This is not possible in practice as only the net processing thread invokes this function.
3068  m_next_send_inv_to_incoming = PoissonNextSend(now, average_interval);
3069  }
3071 }
3072 
3073 std::chrono::microseconds PoissonNextSend(std::chrono::microseconds now, std::chrono::seconds average_interval)
3074 {
3075  double unscaled = -log1p(GetRand(1ULL << 48) * -0.0000000000000035527136788 /* -1/2^48 */);
3076  return now + std::chrono::duration_cast<std::chrono::microseconds>(unscaled * average_interval + 0.5us);
3077 }
3078 
3080 {
3081  return CSipHasher(nSeed0, nSeed1).Write(id);
3082 }
3083 
3085 {
3086  std::vector<unsigned char> vchNetGroup(ad.GetGroup(addrman.m_asmap));
3087 
3088  return GetDeterministicRandomizer(RANDOMIZER_ID_NETGROUP).Write(vchNetGroup.data(), vchNetGroup.size()).Finalize();
3089 }
3090 
3091 void CaptureMessage(const CAddress& addr, const std::string& msg_type, const Span<const unsigned char>& data, bool is_incoming)
3092 {
3093  // Note: This function captures the message at the time of processing,
3094  // not at socket receive/send time.
3095  // This ensures that the messages are always in order from an application
3096  // layer (processing) perspective.
3097  auto now = GetTime<std::chrono::microseconds>();
3098 
3099  // Windows folder names can not include a colon
3100  std::string clean_addr = addr.ToString();
3101  std::replace(clean_addr.begin(), clean_addr.end(), ':', '_');
3102 
3103  fs::path base_path = gArgs.GetDataDirNet() / "message_capture" / clean_addr;
3104  fs::create_directories(base_path);
3105 
3106  fs::path path = base_path / (is_incoming ? "msgs_recv.dat" : "msgs_sent.dat");
3108 
3109  ser_writedata64(f, now.count());
3110  f.write(msg_type.data(), msg_type.length());
3111  for (auto i = msg_type.length(); i < CMessageHeader::COMMAND_SIZE; ++i) {
3112  f << uint8_t{'\0'};
3113  }
3114  uint32_t size = data.size();
3115  ser_writedata32(f, size);
3116  f.write((const char*)data.data(), data.size());
3117 }
const std::vector< std::string > & DNSSeeds() const
Return the list of hostnames to look up for DNS seeds.
Definition: chainparams.h:114
std::vector< CService > vBinds
Definition: net.h:769
std::atomic< bool > flagInterruptMsgProc
Definition: net.h:1148
uint256 data_hash
Definition: net.h:322
void copyStats(CNodeStats &stats, const std::vector< bool > &m_asmap)
Definition: net.cpp:569
std::vector< CAddress > m_addrs_response_cache
Definition: net.h:1080
std::vector< unsigned char > GetGroup(const std::vector< bool > &asmap) const
Get the canonical identifier of our network group.
Definition: netaddress.cpp:766
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
std::chrono::microseconds m_min_ping_time
Definition: net.h:1204
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:66
CONSTEXPR_IF_NOT_DEBUG Span< C > first(std::size_t count) const noexcept
Definition: span.h:199
uint64_t CalculateKeyedNetGroup(const CAddress &ad) const
Definition: net.cpp:3084
#define WSAEINPROGRESS
Definition: compat.h:50
std::string m_type
Definition: net.h:111
void SocketHandler()
Definition: net.cpp:1512
void RandAddEvent(const uint32_t event_info) noexcept
Gathers entropy from the low bits of the time at which events occur.
Definition: random.cpp:587
void MoveTo(CSemaphoreGrant &grant)
Definition: sync.h:345
std::atomic_bool fPauseSend
Definition: net.h:458
uint8_t pchChecksum[CHECKSUM_SIZE]
Definition: protocol.h:57
Access to the (IP) address database (peers.dat)
Definition: addrdb.h:68
uint64_t GetRand(uint64_t nMax) noexcept
Generate a uniform random integer in the range [0..range).
Definition: random.cpp:591
#define WSAEINTR
Definition: compat.h:49
void ThreadOpenAddedConnections()
Definition: net.cpp:2171
bool GetLocal(CService &addr, const CNetAddr *paddrPeer)
Definition: net.cpp:127
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:58
bool m_i2p_accept_incoming
Definition: net.h:778
std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const
returns the time left in the current max outbound cycle in case of no limit, it will always return 0 ...
Definition: net.cpp:2913
int m_max_outbound
Definition: net.h:1127
std::atomic< bool > fNetworkActive
Definition: net.h:1060
static void AddFlag(NetPermissionFlags &flags, NetPermissionFlags f)
ServiceFlags
nServices flags
Definition: protocol.h:271
void Finalize(Span< unsigned char > output)
Definition: hash.h:30
uint16_t GetPort() const
Definition: netaddress.cpp:955
std::unique_ptr< TransportSerializer > m_serializer
Definition: net.h:401
RecursiveMutex cs_vNodes
Definition: net.h:1069
#define LogPrint(category,...)
Definition: logging.h:188
int readData(Span< const uint8_t > msg_bytes)
Definition: net.cpp:710
assert(!tx.IsCoinBase())
bool AddLocal(const CService &addr, int nScore)
Definition: net.cpp:230
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:24
A set of addresses that represent the hash of a string or FQDN.
Definition: netaddress.h:67
We open manual connections to addresses that users explicitly requested via the addnode RPC or the -a...
uint32_t m_mapped_as
Definition: net.h:274
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
CAddrInfo SelectTriedCollision() EXCLUSIVE_LOCKS_REQUIRED(!cs)
Randomly select an address in tried that another address is attempting to evict.
Definition: addrman.h:569
Dummy value to indicate the number of NET_* constants.
Definition: netaddress.h:70
void scheduleEvery(Function f, std::chrono::milliseconds delta)
Repeat f until the scheduler is stopped.
Definition: scheduler.cpp:110
static bool IsSelectableSocket(const SOCKET &s)
Definition: compat.h:100
void SetIP(const CNetAddr &ip)
Definition: netaddress.cpp:107
void WakeMessageHandler()
Definition: net.cpp:1640
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
Definition: net.cpp:2469
uint64_t GetOutboundTargetBytesLeft() const
response the bytes left in the current max outbound cycle in case of no limit, it will always respons...
Definition: net.cpp:2947
void Interrupt()
Definition: net.cpp:2638
int64_t nLastTXTime
Definition: net.h:1206
void ser_writedata64(Stream &s, uint64_t obj)
Definition: serialize.h:84
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:1437
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:117
Mutex mutexMsgProc
Definition: net.h:1147
static const bool DEFAULT_FORCEDNSSEED
Definition: net.h:82
const bool m_is_local
Definition: net.cpp:885
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
CDataStream hdrbuf
Definition: net.h:324
int64_t GetTimeSeconds()
Returns the system time (not mockable)
Definition: time.cpp:127
#define WSAEADDRINUSE
Definition: compat.h:51
static void ClearFlag(NetPermissionFlags &flags, NetPermissionFlags f)
ClearFlag is only called with f == NetPermissionFlags::Implicit.
bool IsIPv6() const
Definition: netaddress.cpp:320
std::vector< unsigned char > data
Definition: net.h:110
unsigned int nDataPos
Definition: net.h:328
const ConnectionType m_conn_type
Definition: net.h:676
uint64_t GetTotalBytesRecv() const
Definition: net.cpp:2956
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:40
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:1054
void * sockopt_arg_type
Definition: compat.h:88
constexpr auto GetRandMillis
Definition: random.h:84
int m_max_outbound_full_relay
Definition: net.h:1119
void resize(size_type n, value_type c=0)
Definition: streams.h:257
bool GetNameProxy(proxyType &nameProxyOut)
Definition: netbase.cpp:633
std::vector< CService > m_onion_binds
A vector of -bind=<address>:<port>=onion arguments each of which is an address and port that are desi...
Definition: net.h:1188
void ser_writedata32(Stream &s, uint32_t obj)
Definition: serialize.h:74
static constexpr std::chrono::seconds MAX_UPLOAD_TIMEFRAME
The default timeframe for -maxuploadtarget.
Definition: net.cpp:79
void ProcessAddrFetch()
Definition: net.cpp:1770
constexpr std::size_t size() const noexcept
Definition: span.h:182
bool LookupHost(const std::string &name, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
Resolve a host string to its corresponding network addresses.
Definition: netbase.cpp:169
bool AlreadyConnectedToAddress(const CAddress &addr)
Determine whether we&#39;re already connected to a given address, in order to avoid initiating duplicate ...
Definition: net.cpp:351
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, const CNetAddr &addr) const
Definition: net.cpp:510
#define FEELER_SLEEP_WINDOW
Definition: net.cpp:82
int nMaxAddnode
Definition: net.h:1125
RAII-style semaphore lock.
Definition: sync.h:315
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
Definition: net.cpp:3017
CService me
Our I2P address.
Definition: i2p.h:36
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
Definition: net.cpp:2328
bool m_prefer_evict
Definition: net.h:442
#define PACKAGE_NAME
RecursiveMutex cs_addrName
Definition: net.h:698
bool fDiscover
Definition: net.cpp:108
NetEventsInterface * m_msgproc
Definition: net.h:1130
CAmount minFeeFilter
Definition: net.h:265
void Discover()
Definition: net.cpp:2389
CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
Definition: net.cpp:177
void CreateNodeFromAcceptedSocket(SOCKET hSocket, NetPermissionFlags permissionFlags, const CAddress &addr_bind, const CAddress &addr)
Create a CNode object from a socket that has just been accepted and add the node to the vNodes member...
Definition: net.cpp:1118
CAddrMan & addrman
Definition: net.h:1062
int m_max_outbound_block_relay
Definition: net.h:1123
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:204
void Clear() EXCLUSIVE_LOCKS_REQUIRED(!cs)
Definition: addrman.h:464
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:600
void SetTryNewOutboundPeer(bool flag)
Definition: net.cpp:1792
uint32_t nMessageSize
Definition: protocol.h:56
std::string ToString() const
Definition: netaddress.cpp:631
std::unique_ptr< TransportDeserializer > m_deserializer
Definition: net.h:400
static const uint64_t RANDOMIZER_ID_LOCALHOSTNONCE
Definition: net.cpp:103
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:288
void ThreadSocketHandler()
Definition: net.cpp:1630
An established connection with another peer.
Definition: i2p.h:31
static bool CompareNodeBlockTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition: net.cpp:850
Network GetNetClass() const
Definition: netaddress.cpp:707
#define INVALID_SOCKET
Definition: compat.h:53
static bool CompareNodeBlockRelayOnlyTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition: net.cpp:868
CService LookupNumeric(const std::string &name, uint16_t portDefault, DNSLookupFn dns_lookup_function)
Resolve a service string with a numeric IP to its first corresponding service.
Definition: netbase.cpp:229
std::chrono::microseconds PoissonNextSend(std::chrono::microseconds now, std::chrono::seconds average_interval)
Return a timestamp in the future (in microseconds) for exponentially distributed events.
Definition: net.cpp:3073
NetPermissionFlags
static std::vector< CAddress > ConvertSeeds(const std::vector< uint8_t > &vSeedsIn)
Convert the serialized seeds into usable address objects.
Definition: net.cpp:152
std::string GetCommand() const
Definition: protocol.cpp:102
static const int TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:52
unsigned char * begin()
Definition: uint256.h:58
std::vector< CAddress > GetAddresses(size_t max_addresses, size_t max_pct, std::optional< Network > network) const
Return all or many randomly selected addresses, optionally by network.
Definition: net.cpp:2734
void GetNodeStats(std::vector< CNodeStats > &vstats) const
Definition: net.cpp:2825
bool Lookup(const std::string &name, std::vector< CService > &vAddr, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
Resolve a service string to its corresponding service.
Definition: netbase.cpp:197
#define WSAGetLastError()
Definition: compat.h:43
bool operator()(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b) const
Definition: net.cpp:888
bool ConnectThroughProxy(const proxyType &proxy, const std::string &strDest, uint16_t port, const Sock &sock, int nTimeout, bool &outProxyConnectionFailed)
Connect to a specified destination service through a SOCKS5 proxy by first connecting to the SOCKS5 p...
Definition: netbase.cpp:655
void StopThreads()
Definition: net.cpp:2662
static bool CompareNodeTXTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition: net.cpp:858
std::list< CNetMessage > vRecvMsg
Definition: net.h:696
bool GetTryNewOutboundPeer() const
Definition: net.cpp:1787
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:268
void DumpAnchors(const fs::path &anchors_db_path, const std::vector< CAddress > &anchors)
Dump the anchor IP address database (anchors.dat)
Definition: addrdb.cpp:256
bool IsNull() const
Definition: uint256.h:31
void NotifyNumConnectionsChanged()
Definition: net.cpp:1297
enum Network GetNetwork() const
Definition: netaddress.cpp:524
const NodeId m_node_id
Definition: net.h:320
I2P.
Definition: netaddress.h:60
void RecordBytesSent(uint64_t bytes)
Definition: net.cpp:2885
std::map< uint64_t, CachedAddrResponse > m_addr_response_caches
Addr responses stored in different caches per (network, local socket) prevent cross-network node iden...
Definition: net.h:1098
std::atomic< ServiceFlags > nServices
Definition: net.h:404
void SetAddrLocal(const CService &addrLocalIn)
May not be called more than once.
Definition: net.cpp:553
static bool HasFlag(NetPermissionFlags flags, NetPermissionFlags f)
void write(const char *pch, size_t nSize)
Definition: streams.h:638
bool IsCommandValid() const
Definition: protocol.cpp:107
uint32_t GetMappedAS(const std::vector< bool > &asmap) const
Definition: netaddress.cpp:725
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition: net.h:961
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:3049
uint16_t GetDefaultPort() const
Definition: chainparams.h:84
ServiceFlags nLocalServices
Services this instance offers.
Definition: net.h:1112
RecursiveMutex cs_mapLocalHost
Definition: net.cpp:110
bool IsValid() const
Definition: netaddress.cpp:451
bool DisconnectNode(const std::string &node)
Definition: net.cpp:2836
static constexpr int DNSSEEDS_DELAY_PEER_THRESHOLD
Definition: net.cpp:76
Stochastical (IP) address manager.
Definition: addrman.h:173
CHash256 hasher
Definition: net.h:321
Definition: net.cpp:86
int GetExtraBlockRelayCount() const
Definition: net.cpp:1818
std::atomic< int64_t > nLastSend
Definition: net.h:424
static constexpr int ADDRV2_FORMAT
A flag that is ORed into the protocol version to designate that addresses should be serialized in (un...
Definition: netaddress.h:34
uint16_t nPort
Definition: net.h:230
void RecordBytesRecv(uint64_t bytes)
Definition: net.cpp:2879
bool HaveNameProxy()
Definition: netbase.cpp:641
void DumpAddresses()
Definition: net.cpp:1759
bool IsDiscouraged(const CNetAddr &net_addr)
Return whether net_addr is discouraged.
Definition: banman.cpp:69
std::chrono::microseconds PoissonNextSendInbound(std::chrono::microseconds now, std::chrono::seconds average_interval)
Attempts to obfuscate tx time through exponentially distributed emitting.
Definition: net.cpp:3062
uint64_t randbits(int bits) noexcept
Generate a random (bits)-bit integer.
Definition: random.h:172
std::thread threadI2PAcceptIncoming
Definition: net.h:1169
#define LOCK2(cs1, cs2)
Definition: sync.h:233
std::vector< CAddress > GetAddr(size_t max_addresses, size_t max_pct, std::optional< Network > network) EXCLUSIVE_LOCKS_REQUIRED(!cs)
Return all or many randomly selected addresses, optionally by network.
Definition: addrman.h:599
Extended statistics about a CAddress.
Definition: addrman.h:32
ServiceFlags GetLocalServices() const
Definition: net.h:656
#define SOCKET_ERROR
Definition: compat.h:54
static CAddress GetBindAddress(SOCKET sock)
Get the bind address for a socket as CAddress.
Definition: net.cpp:367
void TraceThread(const char *thread_name, std::function< void()> thread_func)
A wrapper for do-something-once thread functions.
Definition: thread.cpp:13
void CloseSocketDisconnect()
Definition: net.cpp:499
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
Definition: net.cpp:516
CAddrInfo Select(bool newOnly=false) EXCLUSIVE_LOCKS_REQUIRED(!cs)
Choose an address to connect to.
Definition: addrman.h:582
uint16_t GetListenPort()
Definition: net.cpp:121
Sort eviction candidates by network/localhost and connection uptime.
Definition: net.cpp:884
bool Write(const CAddrMan &addr)
Definition: addrdb.cpp:236
size_type size() const
Definition: streams.h:255
std::chrono::microseconds m_cache_entry_expiration
Definition: net.h:1081
void AddAddrFetch(const std::string &strDest)
Definition: net.cpp:115
static bool NodeFullyConnected(const CNode *pnode)
Definition: net.cpp:3012
unsigned int nPrevNodeCount
Definition: net.h:1071
static const uint64_t RANDOMIZER_ID_NETGROUP
Definition: net.cpp:102
bool InactivityCheck(const CNode &node) const
Return true if the peer is inactive and should be disconnected.
Definition: net.cpp:1317
bool AddNode(const std::string &node)
Definition: net.cpp:2786
static constexpr size_t COMMAND_SIZE
Definition: protocol.h:34
std::condition_variable condMsgProc
Definition: net.h:1146
std::atomic_bool m_start_extra_block_relay_peers
flag for initiating extra block-relay-only peer connections.
Definition: net.h:1180
bool ConnectSocketDirectly(const CService &addrConnect, const Sock &sock, int nTimeout, bool manual_connection)
Try to connect to the specified service on the specified socket.
Definition: netbase.cpp:540
RecursiveMutex cs_vAddedNodes
Definition: net.h:1066
CService GetAddrLocal() const
Definition: net.cpp:548
bool Add(const CAddress &addr, const CNetAddr &source, int64_t nTimePenalty=0) EXCLUSIVE_LOCKS_REQUIRED(!cs)
Add a single address.
Definition: addrman.h:508
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *strDest, ConnectionType conn_type)
Definition: net.cpp:2199
size_t SocketSendData(CNode &node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend)
Definition: net.cpp:785
std::atomic< int64_t > nLastRecv
Definition: net.h:425
std::optional< CAddress > GetLocalAddrForPeer(CNode *pnode)
Returns a local address that we should advertise to this peer.
Definition: net.cpp:204
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition: net.h:1141
static bool HasAllDesirableServiceFlags(ServiceFlags services)
A shortcut for (services & GetDesirableServiceFlags(services)) == GetDesirableServiceFlags(services)...
Definition: protocol.h:343
std::thread threadOpenAddedConnections
Definition: net.h:1166
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Obtain the IPv4/6 socket address this represents.
Definition: netaddress.cpp:982
std::vector< CAddress > ReadAnchors(const fs::path &anchors_db_path)
Read the anchor IP address database (anchors.dat)
Definition: addrdb.cpp:262
Network m_network
Definition: net.h:1213
std::string ToStringIP() const
Definition: netaddress.cpp:608
#define LOCK(cs)
Definition: sync.h:232
Mutex cs_hSocket
Definition: net.h:413
CNode * FindNode(const CNetAddr &ip)
Definition: net.cpp:307
void ResolveCollisions() EXCLUSIVE_LOCKS_REQUIRED(!cs)
See if any to-be-evicted tried table entries have been tested and if so resolve the collisions...
Definition: addrman.h:559
#define MSG_NOSIGNAL
Definition: compat.h:110
ServiceFlags GetLocalServices() const
Used to convey which local services we are offering peers during node connection. ...
Definition: net.cpp:2968
RecursiveMutex m_addr_fetches_mutex
Definition: net.h:1064
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:57
bool IsPeerAddrLocalGood(CNode *pnode)
Definition: net.cpp:197
static const int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
Definition: version.h:15
bool CloseSocket(SOCKET &hSocket)
Close socket and set hSocket to INVALID_SOCKET.
Definition: sock.cpp:329
CConnman(uint64_t seed0, uint64_t seed1, CAddrMan &addrman, bool network_active=true)
Definition: net.cpp:2453
static constexpr int DNSSEEDS_TO_QUERY_AT_ONCE
Number of DNS seeds to query when the number of connections is low.
Definition: net.cpp:63
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:560
Fast randomness source.
Definition: random.h:119
const CAddress addrBind
Definition: net.h:432
std::vector< std::string > vSeedNodes
Definition: net.h:766
std::vector< std::string > m_specified_outgoing
Definition: net.h:775
int64_t m_peer_connect_timeout
Definition: net.h:1050
void DisconnectNodes()
Definition: net.cpp:1247
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:1114
void ThreadOpenConnections(std::vector< std::string > connect)
Definition: net.cpp:1832
std::thread threadMessageHandler
Definition: net.h:1168
void CaptureMessage(const CAddress &addr, const std::string &msg_type, const Span< const unsigned char > &data, bool is_incoming)
Dump binary message to file, with timestamp.
Definition: net.cpp:3091
Network m_network
Definition: net.h:273
bool fInbound
Definition: net.h:254
const uint256 & GetMessageHash() const
Definition: net.cpp:727
virtual void FinalizeNode(const CNode &node)=0
Handle removal of a peer (clear state)
int GetExtraFullOutboundCount() const
Definition: net.cpp:1804
A CService with information about it as peer.
Definition: protocol.h:358
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const
Return vector of current BLOCK_RELAY peers.
Definition: net.cpp:2104
bool Start(CScheduler &scheduler, const Options &options)
Definition: net.cpp:2510
static int GetnScore(const CService &addr)
Definition: net.cpp:189
void MaybeSetAddrName(const std::string &addrNameIn)
Sets the addrName only if it was not previously set.
Definition: net.cpp:541
const std::vector< std::string > & getAllNetMessageTypes()
Definition: protocol.cpp:179
std::string addrName
Definition: net.h:251
Network
A network type.
Definition: netaddress.h:45
bool ReceiveMsgBytes(Span< const uint8_t > msg_bytes, bool &complete)
Receive bytes from the buffer and deserialize them into messages.
Definition: net.cpp:626
Do not call AddLocal() for our special addresses, e.g., for incoming Tor connections, to prevent gossiping them over the network.
Definition: net.cpp:93
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:1174
const CMessageHeader::MessageStartChars & MessageStart() const
Definition: chainparams.h:83
int64_t NodeId
Definition: net.h:88
bool InitBinds(const Options &options)
Definition: net.cpp:2488
CNetCleanup()
Definition: net.cpp:2626
void SetNetworkActive(bool active)
Definition: net.cpp:2440
#define WAIT_LOCK(cs, name)
Definition: sync.h:237
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:36
std::atomic< bool > m_bip152_highbandwidth_to
Definition: net.h:527
CClientUIInterface * clientInterface
Definition: net.h:1129
NodeId GetId() const
Definition: net.h:585
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition: net.cpp:3079
std::optional< CNetMessage > GetMessage(std::chrono::microseconds time, uint32_t &out_err_raw_size) override
Definition: net.cpp:735
static constexpr std::chrono::minutes DNSSEEDS_DELAY_MANY_PEERS
Definition: net.cpp:75
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e. connected via our Tor onion service.
Definition: net.h:434
std::atomic_bool fDisconnect
Definition: net.h:452
int nMaxConnections
Definition: net.h:1116
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:113
static RPCHelpMan send()
Definition: rpcwallet.cpp:4028
int nConnectTimeout
Definition: netbase.cpp:38
void prepareForTransport(CSerializedNetMsg &msg, std::vector< unsigned char > &header) override
Definition: net.cpp:772
static constexpr size_t MAX_BLOCK_RELAY_ONLY_ANCHORS
Maximum number of block-relay-only anchor connections.
Definition: net.cpp:54
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:276
bool IsRoutable() const
Definition: netaddress.cpp:490
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
Definition: sock.cpp:311
#define WSAEWOULDBLOCK
Definition: compat.h:46
std::optional< NodeId > SelectNodeToEvict(std::vector< NodeEvictionCandidate > &&vEvictionCandidates)
Select an inbound peer to evict after filtering out (protecting) peers having distinct, difficult-to-forge characteristics.
Definition: net.cpp:980
const std::string NET_MESSAGE_COMMAND_OTHER
Definition: net.cpp:100
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
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
unsigned int GetReceiveFloodSize() const
Definition: net.cpp:2973
Inbound connections are those initiated by a peer.
~CNode()
Definition: net.cpp:3007
void DeleteNode(CNode *pnode)
Definition: net.cpp:2721
RecursiveMutex cs_SubVer
Definition: net.h:436
static constexpr std::chrono::seconds DNSSEEDS_DELAY_FEW_PEERS
How long to delay before querying DNS seeds.
Definition: net.cpp:74
unsigned int SOCKET
Definition: compat.h:41
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
Definition: net.h:1162
const Network m_network
Definition: net.cpp:886
bool CheckIncomingNonce(uint64_t nonce)
Definition: net.cpp:356
static constexpr size_t MESSAGE_START_SIZE
Definition: protocol.h:33
const CAddress addr
Definition: net.h:430
CNode(NodeId id, ServiceFlags nLocalServicesIn, SOCKET hSocketIn, const CAddress &addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const CAddress &addrBindIn, const std::string &addrNameIn, ConnectionType conn_type_in, bool inbound_onion)
Definition: net.cpp:2975
bool Complete() const override
Definition: net.h:355
static const bool DEFAULT_DNSSEED
Definition: net.h:83
bool Match(const CNetAddr &addr) const
CDataStream vRecv
Definition: net.h:326
const int64_t nTimeConnected
Unix epoch time at peer connection, in seconds.
Definition: net.h:427
CMessageHeader hdr
Definition: net.h:325
int flags
Definition: bitcoin-tx.cpp:512
#define X(name)
Definition: net.cpp:568
std::atomic< NodeId > nLastNodeId
Definition: net.h:1070
bool RemoveAddedNode(const std::string &node)
Definition: net.cpp:2797
Network address.
Definition: netaddress.h:121
std::list< CNode * > vNodesDisconnected
Definition: net.h:1068
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type)
Definition: net.cpp:382
256-bit opaque blob.
Definition: uint256.h:124
std::vector< CService > onion_binds
Definition: net.h:770
~CNetCleanup()
Definition: net.cpp:2628
size_t GetNodeCount(ConnectionDirection) const
Definition: net.cpp:2809
bool IsReachable(enum Network net)
Definition: net.cpp:276
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:229
ServiceFlags nServices
Serialized as uint64_t in V1, and as CompactSize in V2.
Definition: protocol.h:451
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
bool ShouldRunInactivityChecks(const CNode &node, std::optional< int64_t > now=std::nullopt) const
Return true if we should disconnect the peer for failing an inactivity check.
Definition: net.cpp:1311
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
Definition: net.h:49
CService proxy
Definition: netbase.h:56
std::string ToString() const
BanMan * m_banman
Pointer to this node&#39;s banman.
Definition: net.h:1132
std::atomic< int64_t > nLastTXTime
UNIX epoch time of the last transaction received from this peer that we had not yet seen (e...
Definition: net.h:571
static const uint64_t SELECT_TIMEOUT_MILLISECONDS
Definition: net.cpp:98
Mutex cs_vRecv
Definition: net.h:414
~CConnman()
Definition: net.cpp:2728
std::thread threadOpenConnections
Definition: net.h:1167
bool AttemptToEvictConnection()
Try to find a connection to evict when the node is full.
Definition: net.cpp:1048
std::string original
Definition: translation.h:17
ConnectionType
Different types of connections to a peer.
Definition: net.h:121
int readHeader(Span< const uint8_t > msg_bytes)
Definition: net.cpp:670
constexpr C * data() const noexcept
Definition: span.h:169
const CChainParams & Params()
Return the currently selected parameters.
CSemaphoreGrant grantOutbound
Definition: net.h:453
bool SetSocketNoDelay(const SOCKET &hSocket)
Set the TCP_NODELAY flag on a socket.
Definition: netbase.cpp:746
const CChainParams & m_chain_params
Definition: net.h:319
size_t size() const EXCLUSIVE_LOCKS_REQUIRED(!cs)
Return the number of (unique) addresses in all tables.
Definition: addrman.h:500
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12
NodeId GetNewNodeId()
Definition: net.cpp:2463
Feeler connections are short-lived connections made to check that a node is alive.
std::vector< AddedNodeInfo > GetAddedNodeInfo() const
Definition: net.cpp:2117
std::string addrLocal
Definition: net.h:267
NetPermissionFlags m_permissionFlags
Definition: net.h:403
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:588
bool fAddressesInitialized
Definition: net.h:1061
std::thread threadDNSAddressSeed
Definition: net.h:1164
int64_t nTimeConnected
Definition: net.h:1203
bool fLogIPs
Definition: logging.cpp:36
int64_t GetAdjustedTime()
Definition: timedata.cpp:34
std::string ToStringIPPort() const
ServiceFlags GetDesirableServiceFlags(ServiceFlags services)
Gets the set of service flags which are "desirable" for a given peer.
Definition: protocol.cpp:127
std::vector< ListenSocket > vhListenSocket
Definition: net.h:1059
std::chrono::seconds GetMaxOutboundTimeframe() const
Definition: net.cpp:2908
#define MSG_DONTWAIT
Definition: compat.h:115
static const uint64_t RANDOMIZER_ID_ADDRCACHE
Definition: net.cpp:104
static uint32_t ReadLE32(const unsigned char *ptr)
Definition: common.h:24
TOR (v2 or v3)
Definition: netaddress.h:57
Mutex cs_vSend
Definition: net.h:412
std::atomic< int64_t > nTimeOffset
Definition: net.h:428
ArgsManager gArgs
Definition: system.cpp:84
bool fListen
Definition: net.cpp:109
std::atomic_bool fSuccessfullyConnected
fSuccessfullyConnected is set to true on receiving VERACK from the peer.
Definition: net.h:449
SipHash-2-4.
Definition: siphash.h:13
static constexpr uint64_t MAX_SIZE
The maximum size of a serialized object in bytes or number of elements (for eg vectors) when the size...
Definition: serialize.h:31
void ThreadMessageHandler()
Definition: net.cpp:2234
static int count
Definition: tests.c:41
These are the default connections that we use to connect with the network.
bool OutboundTargetReached(bool historicalBlockServingLimit) const
check if the outbound target is reached if param historicalBlockServingLimit is set true...
Definition: net.cpp:2927
static constexpr auto FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes.
Definition: net.h:54
void StopNodes()
Definition: net.cpp:2679
std::atomic< int > nVersion
Definition: net.h:435
static void EraseLastKElements(std::vector< T > &elements, Comparator comparator, size_t k, std::function< bool(const NodeEvictionCandidate &)> predicate=[](const NodeEvictionCandidate &n) { return true;})
Sort an array by the specified comparator, then erase the last K elements where predicate is true...
Definition: net.cpp:898
void InterruptSocks5(bool interrupt)
Definition: netbase.cpp:753
unsigned int nSendBufferMaxSize
Definition: net.h:1056
static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL
Run the extra block-relay-only connection loop once every 5 minutes.
Definition: net.h:56
static constexpr std::chrono::minutes DUMP_PEERS_INTERVAL
Definition: net.cpp:60
std::vector< bool > m_asmap
Definition: addrman.h:190
static constexpr size_t HEADER_SIZE
Definition: protocol.h:39
std::string ToString() const
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(cs_mapLocalHost)
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
Definition: netbase.cpp:616
std::atomic< bool > m_bip152_highbandwidth_from
Definition: net.h:529
void ThreadI2PAcceptIncoming()
Definition: net.cpp:2289
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
std::function< std::unique_ptr< Sock >const CService &)> CreateSock
Socket factory.
Definition: netbase.cpp:528
#define WSAEMSGSIZE
Definition: compat.h:48
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
Definition: net.h:47
bool AddConnection(const std::string &address, ConnectionType conn_type)
Attempts to open a connection.
Definition: net.cpp:1213
bool IsBanned(const CNetAddr &net_addr)
Return whether net_addr is banned.
Definition: banman.cpp:75
BindFlags
Used to pass flags to the Bind() function.
Definition: net.cpp:85
bool GenerateSelectSet(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set)
Definition: net.cpp:1348
void AcceptConnection(const ListenSocket &hListenSocket)
Definition: net.cpp:1092
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:92
CClientUIInterface uiInterface
Definition: net.h:191
static bool CompareNetGroupKeyed(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition: net.cpp:846
uint256 Hash(const T &in1)
Compute the 256-bit hash of an object.
Definition: hash.h:75
uint64_t GetMaxOutboundTarget() const
Definition: net.cpp:2902
Information about a peer.
Definition: net.h:394
static CNetCleanup instance_of_cnetcleanup
Definition: net.cpp:2636
void Attempt(const CService &addr, bool fCountFailure, int64_t nTime=GetAdjustedTime()) EXCLUSIVE_LOCKS_REQUIRED(!cs)
Mark an entry as connection attempted to.
Definition: addrman.h:549
bool SetSockAddr(const struct sockaddr *paddr)
Definition: netaddress.cpp:941
std::thread threadSocketHandler
Definition: net.h:1165
Simple class for background tasks that should be run periodically or once "after a while"...
Definition: scheduler.h:33
We use block-relay-only connections to help prevent against partition attacks.
RecursiveMutex cs_totalBytesRecv
Definition: net.h:1039
std::atomic< std::chrono::microseconds > m_last_ping_time
Last measured round-trip time.
Definition: net.h:574
bool SetInternal(const std::string &name)
Create an "internal" address that represents a name or FQDN.
Definition: netaddress.cpp:173
uint64_t nKeyedNetGroup
Definition: net.h:1210
Network ConnectedThroughNetwork() const
Get network the peer connected through.
Definition: net.cpp:562
virtual void InitializeNode(CNode *pnode)=0
Initialize a peer (setup state, queue any initial messages)
std::string GetAddrName() const
Definition: net.cpp:536
RecursiveMutex cs_addrLocal
Definition: net.h:703
bool TryAcquire()
Definition: sync.h:338
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
Definition: net.h:1138
AddrFetch connections are short lived connections used to solicit addresses from peers.
#define LogPrintf(...)
Definition: logging.h:184
void Good(const CService &addr, bool test_before_evict=true, int64_t nTime=GetAdjustedTime()) EXCLUSIVE_LOCKS_REQUIRED(!cs)
Mark an entry as accessible.
Definition: addrman.h:539
std::atomic< std::chrono::microseconds > m_min_ping_time
Lowest measured round-trip time.
Definition: net.h:578
int64_t GetTime()
Return system time (or mocked time, if set)
Definition: time.cpp:26
uint64_t GetTotalBytesSent() const
Definition: net.cpp:2962
CNode * AddRef()
Definition: net.h:624
std::unique_ptr< CSemaphore > semAddnode
Definition: net.h:1115
std::atomic< std::chrono::microseconds > m_next_send_inv_to_incoming
Definition: net.h:1182
std::unique_ptr< Sock > sock
Connected socket.
Definition: i2p.h:33
void Init(const Options &connOptions)
Definition: net.h:781
CThreadInterrupt interruptNet
This is signaled when network activity should cease.
Definition: net.h:1156
unsigned int nHdrPos
Definition: net.h:327
ConnectionDirection
Definition: netbase.h:32
static const int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
Definition: clientversion.h:33
int GetRandInt(int nMax) noexcept
Definition: random.cpp:596
CService peer
The peer&#39;s I2P address.
Definition: i2p.h:39
bool eof() const
Definition: streams.h:356
static bool ReverseCompareNodeMinPingTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition: net.cpp:836
bool IsInboundConn() const
Definition: net.h:495
const uint64_t nSeed1
Definition: net.h:1141
void Stop()
Definition: net.h:814
bool m_use_addrman_outgoing
Definition: net.h:774
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:768
std::atomic< int64_t > nLastBlockTime
UNIX epoch time of the last block received from this peer that we had not yet seen (e...
Definition: net.h:565
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
uint32_t nTime
Always included in serialization, except in the network format on INIT_PROTO_VERSION.
Definition: protocol.h:449
void SplitHostPort(std::string in, uint16_t &portOut, std::string &hostOut)
char pchMessageStart[MESSAGE_START_SIZE]
Definition: protocol.h:54
CHash256 & Write(Span< const unsigned char > input)
Definition: hash.h:37
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:241
bool fRelayTxes
Definition: net.h:244
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0...
Definition: net.h:773
bool fNameLookup
Definition: netbase.cpp:39
void ProtectEvictionCandidatesByRatio(std::vector< NodeEvictionCandidate > &eviction_candidates)
Protect desirable or disadvantaged inbound peers from eviction by ratio.
Definition: net.cpp:907
const char *const ANCHORS_DATABASE_FILENAME
Anchor IP address database file name.
Definition: net.cpp:57
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:564
int64_t nLastBlockTime
Definition: net.h:1205
bool m_use_addrman_outgoing
Definition: net.h:1128
Cache responses to addr requests to minimize privacy leak.
Definition: net.h:1079
virtual bool ProcessMessages(CNode *pnode, std::atomic< bool > &interrupt)=0
Process protocol messages received from a given node.
std::vector< unsigned char > GetAddrBytes() const
Definition: netaddress.cpp:820
int64_t nLastTry
last try whatsoever by us (memory only)
Definition: addrman.h:36
void RemoveLocal(const CService &addr)
Definition: net.cpp:261
NodeId nodeid
Definition: net.h:242
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:301
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: system.h:282
RecursiveMutex cs_totalBytesSent
Definition: net.h:1040
unsigned int nReceiveFloodSize
Definition: net.h:1057
bool fRelevantServices
Definition: net.h:1207
std::unique_ptr< TxRelay > m_tx_relay
Definition: net.h:558
virtual bool SendMessages(CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(pnode -> cs_sendProcessing)=0
Send queued protocol messages to a given node.
CompareNodeNetworkTime(bool is_local, Network network)
Definition: net.cpp:887
Message header.
Definition: protocol.h:30
void ThreadDNSAddressSeed()
Definition: net.cpp:1649
static bool ReverseCompareNodeTimeConnected(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition: net.cpp:841
Addresses from these networks are not publicly routable on the global Internet.
Definition: netaddress.h:48
static const bool DEFAULT_FIXEDSEEDS
Definition: net.h:84