Bitcoin ABC  0.28.12
P2P Digital Currency
net.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2019 The Bitcoin Core developers
3 // Copyright (c) 2017-2019 The Bitcoin developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #ifndef BITCOIN_NET_H
8 #define BITCOIN_NET_H
9 
10 #include <avalanche/proofid.h>
12 #include <bloom.h>
13 #include <chainparams.h>
14 #include <compat.h>
15 #include <consensus/amount.h>
16 #include <crypto/siphash.h>
17 #include <hash.h>
18 #include <i2p.h>
19 #include <kernel/cs_main.h>
20 #include <logging.h>
21 #include <net_permissions.h>
22 #include <netaddress.h>
23 #include <nodeid.h>
24 #include <protocol.h>
25 #include <pubkey.h>
26 #include <radix.h>
27 #include <random.h>
28 #include <span.h>
29 #include <streams.h>
30 #include <sync.h>
31 #include <threadinterrupt.h>
32 #include <uint256.h>
33 #include <util/check.h>
34 #include <util/time.h>
35 
36 #include <atomic>
37 #include <condition_variable>
38 #include <cstdint>
39 #include <deque>
40 #include <functional>
41 #include <list>
42 #include <map>
43 #include <memory>
44 #include <thread>
45 #include <vector>
46 
47 class AddrMan;
48 class BanMan;
49 class Config;
50 class CNode;
51 class CScheduler;
52 struct bilingual_str;
53 
55 static const bool DEFAULT_WHITELISTRELAY = true;
57 static const bool DEFAULT_WHITELISTFORCERELAY = false;
58 
63 static constexpr std::chrono::minutes TIMEOUT_INTERVAL{20};
65 static constexpr auto FEELER_INTERVAL = 2min;
67 static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL = 5min;
69 static const unsigned int MAX_SUBVERSION_LENGTH = 256;
76 static const int MAX_ADDNODE_CONNECTIONS = 8;
78 static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS = 2;
85 static const int MAX_FEELER_CONNECTIONS = 1;
87 static const bool DEFAULT_LISTEN = true;
93 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 4096;
95 static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET = 0;
97 static const bool DEFAULT_BLOCKSONLY = false;
99 static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
101 static const int NUM_FDS_MESSAGE_CAPTURE = 1;
102 
103 static const bool DEFAULT_FORCEDNSSEED = false;
104 static const bool DEFAULT_DNSSEED = true;
105 static const bool DEFAULT_FIXEDSEEDS = true;
106 static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
107 static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
108 
110  std::string strAddedNode;
113  bool fInbound;
114 };
115 
116 struct CNodeStats;
117 class CClientUIInterface;
118 
120  CSerializedNetMsg() = default;
123  // No copying, only moves.
124  CSerializedNetMsg(const CSerializedNetMsg &msg) = delete;
126 
128  CSerializedNetMsg copy;
129  copy.data = data;
130  copy.m_type = m_type;
131  return copy;
132  }
133 
134  std::vector<uint8_t> data;
135  std::string m_type;
136 };
137 
138 const std::vector<std::string> CONNECTION_TYPE_DOC{
139  "outbound-full-relay (default automatic connections)",
140  "block-relay-only (does not relay transactions or addresses)",
141  "inbound (initiated by the peer)",
142  "manual (added via addnode RPC or -addnode/-connect configuration options)",
143  "addr-fetch (short-lived automatic connection for soliciting addresses)",
144  "feeler (short-lived automatic connection for testing addresses)"};
145 
151 enum class ConnectionType {
157  INBOUND,
158 
166 
173  MANUAL,
174 
191  FEELER,
192 
202  BLOCK_RELAY,
203 
210  ADDR_FETCH,
211 
217 };
218 
220 std::string ConnectionTypeAsString(ConnectionType conn_type);
221 
228 void Discover();
229 
230 uint16_t GetListenPort();
231 
232 enum {
233  // unknown
235  // address a local interface listens on
237  // address explicit bound to
239  // address reported by UPnP or NAT-PMP
241  // address explicitly specified (-externalip=)
243 
244  LOCAL_MAX
245 };
246 
247 bool IsPeerAddrLocalGood(CNode *pnode);
249 std::optional<CService> GetLocalAddrForPeer(CNode &node);
250 
255 void SetReachable(enum Network net, bool reachable);
257 bool IsReachable(enum Network net);
259 bool IsReachable(const CNetAddr &addr);
260 
261 bool AddLocal(const CService &addr, int nScore = LOCAL_NONE);
262 bool AddLocal(const CNetAddr &addr, int nScore = LOCAL_NONE);
263 void RemoveLocal(const CService &addr);
264 bool SeenLocal(const CService &addr);
265 bool IsLocal(const CService &addr);
266 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr);
267 CService GetLocalAddress(const CNetAddr &addrPeer);
268 
269 extern bool fDiscover;
270 extern bool fListen;
271 
273  int nScore;
274  uint16_t nPort;
275 };
276 
278 extern std::map<CNetAddr, LocalServiceInfo>
280 
281 extern const std::string NET_MESSAGE_COMMAND_OTHER;
282 // Command, total bytes
283 typedef std::map<std::string, uint64_t> mapMsgCmdSize;
284 
290 struct CNodeStats {
292  std::chrono::seconds m_last_send;
293  std::chrono::seconds m_last_recv;
294  std::chrono::seconds m_last_tx_time;
295  std::chrono::seconds m_last_proof_time;
296  std::chrono::seconds m_last_block_time;
297  std::chrono::seconds m_connected;
298  int64_t nTimeOffset;
299  std::string m_addr_name;
300  int nVersion;
301  std::string cleanSubVer;
302  bool fInbound;
306  uint64_t nSendBytes;
308  uint64_t nRecvBytes;
311  std::chrono::microseconds m_last_ping_time;
312  std::chrono::microseconds m_min_ping_time;
313  // Our address, as reported by the peer
314  std::string addrLocal;
315  // Address of this peer
317  // Bind address of our side of the connection
319  // Network the peer connected through
321  uint32_t m_mapped_as;
323  std::optional<double> m_availabilityScore;
324 };
325 
331 class CNetMessage {
332 public:
336  std::chrono::microseconds m_time{0};
337  bool m_valid_netmagic = false;
338  bool m_valid_header = false;
339  bool m_valid_checksum = false;
341  uint32_t m_message_size{0};
343  uint32_t m_raw_message_size{0};
344  std::string m_type;
345 
346  CNetMessage(CDataStream &&recv_in) : m_recv(std::move(recv_in)) {}
347 
348  void SetVersion(int nVersionIn) { m_recv.SetVersion(nVersionIn); }
349 };
350 
357 public:
358  // returns true if the current deserialization is complete
359  virtual bool Complete() const = 0;
360  // set the serialization context version
361  virtual void SetVersion(int version) = 0;
363  virtual int Read(const Config &config, Span<const uint8_t> &msg_bytes) = 0;
364  // decomposes a message from the context
365  virtual CNetMessage GetMessage(const Config &config,
366  std::chrono::microseconds time) = 0;
368 };
369 
371 private:
372  mutable CHash256 hasher;
374 
375  // Parsing header (false) or data (true)
376  bool in_data;
377  // Partially received header.
379  // Complete header.
381  // Received message data.
383  uint32_t nHdrPos;
384  uint32_t nDataPos;
385 
386  const uint256 &GetMessageHash() const;
387  int readHeader(const Config &config, Span<const uint8_t> msg_bytes);
388  int readData(Span<const uint8_t> msg_bytes);
389 
390  void Reset() {
391  vRecv.clear();
392  hdrbuf.clear();
393  hdrbuf.resize(24);
394  in_data = false;
395  nHdrPos = 0;
396  nDataPos = 0;
397  data_hash.SetNull();
398  hasher.Reset();
399  }
400 
401 public:
403  const CMessageHeader::MessageMagic &pchMessageStartIn, int nTypeIn,
404  int nVersionIn)
405  : hdrbuf(nTypeIn, nVersionIn), hdr(pchMessageStartIn),
406  vRecv(nTypeIn, nVersionIn) {
407  Reset();
408  }
409 
410  bool Complete() const override {
411  if (!in_data) {
412  return false;
413  }
414 
415  return (hdr.nMessageSize == nDataPos);
416  }
417 
418  void SetVersion(int nVersionIn) override {
419  hdrbuf.SetVersion(nVersionIn);
420  vRecv.SetVersion(nVersionIn);
421  }
422  int Read(const Config &config, Span<const uint8_t> &msg_bytes) override {
423  int ret = in_data ? readData(msg_bytes) : readHeader(config, msg_bytes);
424  if (ret < 0) {
425  Reset();
426  } else {
427  msg_bytes = msg_bytes.subspan(ret);
428  }
429  return ret;
430  }
431 
432  CNetMessage GetMessage(const Config &config,
433  std::chrono::microseconds time) override;
434 };
435 
440 public:
441  // prepare message for transport (header construction, error-correction
442  // computation, payload encryption, etc.)
443  virtual void prepareForTransport(const Config &config,
444  CSerializedNetMsg &msg,
445  std::vector<uint8_t> &header) = 0;
446  virtual ~TransportSerializer() {}
447 };
448 
450 public:
451  void prepareForTransport(const Config &config, CSerializedNetMsg &msg,
452  std::vector<uint8_t> &header) override;
453 };
454 
456 class CNode {
457  friend class CConnman;
458  friend struct ConnmanTestMsg;
459 
460 public:
461  std::unique_ptr<TransportDeserializer> m_deserializer;
462  std::unique_ptr<TransportSerializer> m_serializer;
463 
464  // socket
467  size_t nSendSize GUARDED_BY(cs_vSend){0};
469  size_t nSendOffset GUARDED_BY(cs_vSend){0};
470  uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
471  std::deque<std::vector<uint8_t>> vSendMsg GUARDED_BY(cs_vSend);
475 
477  std::list<CNetMessage> vProcessMsg GUARDED_BY(cs_vProcessMsg);
478  size_t nProcessQueueSize{0};
479 
480  uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
481 
482  std::atomic<std::chrono::seconds> m_last_send{0s};
483  std::atomic<std::chrono::seconds> m_last_recv{0s};
485  const std::chrono::seconds m_connected;
486  std::atomic<int64_t> nTimeOffset{0};
487  // Address of this peer
488  const CAddress addr;
489  // Bind address of our side of the connection
491  const std::string m_addr_name;
494  const bool m_inbound_onion;
495  std::atomic<int> nVersion{0};
496  // The nonce provided by the remote host.
497  uint64_t nRemoteHostNonce{0};
498  // The extra entropy provided by the remote host.
499  uint64_t nRemoteExtraEntropy{0};
505  std::string cleanSubVer GUARDED_BY(m_subver_mutex){};
506  // This peer is preferred for eviction.
507  bool m_prefer_evict{false};
508  bool HasPermission(NetPermissionFlags permission) const {
509  return NetPermissions::HasFlag(m_permissionFlags, permission);
510  }
511  std::atomic_bool fSuccessfullyConnected{false};
512  // Setting fDisconnect to true will cause the node to be disconnected the
513  // next time DisconnectNodes() runs
514  std::atomic_bool fDisconnect{false};
516  std::atomic<int> nRefCount{0};
517 
518  const uint64_t nKeyedNetGroup;
519  std::atomic_bool fPauseRecv{false};
520  std::atomic_bool fPauseSend{false};
521 
523  switch (m_conn_type) {
527  return true;
532  return false;
533  } // no default case, so the compiler can warn about missing cases
534 
535  assert(false);
536  }
537 
538  bool IsFullOutboundConn() const {
541  }
542 
543  bool IsManualConn() const { return m_conn_type == ConnectionType::MANUAL; }
544 
545  bool IsBlockOnlyConn() const {
547  }
548 
549  bool IsFeelerConn() const { return m_conn_type == ConnectionType::FEELER; }
550 
551  bool IsAddrFetchConn() const {
553  }
554 
555  bool IsInboundConn() const {
557  }
558 
561  }
562 
563  bool ExpectServicesFromConn() const {
564  switch (m_conn_type) {
568  return false;
573  return true;
574  } // no default case, so the compiler can warn about missing cases
575 
576  assert(false);
577  }
578 
591 
592  // We selected peer as (compact blocks) high-bandwidth peer (BIP152)
593  std::atomic<bool> m_bip152_highbandwidth_to{false};
594  // Peer selected us as (compact blocks) high-bandwidth peer (BIP152)
595  std::atomic<bool> m_bip152_highbandwidth_from{false};
596 
601  std::atomic_bool m_has_all_wanted_services{false};
602 
609  std::atomic_bool m_relays_txs{false};
610 
615  std::atomic_bool m_bloom_filter_loaded{false};
616 
617  // True if we know this peer is using Avalanche (at least polling)
618  std::atomic<bool> m_avalanche_enabled{false};
619 
621  // Pubkey used to verify signatures on Avalanche messages from this peer
622  std::optional<CPubKey> m_avalanche_pubkey GUARDED_BY(cs_avalanche_pubkey);
623 
625  void invsPolled(uint32_t count);
626 
628  void invsVoted(uint32_t count);
629 
646  void updateAvailabilityScore(double decayFactor);
647  double getAvailabilityScore() const;
648 
649  // Store the next time we will consider a getavaaddr message from this peer
650  std::chrono::seconds m_nextGetAvaAddr{0};
651 
652  // The last time the node sent us a faulty message
653  std::atomic<std::chrono::seconds> m_avalanche_last_message_fault{0s};
654  // How much faulty messages did this node accumulate
656 
658 
666  std::atomic<std::chrono::seconds> m_last_block_time{0s};
667 
674  std::atomic<std::chrono::seconds> m_last_tx_time{0s};
675 
682  std::atomic<std::chrono::seconds> m_last_proof_time{0s};
683 
685  std::atomic<std::chrono::microseconds> m_last_ping_time{0us};
686 
691  std::atomic<std::chrono::microseconds> m_min_ping_time{
692  std::chrono::microseconds::max()};
693 
694  CNode(NodeId id, SOCKET hSocketIn, const CAddress &addrIn,
695  uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn,
696  uint64_t nLocalExtraEntropyIn, const CAddress &addrBindIn,
697  const std::string &addrNameIn, ConnectionType conn_type_in,
698  bool inbound_onion);
699  ~CNode();
700  CNode(const CNode &) = delete;
701  CNode &operator=(const CNode &) = delete;
702 
707  void PongReceived(std::chrono::microseconds ping_time) {
708  m_last_ping_time = ping_time;
709  m_min_ping_time = std::min(m_min_ping_time.load(), ping_time);
710  }
711 
712  NodeId GetId() const { return id; }
713 
714  uint64_t GetLocalNonce() const { return nLocalHostNonce; }
715  uint64_t GetLocalExtraEntropy() const { return nLocalExtraEntropy; }
716 
717  int GetRefCount() const {
718  assert(nRefCount >= 0);
719  return nRefCount;
720  }
721 
731  bool ReceiveMsgBytes(const Config &config, Span<const uint8_t> msg_bytes,
732  bool &complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv);
733 
734  void SetCommonVersion(int greatest_common_version) {
736  m_greatest_common_version = greatest_common_version;
737  }
739 
742  void SetAddrLocal(const CService &addrLocalIn)
744 
746  nRefCount++;
747  return this;
748  }
749 
750  void Release() { nRefCount--; }
751 
753 
754  void copyStats(CNodeStats &stats)
757 
758  std::string ConnectionTypeAsString() const {
760  }
761 
762 private:
763  const NodeId id;
764  const uint64_t nLocalHostNonce;
765  const uint64_t nLocalExtraEntropy;
768 
770  // Used only by SocketHandler thread
771  std::list<CNetMessage> vRecvMsg;
772 
773  // Our address, as reported by the peer
776 
782  std::atomic<uint64_t> invCounters{0};
783 
785  std::atomic<double> availabilityScore{0.};
786 
787  mapMsgCmdSize mapSendBytesPerMsgCmd GUARDED_BY(cs_vSend);
788  mapMsgCmdSize mapRecvBytesPerMsgCmd GUARDED_BY(cs_vRecv);
789 };
790 
795 public:
800 
802  virtual void InitializeNode(const Config &config, CNode &node,
803  ServiceFlags our_services) = 0;
804 
806  virtual void FinalizeNode(const Config &config, const CNode &node) = 0;
807 
817  virtual bool ProcessMessages(const Config &config, CNode *pnode,
818  std::atomic<bool> &interrupt)
820 
828  virtual bool SendMessages(const Config &config, CNode *pnode)
830 
831 protected:
837  ~NetEventsInterface() = default;
838 };
839 
840 namespace {
841 struct CConnmanTest;
842 }
843 
844 class NetEventsInterface;
845 class CConnman {
846 public:
849  CONNECTIONS_IN = (1U << 0),
850  CONNECTIONS_OUT = (1U << 1),
852  };
853 
854  struct Options {
860  int nMaxAddnode = 0;
861  int nMaxFeeler = 0;
863  std::vector<NetEventsInterface *> m_msgproc;
864  BanMan *m_banman = nullptr;
865  unsigned int nSendBufferMaxSize = 0;
866  unsigned int nReceiveFloodSize = 0;
867  uint64_t nMaxOutboundLimit = 0;
869  std::vector<std::string> vSeedNodes;
870  std::vector<NetWhitelistPermissions> vWhitelistedRange;
871  std::vector<NetWhitebindPermissions> vWhiteBinds;
872  std::vector<CService> vBinds;
873  std::vector<CService> onion_binds;
878  std::vector<std::string> m_specified_outgoing;
879  std::vector<std::string> m_added_nodes;
881  };
882 
883  void Init(const Options &connOptions)
885  nLocalServices = connOptions.nLocalServices;
886  nMaxConnections = connOptions.nMaxConnections;
887  m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
888  nMaxAddnode = connOptions.nMaxAddnode;
889  nMaxFeeler = connOptions.nMaxFeeler;
890  {
891  // Lock cs_main to prevent a potential race with the peer validation
892  // logic thread.
893  LOCK(::cs_main);
895  std::min(connOptions.m_max_outbound_full_relay,
896  connOptions.nMaxConnections);
897  m_max_avalanche_outbound = connOptions.m_max_avalanche_outbound;
898  m_max_outbound_block_relay = connOptions.m_max_outbound_block_relay;
902  }
903  m_client_interface = connOptions.uiInterface;
904  m_banman = connOptions.m_banman;
905  m_msgproc = connOptions.m_msgproc;
906  nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
907  nReceiveFloodSize = connOptions.nReceiveFloodSize;
909  std::chrono::seconds{connOptions.m_peer_connect_timeout};
910  {
912  nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
913  }
914  vWhitelistedRange = connOptions.vWhitelistedRange;
915  {
917  m_added_nodes = connOptions.m_added_nodes;
918  }
919  m_onion_binds = connOptions.onion_binds;
920  }
921 
922  CConnman(const Config &configIn, uint64_t seed0, uint64_t seed1,
923  AddrMan &addrmanIn, bool network_active = true);
924  ~CConnman();
925 
926  bool Start(CScheduler &scheduler, const Options &options)
929 
930  void StopThreads();
931  void StopNodes();
932  void Stop() {
933  StopThreads();
934  StopNodes();
935  };
936 
938  bool GetNetworkActive() const { return fNetworkActive; };
940  void SetNetworkActive(bool active);
941  void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure,
942  CSemaphoreGrant *grantOutbound,
943  const char *strDest, ConnectionType conn_type);
944  bool CheckIncomingNonce(uint64_t nonce);
945 
946  bool ForNode(NodeId id, std::function<bool(CNode *pnode)> func);
947 
948  void PushMessage(CNode *pnode, CSerializedNetMsg &&msg);
949 
950  using NodeFn = std::function<void(CNode *)>;
951  void ForEachNode(const NodeFn &func) {
953  for (auto &&node : m_nodes) {
954  if (NodeFullyConnected(node)) {
955  func(node);
956  }
957  }
958  };
959 
960  void ForEachNode(const NodeFn &func) const {
962  for (auto &&node : m_nodes) {
963  if (NodeFullyConnected(node)) {
964  func(node);
965  }
966  }
967  };
968 
969  // Addrman functions
980  std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct,
981  std::optional<Network> network) const;
988  std::vector<CAddress> GetAddresses(CNode &requestor, size_t max_addresses,
989  size_t max_pct);
990 
991  // This allows temporarily exceeding m_max_outbound_full_relay, with the
992  // goal of finding a peer that is better than all our current peers.
993  void SetTryNewOutboundPeer(bool flag);
994  bool GetTryNewOutboundPeer() const;
995 
997  LogPrint(BCLog::NET, "net: enabling extra block-relay-only peers\n");
999  }
1000 
1001  // Return the number of outbound peers we have in excess of our target (eg,
1002  // if we previously called SetTryNewOutboundPeer(true), and have since set
1003  // to false, we may have extra peers that we wish to disconnect). This may
1004  // return a value less than (num_outbound_connections - num_outbound_slots)
1005  // in cases where some outbound connections are not yet fully connected, or
1006  // not yet fully disconnected.
1007  int GetExtraFullOutboundCount() const;
1008  // Count the number of block-relay-only peers we have over our limit.
1009  int GetExtraBlockRelayCount() const;
1010 
1011  bool AddNode(const std::string &node)
1013  bool RemoveAddedNode(const std::string &node)
1015  std::vector<AddedNodeInfo> GetAddedNodeInfo() const
1017 
1032  bool AddConnection(const std::string &address, ConnectionType conn_type);
1033 
1034  size_t GetNodeCount(NumConnections num) const;
1035  void GetNodeStats(std::vector<CNodeStats> &vstats) const;
1036  bool DisconnectNode(const std::string &node);
1037  bool DisconnectNode(const CSubNet &subnet);
1038  bool DisconnectNode(const CNetAddr &addr);
1039  bool DisconnectNode(NodeId id);
1040 
1048 
1049  uint64_t GetMaxOutboundTarget() const;
1050  std::chrono::seconds GetMaxOutboundTimeframe() const;
1051 
1055  bool OutboundTargetReached(bool historicalBlockServingLimit) const;
1056 
1059  uint64_t GetOutboundTargetBytesLeft() const;
1060 
1063  std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const;
1064 
1065  uint64_t GetTotalBytesRecv() const;
1066  uint64_t GetTotalBytesSent() const;
1067 
1069  CSipHasher GetDeterministicRandomizer(uint64_t id) const;
1070 
1071  unsigned int GetReceiveFloodSize() const;
1072 
1074 
1079  bool ShouldRunInactivityChecks(const CNode &node,
1080  std::chrono::seconds now) const;
1081 
1082 private:
1083  struct ListenSocket {
1084  public:
1087  NetPermissions::AddFlag(flags, m_permissions);
1088  }
1089  ListenSocket(SOCKET socket_, NetPermissionFlags permissions_)
1090  : socket(socket_), m_permissions(permissions_) {}
1091 
1092  private:
1094  };
1095 
1096  bool BindListenPort(const CService &bindAddr, bilingual_str &strError,
1097  NetPermissionFlags permissions);
1098  bool Bind(const CService &addr, unsigned int flags,
1099  NetPermissionFlags permissions);
1100  bool InitBinds(const Options &options);
1101 
1104  void AddAddrFetch(const std::string &strDest)
1107  void
1108  ThreadOpenConnections(std::vector<std::string> connect,
1109  std::function<void(const CAddress &, ConnectionType)>
1110  mockOpenConnection)
1114  void ThreadI2PAcceptIncoming();
1115  void AcceptConnection(const ListenSocket &hListenSocket);
1116 
1125  void CreateNodeFromAcceptedSocket(SOCKET hSocket,
1126  NetPermissionFlags permissionFlags,
1127  const CAddress &addr_bind,
1128  const CAddress &addr);
1129 
1130  void DisconnectNodes();
1133  bool InactivityCheck(const CNode &node) const;
1134  bool GenerateSelectSet(std::set<SOCKET> &recv_set,
1135  std::set<SOCKET> &send_set,
1136  std::set<SOCKET> &error_set);
1137  void SocketEvents(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set,
1138  std::set<SOCKET> &error_set);
1141  void ThreadDNSAddressSeed()
1143 
1144  uint64_t CalculateKeyedNetGroup(const CAddress &ad) const;
1145 
1146  CNode *FindNode(const CNetAddr &ip);
1147  CNode *FindNode(const CSubNet &subNet);
1148  CNode *FindNode(const std::string &addrName);
1149  CNode *FindNode(const CService &addr);
1150 
1155  bool AlreadyConnectedToAddress(const CAddress &addr);
1156 
1157  bool AttemptToEvictConnection();
1158  CNode *ConnectNode(CAddress addrConnect, const char *pszDest,
1159  bool fCountFailure, ConnectionType conn_type);
1161  const CNetAddr &addr) const;
1162 
1163  void DeleteNode(CNode *pnode);
1164 
1165  NodeId GetNewNodeId();
1166 
1167  size_t SocketSendData(CNode &node) const
1168  EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend);
1169  void DumpAddresses();
1170 
1171  // Network stats
1172  void RecordBytesRecv(uint64_t bytes);
1173  void RecordBytesSent(uint64_t bytes);
1174 
1178  std::vector<CAddress> GetCurrentBlockRelayOnlyConns() const;
1179 
1180  // Whether the node should be passed out in ForEach* callbacks
1181  static bool NodeFullyConnected(const CNode *pnode);
1182 
1183  const Config *config;
1184 
1185  // Network usage totals
1187  std::atomic<uint64_t> nTotalBytesRecv{0};
1188  uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent){0};
1189 
1190  // outbound limit & stats
1191  uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent){0};
1192  std::chrono::seconds
1193  nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent){0};
1194  uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent);
1195 
1196  // P2P timeout in seconds
1197  std::chrono::seconds m_peer_connect_timeout;
1198 
1199  // Whitelisted ranges. Any node connecting from these is automatically
1200  // whitelisted (as well as those connecting to whitelisted binds).
1201  std::vector<NetWhitelistPermissions> vWhitelistedRange;
1202 
1203  unsigned int nSendBufferMaxSize{0};
1204  unsigned int nReceiveFloodSize{0};
1205 
1206  std::vector<ListenSocket> vhListenSocket;
1207  std::atomic<bool> fNetworkActive{true};
1210  std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
1212  std::vector<std::string> m_added_nodes GUARDED_BY(m_added_nodes_mutex);
1214  std::vector<CNode *> m_nodes GUARDED_BY(m_nodes_mutex);
1215  std::list<CNode *> m_nodes_disconnected;
1217  std::atomic<NodeId> nLastNodeId{0};
1218  unsigned int nPrevNodeCount{0};
1219 
1227  std::vector<CAddress> m_addrs_response_cache;
1228  std::chrono::microseconds m_cache_entry_expiration{0};
1229  };
1230 
1245  std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
1246 
1258 
1259  std::unique_ptr<CSemaphore> semOutbound;
1260  std::unique_ptr<CSemaphore> semAddnode;
1262 
1263  // How many full-relay (tx, block, addr) outbound peers we want
1265 
1266  // How many block-relay only outbound peers we want
1267  // We do not relay tx or addr messages with these peers
1269 
1270  // How many avalanche enabled outbound peers we want
1272 
1278  // FIXME m_msgproc is a terrible name
1279  std::vector<NetEventsInterface *> m_msgproc;
1285 
1290  std::vector<CAddress> m_anchors;
1291 
1293  const uint64_t nSeed0, nSeed1;
1294 
1296  bool fMsgProcWake GUARDED_BY(mutexMsgProc);
1297 
1298  std::condition_variable condMsgProc;
1300  std::atomic<bool> flagInterruptMsgProc{false};
1301 
1309 
1314  std::unique_ptr<i2p::sam::Session> m_i2p_sam_session;
1315 
1317  std::thread threadSocketHandler;
1322 
1328 
1334  std::atomic_bool m_start_extra_block_relay_peers{false};
1335 
1340  std::vector<CService> m_onion_binds;
1341 
1342  friend struct ::CConnmanTest;
1343  friend struct ConnmanTestMsg;
1344 };
1345 
1346 std::string getSubVersionEB(uint64_t MaxBlockSize);
1347 std::string userAgent(const Config &config);
1348 
1350 void CaptureMessageToFile(const CAddress &addr, const std::string &msg_type,
1351  Span<const uint8_t> data, bool is_incoming);
1352 
1356 extern std::function<void(const CAddress &addr, const std::string &msg_type,
1357  Span<const uint8_t> data, bool is_incoming)>
1359 
1362  std::chrono::seconds m_connected;
1363  std::chrono::microseconds m_min_ping_time;
1364  std::chrono::seconds m_last_block_time;
1365  std::chrono::seconds m_last_proof_time;
1366  std::chrono::seconds m_last_tx_time;
1370  uint64_t nKeyedNetGroup;
1375 };
1376 
1384 [[nodiscard]] std::optional<NodeId>
1385 SelectNodeToEvict(std::vector<NodeEvictionCandidate> &&vEvictionCandidates);
1386 
1410  std::vector<NodeEvictionCandidate> &vEvictionCandidates);
1411 
1412 #endif // BITCOIN_NET_H
int flags
Definition: bitcoin-tx.cpp:533
#define Assume(val)
Assume is the identity function.
Definition: check.h:97
Stochastic address manager.
Definition: addrman.h:69
Definition: banman.h:58
A CService with information about it as peer.
Definition: protocol.h:442
Signals for UI communication.
Definition: ui_interface.h:24
Definition: net.h:845
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 m_nodes membe...
Definition: net.cpp:1291
std::condition_variable condMsgProc
Definition: net.h:1298
size_t GetNodeCount(NumConnections num) const
Definition: net.cpp:3249
uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1188
std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1193
std::thread threadMessageHandler
Definition: net.h:1320
void ForEachNode(const NodeFn &func)
Definition: net.h:951
std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const
returns the time in second left in the current max outbound cycle in case of no limit,...
Definition: net.cpp:3351
bool OutboundTargetReached(bool historicalBlockServingLimit) const
check if the outbound target is reached.
Definition: net.cpp:3367
CClientUIInterface * m_client_interface
Definition: net.h:1277
size_t SocketSendData(CNode &node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend)
Definition: net.cpp:822
void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:2610
void ForEachNode(const NodeFn &func) const
Definition: net.h:960
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:3539
bool AddConnection(const std::string &address, ConnectionType conn_type)
Attempts to open a connection.
Definition: net.cpp:1414
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type)
Definition: net.cpp:422
void DeleteNode(CNode *pnode)
Definition: net.cpp:3145
bool RemoveAddedNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:3237
bool AttemptToEvictConnection()
Try to find a connection to evict when the node is full.
Definition: net.cpp:1209
bool GetNetworkActive() const
Definition: net.h:938
bool AlreadyConnectedToAddress(const CAddress &addr)
Determine whether we're already connected to a given address, in order to avoid initiating duplicate ...
Definition: net.cpp:390
int m_max_outbound
Definition: net.h:1275
ServiceFlags nLocalServices
Services this node offers.
Definition: net.h:1257
bool GetTryNewOutboundPeer() const
Definition: net.cpp:2069
void Stop()
Definition: net.h:932
int m_max_outbound_block_relay
Definition: net.h:1268
std::thread threadI2PAcceptIncoming
Definition: net.h:1321
void SetTryNewOutboundPeer(bool flag)
Definition: net.cpp:2073
std::atomic< bool > flagInterruptMsgProc
Definition: net.h:1300
unsigned int GetReceiveFloodSize() const
Definition: net.cpp:3414
void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2529
void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:3056
void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:1907
void SocketEvents(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set)
Definition: net.cpp:1677
NodeId GetNewNodeId()
Definition: net.cpp:2867
CThreadInterrupt interruptNet
This is signaled when network activity should cease.
Definition: net.h:1308
std::unique_ptr< CSemaphore > semAddnode
Definition: net.h:1260
bool Start(CScheduler &scheduler, const Options &options) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition: net.cpp:2920
std::atomic< NodeId > nLastNodeId
Definition: net.h:1217
void RecordBytesSent(uint64_t bytes)
Definition: net.cpp:3327
bool fMsgProcWake GUARDED_BY(mutexMsgProc)
flag for waking the message processor.
std::vector< std::string > m_added_nodes GUARDED_BY(m_added_nodes_mutex)
int GetExtraBlockRelayCount() const
Definition: net.cpp:2101
void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:1899
BanMan * m_banman
Pointer to this node's banman.
Definition: net.h:1284
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:3390
std::thread threadDNSAddressSeed
Definition: net.h:1316
void ThreadI2PAcceptIncoming()
Definition: net.cpp:2676
const uint64_t nSeed1
Definition: net.h:1293
void StartExtraBlockRelayPeers()
Definition: net.h:996
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
Definition: net.h:1290
std::chrono::seconds GetMaxOutboundTimeframe() const
Definition: net.cpp:3347
friend struct ConnmanTestMsg
Definition: net.h:1343
unsigned int nPrevNodeCount
Definition: net.h:1218
void NotifyNumConnectionsChanged()
Definition: net.cpp:1513
ServiceFlags GetLocalServices() const
Used to convey which local services we are offering peers during node connection.
Definition: net.cpp:3410
bool DisconnectNode(const std::string &node)
Definition: net.cpp:3278
std::chrono::seconds m_peer_connect_timeout
Definition: net.h:1197
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.
Definition: net.h:1327
bool InitBinds(const Options &options)
Definition: net.cpp:2893
void AddAddrFetch(const std::string &strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex)
Definition: net.cpp:131
uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1191
std::vector< ListenSocket > vhListenSocket
Definition: net.h:1206
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const
Return vector of current BLOCK_RELAY peers.
Definition: net.cpp:2460
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition: net.cpp:3551
uint64_t GetMaxOutboundTarget() const
Definition: net.cpp:3342
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:1259
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:1201
RecursiveMutex cs_totalBytesSent
Definition: net.h:1186
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
Definition: net.cpp:2871
std::thread threadOpenConnections
Definition: net.h:1319
NumConnections
Definition: net.h:847
@ CONNECTIONS_IN
Definition: net.h:849
@ CONNECTIONS_NONE
Definition: net.h:848
@ CONNECTIONS_ALL
Definition: net.h:851
@ CONNECTIONS_OUT
Definition: net.h:850
Mutex m_addr_fetches_mutex
Definition: net.h:1211
bool InactivityCheck(const CNode &node) const
Return true if the peer is inactive and should be disconnected.
Definition: net.cpp:1532
CNode * FindNode(const CNetAddr &ip)
Definition: net.cpp:350
void GetNodeStats(std::vector< CNodeStats > &vstats) const
Definition: net.cpp:3267
std::vector< AddedNodeInfo > GetAddedNodeInfo() const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2472
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition: net.h:1293
unsigned int nReceiveFloodSize
Definition: net.h:1204
int GetExtraFullOutboundCount() const
Definition: net.cpp:2085
uint64_t GetTotalBytesRecv() const
Definition: net.cpp:3401
RecursiveMutex m_nodes_mutex
Definition: net.h:1216
static bool NodeFullyConnected(const CNode *pnode)
Definition: net.cpp:3490
void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex)
Definition: net.cpp:2051
int nMaxConnections
Definition: net.h:1261
CConnman(const Config &configIn, uint64_t seed0, uint64_t seed1, AddrMan &addrmanIn, bool network_active=true)
Definition: net.cpp:2856
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:3159
std::deque< std::string > m_addr_fetches GUARDED_BY(m_addr_fetches_mutex)
std::function< void(CNode *)> NodeFn
Definition: net.h:950
void SetNetworkActive(bool active)
Definition: net.cpp:2842
std::list< CNode * > m_nodes_disconnected
Definition: net.h:1215
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *strDest, ConnectionType conn_type)
Definition: net.cpp:2561
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, const CNetAddr &addr) const
Definition: net.cpp:566
bool GenerateSelectSet(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set)
Definition: net.cpp:1572
AddrMan & addrman
Definition: net.h:1209
void SocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:1760
uint64_t CalculateKeyedNetGroup(const CAddress &ad) const
Definition: net.cpp:3555
Mutex mutexMsgProc
Definition: net.h:1299
bool fAddressesInitialized
Definition: net.h:1208
~CConnman()
Definition: net.cpp:3153
void StopThreads()
Definition: net.cpp:3079
bool AddNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:3225
std::thread threadOpenAddedConnections
Definition: net.h:1318
Mutex m_added_nodes_mutex
Definition: net.h:1213
std::vector< CNode * > m_nodes GUARDED_BY(m_nodes_mutex)
const Config * config
Definition: net.h:1183
void Init(const Options &connOptions) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.h:883
bool CheckIncomingNonce(uint64_t nonce)
Definition: net.cpp:395
int m_max_outbound_full_relay
Definition: net.h:1264
int nMaxAddnode
Definition: net.h:1273
void RecordBytesRecv(uint64_t bytes)
Definition: net.cpp:3323
bool ShouldRunInactivityChecks(const CNode &node, std::chrono::seconds now) const
Return true if we should disconnect the peer for failing an inactivity check.
Definition: net.cpp:1527
void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:1891
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
Definition: net.cpp:3494
void StopNodes()
Definition: net.cpp:3100
bool GetUseAddrmanOutgoing() const
Definition: net.h:939
unsigned int nSendBufferMaxSize
Definition: net.h:1203
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
Definition: net.h:1314
bool m_use_addrman_outgoing
Definition: net.h:1276
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:1245
uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent)
std::atomic< uint64_t > nTotalBytesRecv
Definition: net.h:1187
std::atomic< bool > fNetworkActive
Definition: net.h:1207
std::atomic_bool m_start_extra_block_relay_peers
flag for initiating extra block-relay-only peer connections.
Definition: net.h:1334
void DisconnectNodes()
Definition: net.cpp:1463
void DumpAddresses()
Definition: net.cpp:2042
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:1340
int nMaxFeeler
Definition: net.h:1274
std::vector< NetEventsInterface * > m_msgproc
Definition: net.h:1279
std::thread threadSocketHandler
Definition: net.h:1317
uint64_t GetTotalBytesSent() const
Definition: net.cpp:3405
void ThreadOpenConnections(std::vector< std::string > connect, std::function< void(const CAddress &, ConnectionType)> mockOpenConnection) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:2115
void AcceptConnection(const ListenSocket &hListenSocket)
Definition: net.cpp:1263
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
Definition: net.cpp:2714
int m_max_avalanche_outbound
Definition: net.h:1271
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:199
void SetVersion(int n)
Definition: streams.h:355
void resize(size_type n, value_type c=0)
Definition: streams.h:248
void clear()
Definition: streams.h:254
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
Definition: hash.h:22
CHash256 & Reset()
Definition: hash.h:41
Message header.
Definition: protocol.h:34
uint32_t nMessageSize
Definition: protocol.h:71
std::array< uint8_t, MESSAGE_START_SIZE > MessageMagic
Definition: protocol.h:46
Network address.
Definition: netaddress.h:121
Transport protocol agnostic message container.
Definition: net.h:331
CNetMessage(CDataStream &&recv_in)
Definition: net.h:346
uint32_t m_message_size
size of the payload
Definition: net.h:341
std::chrono::microseconds m_time
time of message receipt
Definition: net.h:336
CDataStream m_recv
received message data
Definition: net.h:334
void SetVersion(int nVersionIn)
Definition: net.h:348
uint32_t m_raw_message_size
used wire size of the message (including header/checksum)
Definition: net.h:343
std::string m_type
Definition: net.h:344
bool m_valid_checksum
Definition: net.h:339
bool m_valid_header
Definition: net.h:338
bool m_valid_netmagic
Definition: net.h:337
Information about a peer.
Definition: net.h:456
RecursiveMutex cs_vProcessMsg
Definition: net.h:476
Mutex cs_avalanche_pubkey
Definition: net.h:620
const CAddress addrBind
Definition: net.h:490
bool IsFeelerConn() const
Definition: net.h:549
mapMsgCmdSize mapSendBytesPerMsgCmd GUARDED_BY(cs_vSend)
const std::chrono::seconds m_connected
Unix epoch time at peer connection.
Definition: net.h:485
bool ExpectServicesFromConn() const
Definition: net.h:563
bool m_prefer_evict
Definition: net.h:507
std::atomic< int > nVersion
Definition: net.h:495
std::atomic_bool m_has_all_wanted_services
Whether this peer provides all services that we want.
Definition: net.h:601
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Definition: net.h:480
std::atomic< double > availabilityScore
The last computed score.
Definition: net.h:785
bool IsInboundConn() const
Definition: net.h:555
bool HasPermission(NetPermissionFlags permission) const
Definition: net.h:508
std::atomic_bool fPauseRecv
Definition: net.h:519
bool IsOutboundOrBlockRelayConn() const
Definition: net.h:522
NodeId GetId() const
Definition: net.h:712
bool IsManualConn() const
Definition: net.h:543
std::atomic< int64_t > nTimeOffset
Definition: net.h:486
const std::string m_addr_name
Definition: net.h:491
mapMsgCmdSize mapRecvBytesPerMsgCmd GUARDED_BY(cs_vRecv)
std::string ConnectionTypeAsString() const
Definition: net.h:758
std::deque< std::vector< uint8_t > > vSendMsg GUARDED_BY(cs_vSend)
void SetCommonVersion(int greatest_common_version)
Definition: net.h:734
std::atomic< bool > m_bip152_highbandwidth_to
Definition: net.h:593
std::list< CNetMessage > vRecvMsg
Definition: net.h:771
size_t nProcessQueueSize
Definition: net.h:478
std::atomic_bool m_relays_txs
Whether we should relay transactions to this peer (their version message did not include fRelay=false...
Definition: net.h:609
std::atomic< bool > m_bip152_highbandwidth_from
Definition: net.h:595
void PongReceived(std::chrono::microseconds ping_time)
A ping-pong round trip has completed successfully.
Definition: net.h:707
std::atomic_bool fSuccessfullyConnected
Definition: net.h:511
bool IsAddrFetchConn() const
Definition: net.h:551
uint64_t GetLocalNonce() const
Definition: net.h:714
const CAddress addr
Definition: net.h:488
void SetAddrLocal(const CService &addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
May not be called more than once.
Definition: net.cpp:602
CSemaphoreGrant grantOutbound
Definition: net.h:515
Mutex cs_hSocket
Definition: net.h:473
const uint64_t nKeyedNetGroup
Definition: net.h:518
friend struct ConnmanTestMsg
Definition: net.h:458
std::atomic< int > nRefCount
Definition: net.h:516
std::atomic< int > m_greatest_common_version
Definition: net.h:767
bool IsBlockOnlyConn() const
Definition: net.h:545
int GetCommonVersion() const
Definition: net.h:738
bool IsFullOutboundConn() const
Definition: net.h:538
uint64_t nRemoteHostNonce
Definition: net.h:497
std::unique_ptr< TransportSerializer > m_serializer
Definition: net.h:462
Mutex m_subver_mutex
cleanSubVer is a sanitized string of the user agent byte array we read from the wire.
Definition: net.h:504
Mutex cs_vSend
Definition: net.h:472
std::atomic_bool fPauseSend
Definition: net.h:520
SOCKET hSocket GUARDED_BY(cs_hSocket)
std::chrono::seconds m_nextGetAvaAddr
Definition: net.h:650
uint64_t nRemoteExtraEntropy
Definition: net.h:499
int GetRefCount() const
Definition: net.h:717
uint64_t GetLocalExtraEntropy() const
Definition: net.h:715
SteadyMilliseconds m_last_poll
Definition: net.h:657
std::list< CNetMessage > vProcessMsg GUARDED_BY(cs_vProcessMsg)
void CloseSocketDisconnect() EXCLUSIVE_LOCKS_REQUIRED(!cs_hSocket)
Definition: net.cpp:557
std::optional< CPubKey > m_avalanche_pubkey GUARDED_BY(cs_avalanche_pubkey)
std::unique_ptr< TransportDeserializer > m_deserializer
Definition: net.h:461
double getAvailabilityScore() const
Definition: net.cpp:3441
size_t nSendOffset GUARDED_BY(cs_vSend)
Offset inside the first vSendMsg already sent.
Definition: net.h:469
NetPermissionFlags m_permissionFlags
Definition: net.h:769
std::atomic_bool m_bloom_filter_loaded
Whether this peer has loaded a bloom filter.
Definition: net.h:615
CService addrLocal GUARDED_BY(m_addr_local_mutex)
const ConnectionType m_conn_type
Definition: net.h:766
Network ConnectedThroughNetwork() const
Get network the peer connected through.
Definition: net.cpp:614
void copyStats(CNodeStats &stats) EXCLUSIVE_LOCKS_REQUIRED(!m_subver_mutex
Definition: net.cpp:618
const uint64_t nLocalHostNonce
Definition: net.h:764
std::atomic< std::chrono::microseconds > m_last_ping_time
Last measured round-trip time.
Definition: net.h:685
void updateAvailabilityScore(double decayFactor)
The availability score is calculated using an exponentially weighted average.
Definition: net.cpp:3426
size_t nSendSize GUARDED_BY(cs_vSend)
Total size of all vSendMsg entries.
Definition: net.h:467
std::atomic< std::chrono::seconds > m_avalanche_last_message_fault
Definition: net.h:653
const uint64_t nLocalExtraEntropy
Definition: net.h:765
bool ReceiveMsgBytes(const Config &config, Span< const uint8_t > msg_bytes, bool &complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv)
Receive bytes from the buffer and deserialize them into messages.
Definition: net.cpp:666
void invsPolled(uint32_t count)
The node was polled for count invs.
Definition: net.cpp:3418
Mutex m_addr_local_mutex
Definition: net.h:774
CNode(const CNode &)=delete
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e.
Definition: net.h:494
std::atomic< std::chrono::microseconds > m_min_ping_time
Lowest measured round-trip time.
Definition: net.h:691
const NodeId id
Definition: net.h:763
std::atomic< int > m_avalanche_message_fault_counter
Definition: net.h:655
std::atomic< std::chrono::seconds > m_last_proof_time
UNIX epoch time of the last proof received from this peer that we had not yet seen (e....
Definition: net.h:682
Mutex cs_vRecv
Definition: net.h:474
std::atomic< bool > m_avalanche_enabled
Definition: net.h:618
std::atomic< std::chrono::seconds > m_last_block_time
UNIX epoch time of the last block received from this peer that we had not yet seen (e....
Definition: net.h:666
~CNode()
Definition: net.cpp:3486
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Definition: net.h:470
std::atomic< uint64_t > invCounters
The inventories polled and voted counters since last score computation, stored as a pair of uint32_t ...
Definition: net.h:782
std::atomic_bool fDisconnect
Definition: net.h:514
std::atomic< std::chrono::seconds > m_last_recv
Definition: net.h:483
CNode(NodeId id, SOCKET hSocketIn, const CAddress &addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, uint64_t nLocalExtraEntropyIn, const CAddress &addrBindIn, const std::string &addrNameIn, ConnectionType conn_type_in, bool inbound_onion)
Definition: net.cpp:3447
std::atomic< std::chrono::seconds > m_last_tx_time
UNIX epoch time of the last transaction received from this peer that we had not yet seen (e....
Definition: net.h:674
CService GetAddrLocal() const EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
Definition: net.cpp:596
void invsVoted(uint32_t count)
The node voted for count invs.
Definition: net.cpp:3422
std::atomic< std::chrono::seconds > m_last_send
Definition: net.h:482
bool IsAvalancheOutboundConnection() const
Definition: net.h:559
void Release()
Definition: net.h:750
CNode & operator=(const CNode &)=delete
std::string cleanSubVer GUARDED_BY(m_subver_mutex)
Definition: net.h:505
CNode * AddRef()
Definition: net.h:745
Simple class for background tasks that should be run periodically or once "after a while".
Definition: scheduler.h:41
RAII-style semaphore lock.
Definition: sync.h:397
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:545
SipHash-2-4.
Definition: siphash.h:13
A helper class for interruptible sleeps.
Definition: config.h:17
Different type to mark Mutex at global scope.
Definition: sync.h:144
Interface for message handling.
Definition: net.h:794
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition: net.h:799
virtual bool ProcessMessages(const Config &config, CNode *pnode, std::atomic< bool > &interrupt) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Process protocol messages received from a given node.
virtual bool SendMessages(const Config &config, CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Send queued protocol messages to a given node.
virtual void InitializeNode(const Config &config, CNode &node, ServiceFlags our_services)=0
Initialize a peer (setup state, queue any initial messages)
~NetEventsInterface()=default
Protected destructor so that instances can only be deleted by derived classes.
virtual void FinalizeNode(const Config &config, const CNode &node)=0
Handle removal of a peer (clear state)
static void AddFlag(NetPermissionFlags &flags, NetPermissionFlags f)
static bool HasFlag(NetPermissionFlags flags, NetPermissionFlags f)
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:93
CONSTEXPR_IF_NOT_DEBUG Span< C > subspan(std::size_t offset) const noexcept
Definition: span.h:215
The TransportDeserializer takes care of holding and deserializing the network receive buffer.
Definition: net.h:356
virtual ~TransportDeserializer()
Definition: net.h:367
virtual bool Complete() const =0
virtual CNetMessage GetMessage(const Config &config, std::chrono::microseconds time)=0
virtual void SetVersion(int version)=0
virtual int Read(const Config &config, Span< const uint8_t > &msg_bytes)=0
read and deserialize data, advances msg_bytes data pointer
The TransportSerializer prepares messages for the network transport.
Definition: net.h:439
virtual void prepareForTransport(const Config &config, CSerializedNetMsg &msg, std::vector< uint8_t > &header)=0
virtual ~TransportSerializer()
Definition: net.h:446
CNetMessage GetMessage(const Config &config, std::chrono::microseconds time) override
Definition: net.cpp:763
CDataStream vRecv
Definition: net.h:382
CMessageHeader hdr
Definition: net.h:380
const uint256 & GetMessageHash() const
Definition: net.cpp:754
uint32_t nDataPos
Definition: net.h:384
uint32_t nHdrPos
Definition: net.h:383
int Read(const Config &config, Span< const uint8_t > &msg_bytes) override
read and deserialize data, advances msg_bytes data pointer
Definition: net.h:422
void SetVersion(int nVersionIn) override
Definition: net.h:418
int readData(Span< const uint8_t > msg_bytes)
Definition: net.cpp:737
bool Complete() const override
Definition: net.h:410
int readHeader(const Config &config, Span< const uint8_t > msg_bytes)
Definition: net.cpp:704
CHash256 hasher
Definition: net.h:372
V1TransportDeserializer(const CMessageHeader::MessageMagic &pchMessageStartIn, int nTypeIn, int nVersionIn)
Definition: net.h:402
CDataStream hdrbuf
Definition: net.h:378
uint256 data_hash
Definition: net.h:373
void prepareForTransport(const Config &config, CSerializedNetMsg &msg, std::vector< uint8_t > &header) override
Definition: net.cpp:806
void SetNull()
Definition: uint256.h:39
256-bit opaque blob.
Definition: uint256.h:127
unsigned int SOCKET
Definition: compat.h:40
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
#define LogPrint(category,...)
Definition: logging.h:210
@ NET
Definition: logging.h:40
Definition: init.h:28
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition: rcu.h:257
bool IsPeerAddrLocalGood(CNode *pnode)
Definition: net.cpp:236
const std::vector< std::string > CONNECTION_TYPE_DOC
Definition: net.h:138
uint16_t GetListenPort()
Definition: net.cpp:136
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:93
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:345
CService GetLocalAddress(const CNetAddr &addrPeer)
Definition: net.cpp:220
void RemoveLocal(const CService &addr)
Definition: net.cpp:310
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:69
static constexpr std::chrono::minutes TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:63
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:76
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
Definition: net.cpp:277
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
Definition: net.cpp:242
bool fDiscover
Definition: net.cpp:124
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:107
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
Definition: net.h:101
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:97
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
Definition: net.h:57
static const bool DEFAULT_FORCEDNSSEED
Definition: net.h:103
bool fListen
Definition: net.cpp:125
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
Definition: net.h:55
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(g_maplocalhost_mutex)
static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:95
static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL
Run the extra block-relay-only connection loop once every 5 minutes.
Definition: net.h:67
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:106
const std::string NET_MESSAGE_COMMAND_OTHER
Definition: net.cpp:111
static const int DEFAULT_MAX_AVALANCHE_OUTBOUND_CONNECTIONS
Maximum number of avalanche enabled outgoing connections by default.
Definition: net.h:83
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:316
static const bool DEFAULT_FIXEDSEEDS
Definition: net.h:105
std::function< void(const CAddress &addr, const std::string &msg_type, Span< const uint8_t > data, bool is_incoming)> CaptureMessage
Defaults to CaptureMessageToFile(), but can be overridden by unit tests.
Definition: net.cpp:3642
ConnectionType
Different types of connections to a peer.
Definition: net.h:151
@ BLOCK_RELAY
We use block-relay-only connections to help prevent against partition attacks.
@ MANUAL
We open manual connections to addresses that users explicitly inputted via the addnode RPC,...
@ OUTBOUND_FULL_RELAY
These are the default connections that we use to connect with the network.
@ FEELER
Feeler connections are short-lived connections made to check that a node is alive.
@ INBOUND
Inbound connections are those initiated by a peer.
@ AVALANCHE_OUTBOUND
Special case of connection to a full relay outbound with avalanche service enabled.
@ ADDR_FETCH
AddrFetch connections are short lived connections used to solicit addresses from peers.
std::map< std::string, uint64_t > mapMsgCmdSize
Definition: net.h:283
std::string getSubVersionEB(uint64_t MaxBlockSize)
This function convert MaxBlockSize from byte to MB with a decimal precision one digit rounded down E....
Definition: net.cpp:3577
GlobalMutex g_maplocalhost_mutex
Definition: net.cpp:126
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition: net.h:85
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:87
bool GetLocal(CService &addr, const CNetAddr *paddrPeer=nullptr)
Definition: net.cpp:172
static constexpr auto FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes.
Definition: net.h:65
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition: net.h:99
std::optional< NodeId > SelectNodeToEvict(std::vector< NodeEvictionCandidate > &&vEvictionCandidates)
Select an inbound peer to evict after filtering out (protecting) peers having distinct,...
Definition: net.cpp:1114
void ProtectEvictionCandidatesByRatio(std::vector< NodeEvictionCandidate > &vEvictionCandidates)
Protect desirable or disadvantaged inbound peers from eviction by ratio.
Definition: net.cpp:1019
void CaptureMessageToFile(const CAddress &addr, const std::string &msg_type, Span< const uint8_t > data, bool is_incoming)
Dump binary message to file, with timestamp.
Definition: net.cpp:3611
static const bool DEFAULT_DNSSEED
Definition: net.h:104
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
Definition: net.h:74
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
Definition: net.cpp:575
@ LOCAL_NONE
Definition: net.h:234
@ LOCAL_MAPPED
Definition: net.h:240
@ LOCAL_MANUAL
Definition: net.h:242
@ LOCAL_MAX
Definition: net.h:244
@ LOCAL_BIND
Definition: net.h:238
@ LOCAL_IF
Definition: net.h:236
std::string userAgent(const Config &config)
Definition: net.cpp:3591
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:78
void Discover()
Look up IP addresses from all interfaces on the machine and add them to the list of local addresses t...
Definition: net.cpp:2789
bool IsReachable(enum Network net)
Definition: net.cpp:324
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:334
NetPermissionFlags
Network
A network type.
Definition: netaddress.h:44
int64_t NodeId
Definition: nodeid.h:10
ServiceFlags
nServices flags.
Definition: protocol.h:335
@ NODE_NONE
Definition: protocol.h:338
bool fInbound
Definition: net.h:113
CService resolvedAddress
Definition: net.h:111
bool fConnected
Definition: net.h:112
std::string strAddedNode
Definition: net.h:110
Cache responses to addr requests to minimize privacy leak.
Definition: net.h:1226
std::chrono::microseconds m_cache_entry_expiration
Definition: net.h:1228
std::vector< CAddress > m_addrs_response_cache
Definition: net.h:1227
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition: net.h:1086
ListenSocket(SOCKET socket_, NetPermissionFlags permissions_)
Definition: net.h:1089
NetPermissionFlags m_permissions
Definition: net.h:1093
int m_max_outbound_block_relay
Definition: net.h:858
unsigned int nReceiveFloodSize
Definition: net.h:866
int m_max_outbound_full_relay
Definition: net.h:857
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:871
uint64_t nMaxOutboundLimit
Definition: net.h:867
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:870
CClientUIInterface * uiInterface
Definition: net.h:862
int m_max_avalanche_outbound
Definition: net.h:859
std::vector< CService > onion_binds
Definition: net.h:873
int nMaxFeeler
Definition: net.h:861
std::vector< std::string > m_specified_outgoing
Definition: net.h:878
int nMaxConnections
Definition: net.h:856
ServiceFlags nLocalServices
Definition: net.h:855
std::vector< std::string > m_added_nodes
Definition: net.h:879
int64_t m_peer_connect_timeout
Definition: net.h:868
std::vector< CService > vBinds
Definition: net.h:872
unsigned int nSendBufferMaxSize
Definition: net.h:865
bool m_i2p_accept_incoming
Definition: net.h:880
std::vector< std::string > vSeedNodes
Definition: net.h:869
BanMan * m_banman
Definition: net.h:864
bool m_use_addrman_outgoing
Definition: net.h:877
std::vector< NetEventsInterface * > m_msgproc
Definition: net.h:863
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
Definition: net.h:876
int nMaxAddnode
Definition: net.h:860
POD that contains various stats about a node.
Definition: net.h:290
std::string addrLocal
Definition: net.h:314
CAddress addrBind
Definition: net.h:318
uint64_t nRecvBytes
Definition: net.h:308
mapMsgCmdSize mapSendBytesPerMsgCmd
Definition: net.h:307
std::chrono::microseconds m_last_ping_time
Definition: net.h:311
uint32_t m_mapped_as
Definition: net.h:321
bool fInbound
Definition: net.h:302
uint64_t nSendBytes
Definition: net.h:306
std::chrono::seconds m_last_recv
Definition: net.h:293
std::optional< double > m_availabilityScore
Definition: net.h:323
std::chrono::seconds m_last_proof_time
Definition: net.h:295
ConnectionType m_conn_type
Definition: net.h:322
std::chrono::seconds m_last_send
Definition: net.h:292
std::chrono::seconds m_last_tx_time
Definition: net.h:294
CAddress addr
Definition: net.h:316
std::chrono::microseconds m_min_ping_time
Definition: net.h:312
int64_t nTimeOffset
Definition: net.h:298
std::chrono::seconds m_connected
Definition: net.h:297
bool m_bip152_highbandwidth_from
Definition: net.h:304
bool m_bip152_highbandwidth_to
Definition: net.h:303
std::string m_addr_name
Definition: net.h:299
mapMsgCmdSize mapRecvBytesPerMsgCmd
Definition: net.h:309
int nVersion
Definition: net.h:300
std::chrono::seconds m_last_block_time
Definition: net.h:296
Network m_network
Definition: net.h:320
NodeId nodeid
Definition: net.h:291
NetPermissionFlags m_permissionFlags
Definition: net.h:310
std::string cleanSubVer
Definition: net.h:301
int m_starting_height
Definition: net.h:305
CSerializedNetMsg(const CSerializedNetMsg &msg)=delete
CSerializedNetMsg Copy() const
Definition: net.h:127
std::vector< uint8_t > data
Definition: net.h:134
std::string m_type
Definition: net.h:135
CSerializedNetMsg & operator=(const CSerializedNetMsg &)=delete
CSerializedNetMsg()=default
CSerializedNetMsg(CSerializedNetMsg &&)=default
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
uint16_t nPort
Definition: net.h:274
int nScore
Definition: net.h:273
std::chrono::seconds m_last_tx_time
Definition: net.h:1366
Network m_network
Definition: net.h:1373
double availabilityScore
Definition: net.h:1374
std::chrono::seconds m_connected
Definition: net.h:1362
std::chrono::seconds m_last_block_time
Definition: net.h:1364
bool fRelevantServices
Definition: net.h:1367
std::chrono::microseconds m_min_ping_time
Definition: net.h:1363
std::chrono::seconds m_last_proof_time
Definition: net.h:1365
uint64_t nKeyedNetGroup
Definition: net.h:1370
Bilingual messages:
Definition: translation.h:17
#define LOCK(cs)
Definition: sync.h:306
static int count
Definition: tests.c:31
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
std::chrono::time_point< std::chrono::steady_clock, std::chrono::milliseconds > SteadyMilliseconds
Definition: time.h:31
assert(!tx.IsCoinBase())
static const int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
Definition: version.h:14