Bitcoin Core  24.1.0
P2P Digital Currency
net.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2021 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 #ifndef BITCOIN_NET_H
7 #define BITCOIN_NET_H
8 
9 #include <chainparams.h>
10 #include <common/bloom.h>
11 #include <compat/compat.h>
12 #include <node/connection_types.h>
13 #include <consensus/amount.h>
14 #include <crypto/siphash.h>
15 #include <hash.h>
16 #include <i2p.h>
17 #include <net_permissions.h>
18 #include <netaddress.h>
19 #include <netbase.h>
20 #include <netgroup.h>
21 #include <policy/feerate.h>
22 #include <protocol.h>
23 #include <random.h>
24 #include <span.h>
25 #include <streams.h>
26 #include <sync.h>
27 #include <threadinterrupt.h>
28 #include <uint256.h>
29 #include <util/check.h>
30 #include <util/sock.h>
31 
32 #include <atomic>
33 #include <condition_variable>
34 #include <cstdint>
35 #include <deque>
36 #include <functional>
37 #include <list>
38 #include <map>
39 #include <memory>
40 #include <optional>
41 #include <queue>
42 #include <thread>
43 #include <vector>
44 
45 class AddrMan;
46 class BanMan;
47 class CNode;
48 class CScheduler;
49 struct bilingual_str;
50 
52 static const bool DEFAULT_WHITELISTRELAY = true;
54 static const bool DEFAULT_WHITELISTFORCERELAY = false;
55 
57 static constexpr std::chrono::minutes TIMEOUT_INTERVAL{20};
59 static constexpr auto FEELER_INTERVAL = 2min;
61 static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL = 5min;
63 static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
65 static const unsigned int MAX_SUBVERSION_LENGTH = 256;
69 static const int MAX_ADDNODE_CONNECTIONS = 8;
71 static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS = 2;
73 static const int MAX_FEELER_CONNECTIONS = 1;
75 static const bool DEFAULT_LISTEN = true;
77 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
79 static const std::string DEFAULT_MAX_UPLOAD_TARGET{"0M"};
81 static const bool DEFAULT_BLOCKSONLY = false;
83 static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
85 static const int NUM_FDS_MESSAGE_CAPTURE = 1;
86 
87 static constexpr bool DEFAULT_FORCEDNSSEED{false};
88 static constexpr bool DEFAULT_DNSSEED{true};
89 static constexpr bool DEFAULT_FIXEDSEEDS{true};
90 static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
91 static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
92 
93 typedef int64_t NodeId;
94 
96 {
97  std::string strAddedNode;
99  bool fConnected;
100  bool fInbound;
101 };
102 
103 class CNodeStats;
104 class CClientUIInterface;
105 
107  CSerializedNetMsg() = default;
110  // No implicit copying, only moves.
111  CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
113 
115  {
116  CSerializedNetMsg copy;
117  copy.data = data;
118  copy.m_type = m_type;
119  return copy;
120  }
121 
122  std::vector<unsigned char> data;
123  std::string m_type;
124 };
125 
132 void Discover();
133 
134 uint16_t GetListenPort();
135 
136 enum
137 {
138  LOCAL_NONE, // unknown
139  LOCAL_IF, // address a local interface listens on
140  LOCAL_BIND, // address explicit bound to
141  LOCAL_MAPPED, // address reported by UPnP or NAT-PMP
142  LOCAL_MANUAL, // address explicitly specified (-externalip=)
143 
145 };
146 
147 bool IsPeerAddrLocalGood(CNode *pnode);
149 std::optional<CService> GetLocalAddrForPeer(CNode& node);
150 
155 void SetReachable(enum Network net, bool reachable);
157 bool IsReachable(enum Network net);
159 bool IsReachable(const CNetAddr& addr);
160 
161 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
162 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
163 void RemoveLocal(const CService& addr);
164 bool SeenLocal(const CService& addr);
165 bool IsLocal(const CService& addr);
166 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr);
167 CService GetLocalAddress(const CNetAddr& addrPeer);
168 CService MaybeFlipIPv6toCJDNS(const CService& service);
169 
170 
171 extern bool fDiscover;
172 extern bool fListen;
173 
175 extern std::string strSubVersion;
176 
178  int nScore;
179  uint16_t nPort;
180 };
181 
183 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(g_maplocalhost_mutex);
184 
185 extern const std::string NET_MESSAGE_TYPE_OTHER;
186 using mapMsgTypeSize = std::map</* message type */ std::string, /* total bytes */ uint64_t>;
187 
189 {
190 public:
192  std::chrono::seconds m_last_send;
193  std::chrono::seconds m_last_recv;
194  std::chrono::seconds m_last_tx_time;
195  std::chrono::seconds m_last_block_time;
196  std::chrono::seconds m_connected;
197  int64_t nTimeOffset;
198  std::string m_addr_name;
199  int nVersion;
200  std::string cleanSubVer;
201  bool fInbound;
205  uint64_t nSendBytes;
207  uint64_t nRecvBytes;
210  std::chrono::microseconds m_last_ping_time;
211  std::chrono::microseconds m_min_ping_time;
212  // Our address, as reported by the peer
213  std::string addrLocal;
214  // Address of this peer
216  // Bind address of our side of the connection
218  // Network the peer connected through
220  uint32_t m_mapped_as;
222 };
223 
224 
229 class CNetMessage {
230 public:
232  std::chrono::microseconds m_time{0};
233  uint32_t m_message_size{0};
234  uint32_t m_raw_message_size{0};
235  std::string m_type;
236 
237  CNetMessage(CDataStream&& recv_in) : m_recv(std::move(recv_in)) {}
238 
239  void SetVersion(int nVersionIn)
240  {
241  m_recv.SetVersion(nVersionIn);
242  }
243 };
244 
250 public:
251  // returns true if the current deserialization is complete
252  virtual bool Complete() const = 0;
253  // set the serialization context version
254  virtual void SetVersion(int version) = 0;
256  virtual int Read(Span<const uint8_t>& msg_bytes) = 0;
257  // decomposes a message from the context
258  virtual CNetMessage GetMessage(std::chrono::microseconds time, bool& reject_message) = 0;
260 };
261 
263 {
264 private:
266  const NodeId m_node_id; // Only for logging
267  mutable CHash256 hasher;
269  bool in_data; // parsing header (false) or data (true)
270  CDataStream hdrbuf; // partially received header
271  CMessageHeader hdr; // complete header
272  CDataStream vRecv; // received message data
273  unsigned int nHdrPos;
274  unsigned int nDataPos;
275 
276  const uint256& GetMessageHash() const;
277  int readHeader(Span<const uint8_t> msg_bytes);
278  int readData(Span<const uint8_t> msg_bytes);
279 
280  void Reset() {
281  vRecv.clear();
282  hdrbuf.clear();
283  hdrbuf.resize(24);
284  in_data = false;
285  nHdrPos = 0;
286  nDataPos = 0;
287  data_hash.SetNull();
288  hasher.Reset();
289  }
290 
291 public:
292  V1TransportDeserializer(const CChainParams& chain_params, const NodeId node_id, int nTypeIn, int nVersionIn)
293  : m_chain_params(chain_params),
294  m_node_id(node_id),
295  hdrbuf(nTypeIn, nVersionIn),
296  vRecv(nTypeIn, nVersionIn)
297  {
298  Reset();
299  }
300 
301  bool Complete() const override
302  {
303  if (!in_data)
304  return false;
305  return (hdr.nMessageSize == nDataPos);
306  }
307  void SetVersion(int nVersionIn) override
308  {
309  hdrbuf.SetVersion(nVersionIn);
310  vRecv.SetVersion(nVersionIn);
311  }
312  int Read(Span<const uint8_t>& msg_bytes) override
313  {
314  int ret = in_data ? readData(msg_bytes) : readHeader(msg_bytes);
315  if (ret < 0) {
316  Reset();
317  } else {
318  msg_bytes = msg_bytes.subspan(ret);
319  }
320  return ret;
321  }
322  CNetMessage GetMessage(std::chrono::microseconds time, bool& reject_message) override;
323 };
324 
328 public:
329  // prepare message for transport (header construction, error-correction computation, payload encryption, etc.)
330  virtual void prepareForTransport(CSerializedNetMsg& msg, std::vector<unsigned char>& header) const = 0;
331  virtual ~TransportSerializer() {}
332 };
333 
335 public:
336  void prepareForTransport(CSerializedNetMsg& msg, std::vector<unsigned char>& header) const override;
337 };
338 
340 {
342  std::unique_ptr<i2p::sam::Session> i2p_sam_session = nullptr;
343  bool prefer_evict = false;
344 };
345 
347 class CNode
348 {
349  friend class CConnman;
350  friend struct ConnmanTestMsg;
351 
352 public:
353  const std::unique_ptr<TransportDeserializer> m_deserializer; // Used only by SocketHandler thread
354  const std::unique_ptr<const TransportSerializer> m_serializer;
355 
357 
366  std::shared_ptr<Sock> m_sock GUARDED_BY(m_sock_mutex);
367 
369  size_t nSendSize GUARDED_BY(cs_vSend){0};
371  size_t nSendOffset GUARDED_BY(cs_vSend){0};
372  uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
373  std::deque<std::vector<unsigned char>> vSendMsg GUARDED_BY(cs_vSend);
377 
379  std::list<CNetMessage> vProcessMsg GUARDED_BY(cs_vProcessMsg);
380  size_t nProcessQueueSize GUARDED_BY(cs_vProcessMsg){0};
381 
383 
384  uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
385 
386  std::atomic<std::chrono::seconds> m_last_send{0s};
387  std::atomic<std::chrono::seconds> m_last_recv{0s};
389  const std::chrono::seconds m_connected;
390  std::atomic<int64_t> nTimeOffset{0};
391  // Address of this peer
392  const CAddress addr;
393  // Bind address of our side of the connection
395  const std::string m_addr_name;
397  const bool m_inbound_onion;
398  std::atomic<int> nVersion{0};
404  std::string cleanSubVer GUARDED_BY(m_subver_mutex){};
405  const bool m_prefer_evict{false}; // This peer is preferred for eviction.
406  bool HasPermission(NetPermissionFlags permission) const {
407  return NetPermissions::HasFlag(m_permission_flags, permission);
408  }
410  std::atomic_bool fSuccessfullyConnected{false};
411  // Setting fDisconnect to true will cause the node to be disconnected the
412  // next time DisconnectNodes() runs
413  std::atomic_bool fDisconnect{false};
415  std::atomic<int> nRefCount{0};
416 
417  const uint64_t nKeyedNetGroup;
418  std::atomic_bool fPauseRecv{false};
419  std::atomic_bool fPauseSend{false};
420 
422  switch (m_conn_type) {
425  return true;
430  return false;
431  } // no default case, so the compiler can warn about missing cases
432 
433  assert(false);
434  }
435 
436  bool IsFullOutboundConn() const {
438  }
439 
440  bool IsManualConn() const {
442  }
443 
444  bool IsBlockOnlyConn() const {
446  }
447 
448  bool IsFeelerConn() const {
450  }
451 
452  bool IsAddrFetchConn() const {
454  }
455 
456  bool IsInboundConn() const {
458  }
459 
460  bool ExpectServicesFromConn() const {
461  switch (m_conn_type) {
465  return false;
469  return true;
470  } // no default case, so the compiler can warn about missing cases
471 
472  assert(false);
473  }
474 
486 
487  // We selected peer as (compact blocks) high-bandwidth peer (BIP152)
488  std::atomic<bool> m_bip152_highbandwidth_to{false};
489  // Peer selected us as (compact blocks) high-bandwidth peer (BIP152)
490  std::atomic<bool> m_bip152_highbandwidth_from{false};
491 
493  std::atomic_bool m_has_all_wanted_services{false};
494 
499  std::atomic_bool m_relays_txs{false};
500 
503  std::atomic_bool m_bloom_filter_loaded{false};
504 
510  std::atomic<std::chrono::seconds> m_last_block_time{0s};
511 
516  std::atomic<std::chrono::seconds> m_last_tx_time{0s};
517 
519  std::atomic<std::chrono::microseconds> m_last_ping_time{0us};
520 
523  std::atomic<std::chrono::microseconds> m_min_ping_time{std::chrono::microseconds::max()};
524 
525  CNode(NodeId id,
526  std::shared_ptr<Sock> sock,
527  const CAddress& addrIn,
528  uint64_t nKeyedNetGroupIn,
529  uint64_t nLocalHostNonceIn,
530  const CAddress& addrBindIn,
531  const std::string& addrNameIn,
532  ConnectionType conn_type_in,
533  bool inbound_onion,
534  CNodeOptions&& node_opts = {});
535  CNode(const CNode&) = delete;
536  CNode& operator=(const CNode&) = delete;
537 
538  NodeId GetId() const {
539  return id;
540  }
541 
542  uint64_t GetLocalNonce() const {
543  return nLocalHostNonce;
544  }
545 
546  int GetRefCount() const
547  {
548  assert(nRefCount >= 0);
549  return nRefCount;
550  }
551 
561  bool ReceiveMsgBytes(Span<const uint8_t> msg_bytes, bool& complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv);
562 
563  void SetCommonVersion(int greatest_common_version)
564  {
566  m_greatest_common_version = greatest_common_version;
567  }
568  int GetCommonVersion() const
569  {
571  }
572 
576 
578  {
579  nRefCount++;
580  return this;
581  }
582 
583  void Release()
584  {
585  nRefCount--;
586  }
587 
589 
591 
593 
595  void PongReceived(std::chrono::microseconds ping_time) {
596  m_last_ping_time = ping_time;
597  m_min_ping_time = std::min(m_min_ping_time.load(), ping_time);
598  }
599 
600 private:
601  const NodeId id;
602  const uint64_t nLocalHostNonce;
605 
606  std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
607 
608  // Our address, as reported by the peer
611 
612  mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend);
613  mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv);
614 
625  std::unique_ptr<i2p::sam::Session> m_i2p_sam_session GUARDED_BY(m_sock_mutex);
626 };
627 
632 {
633 public:
635  virtual void InitializeNode(CNode& node, ServiceFlags our_services) = 0;
636 
638  virtual void FinalizeNode(const CNode& node) = 0;
639 
647  virtual bool ProcessMessages(CNode* pnode, std::atomic<bool>& interrupt) = 0;
648 
655  virtual bool SendMessages(CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(pnode->cs_sendProcessing) = 0;
656 
657 
658 protected:
663  ~NetEventsInterface() = default;
664 };
665 
666 class CConnman
667 {
668 public:
669 
670  struct Options
671  {
676  int nMaxAddnode = 0;
677  int nMaxFeeler = 0;
680  BanMan* m_banman = nullptr;
681  unsigned int nSendBufferMaxSize = 0;
682  unsigned int nReceiveFloodSize = 0;
683  uint64_t nMaxOutboundLimit = 0;
685  std::vector<std::string> vSeedNodes;
686  std::vector<NetWhitelistPermissions> vWhitelistedRange;
687  std::vector<NetWhitebindPermissions> vWhiteBinds;
688  std::vector<CService> vBinds;
689  std::vector<CService> onion_binds;
694  std::vector<std::string> m_specified_outgoing;
695  std::vector<std::string> m_added_nodes;
697  };
698 
700  {
702 
703  nLocalServices = connOptions.nLocalServices;
704  nMaxConnections = connOptions.nMaxConnections;
705  m_max_outbound_full_relay = std::min(connOptions.m_max_outbound_full_relay, connOptions.nMaxConnections);
706  m_max_outbound_block_relay = connOptions.m_max_outbound_block_relay;
707  m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
708  nMaxAddnode = connOptions.nMaxAddnode;
709  nMaxFeeler = connOptions.nMaxFeeler;
711  m_client_interface = connOptions.uiInterface;
712  m_banman = connOptions.m_banman;
713  m_msgproc = connOptions.m_msgproc;
714  nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
715  nReceiveFloodSize = connOptions.nReceiveFloodSize;
716  m_peer_connect_timeout = std::chrono::seconds{connOptions.m_peer_connect_timeout};
717  {
719  nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
720  }
721  vWhitelistedRange = connOptions.vWhitelistedRange;
722  {
724  m_added_nodes = connOptions.m_added_nodes;
725  }
726  m_onion_binds = connOptions.onion_binds;
727  }
728 
729  CConnman(uint64_t seed0, uint64_t seed1, AddrMan& addrman, const NetGroupManager& netgroupman,
730  bool network_active = true);
731 
732  ~CConnman();
733 
735 
736  void StopThreads();
737  void StopNodes();
738  void Stop()
739  {
740  StopThreads();
741  StopNodes();
742  };
743 
745  bool GetNetworkActive() const { return fNetworkActive; };
747  void SetNetworkActive(bool active);
748  void OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant* grantOutbound, const char* strDest, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex);
749  bool CheckIncomingNonce(uint64_t nonce);
750 
751  bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
752 
754 
755  using NodeFn = std::function<void(CNode*)>;
756  void ForEachNode(const NodeFn& func)
757  {
759  for (auto&& node : m_nodes) {
761  func(node);
762  }
763  };
764 
765  void ForEachNode(const NodeFn& func) const
766  {
768  for (auto&& node : m_nodes) {
770  func(node);
771  }
772  };
773 
774  // Addrman functions
782  std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct, std::optional<Network> network) const;
789  std::vector<CAddress> GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct);
790 
791  // This allows temporarily exceeding m_max_outbound_full_relay, with the goal of finding
792  // a peer that is better than all our current peers.
793  void SetTryNewOutboundPeer(bool flag);
794  bool GetTryNewOutboundPeer() const;
795 
797 
798  // Return the number of outbound peers we have in excess of our target (eg,
799  // if we previously called SetTryNewOutboundPeer(true), and have since set
800  // to false, we may have extra peers that we wish to disconnect). This may
801  // return a value less than (num_outbound_connections - num_outbound_slots)
802  // in cases where some outbound connections are not yet fully connected, or
803  // not yet fully disconnected.
804  int GetExtraFullOutboundCount() const;
805  // Count the number of block-relay-only peers we have over our limit.
806  int GetExtraBlockRelayCount() const;
807 
808  bool AddNode(const std::string& node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
810  std::vector<AddedNodeInfo> GetAddedNodeInfo() const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
811 
824  bool AddConnection(const std::string& address, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex);
825 
826  size_t GetNodeCount(ConnectionDirection) const;
827  void GetNodeStats(std::vector<CNodeStats>& vstats) const;
828  bool DisconnectNode(const std::string& node);
829  bool DisconnectNode(const CSubNet& subnet);
830  bool DisconnectNode(const CNetAddr& addr);
831  bool DisconnectNode(NodeId id);
832 
840 
842  std::chrono::seconds GetMaxOutboundTimeframe() const;
843 
847  bool OutboundTargetReached(bool historicalBlockServingLimit) const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
848 
852 
854 
855  uint64_t GetTotalBytesRecv() const;
857 
859  CSipHasher GetDeterministicRandomizer(uint64_t id) const;
860 
861  unsigned int GetReceiveFloodSize() const;
862 
864 
866  bool ShouldRunInactivityChecks(const CNode& node, std::chrono::seconds now) const;
867 
868 private:
869  struct ListenSocket {
870  public:
871  std::shared_ptr<Sock> sock;
873  ListenSocket(std::shared_ptr<Sock> sock_, NetPermissionFlags permissions_)
874  : sock{sock_}, m_permissions{permissions_}
875  {
876  }
877 
878  private:
880  };
881 
885 
886  bool BindListenPort(const CService& bindAddr, bilingual_str& strError, NetPermissionFlags permissions);
887  bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions);
888  bool InitBinds(const Options& options);
889 
891  void AddAddrFetch(const std::string& strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex);
896  void AcceptConnection(const ListenSocket& hListenSocket);
897 
906  void CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock,
907  NetPermissionFlags permission_flags,
908  const CAddress& addr_bind,
909  const CAddress& addr);
910 
911  void DisconnectNodes();
914  bool InactivityCheck(const CNode& node) const;
915 
921  Sock::EventsPerSock GenerateWaitSockets(Span<CNode* const> nodes);
922 
927 
933  void SocketHandlerConnected(const std::vector<CNode*>& nodes,
934  const Sock::EventsPerSock& events_per_sock)
936 
941  void SocketHandlerListening(const Sock::EventsPerSock& events_per_sock);
942 
945 
946  uint64_t CalculateKeyedNetGroup(const CAddress& ad) const;
947 
948  CNode* FindNode(const CNetAddr& ip);
949  CNode* FindNode(const CSubNet& subNet);
950  CNode* FindNode(const std::string& addrName);
951  CNode* FindNode(const CService& addr);
952 
957  bool AlreadyConnectedToAddress(const CAddress& addr);
958 
960  CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex);
962 
963  void DeleteNode(CNode* pnode);
964 
966 
967  size_t SocketSendData(CNode& node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend);
968  void DumpAddresses();
969 
970  // Network stats
971  void RecordBytesRecv(uint64_t bytes);
973 
977  std::vector<CAddress> GetCurrentBlockRelayOnlyConns() const;
978 
979  // Whether the node should be passed out in ForEach* callbacks
980  static bool NodeFullyConnected(const CNode* pnode);
981 
982  // Network usage totals
984  std::atomic<uint64_t> nTotalBytesRecv{0};
985  uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex) {0};
986 
987  // outbound limit & stats
988  uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex) {0};
989  std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex) {0};
991 
992  // P2P timeout in seconds
993  std::chrono::seconds m_peer_connect_timeout;
994 
995  // Whitelisted ranges. Any node connecting from these is automatically
996  // whitelisted (as well as those connecting to whitelisted binds).
997  std::vector<NetWhitelistPermissions> vWhitelistedRange;
998 
999  unsigned int nSendBufferMaxSize{0};
1000  unsigned int nReceiveFloodSize{0};
1001 
1002  std::vector<ListenSocket> vhListenSocket;
1003  std::atomic<bool> fNetworkActive{true};
1007  std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
1009  std::vector<std::string> m_added_nodes GUARDED_BY(m_added_nodes_mutex);
1011  std::vector<CNode*> m_nodes GUARDED_BY(m_nodes_mutex);
1012  std::list<CNode*> m_nodes_disconnected;
1014  std::atomic<NodeId> nLastNodeId{0};
1015  unsigned int nPrevNodeCount{0};
1016 
1024  std::vector<CAddress> m_addrs_response_cache;
1025  std::chrono::microseconds m_cache_entry_expiration{0};
1026  };
1027 
1042  std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
1043 
1055 
1056  std::unique_ptr<CSemaphore> semOutbound;
1057  std::unique_ptr<CSemaphore> semAddnode;
1059 
1060  // How many full-relay (tx, block, addr) outbound peers we want
1062 
1063  // How many block-relay only outbound peers we want
1064  // We do not relay tx or addr messages with these peers
1066 
1075 
1080  std::vector<CAddress> m_anchors;
1081 
1083  const uint64_t nSeed0, nSeed1;
1084 
1086  bool fMsgProcWake GUARDED_BY(mutexMsgProc);
1087 
1088  std::condition_variable condMsgProc;
1090  std::atomic<bool> flagInterruptMsgProc{false};
1091 
1099 
1105  std::unique_ptr<i2p::sam::Session> m_i2p_sam_session;
1106 
1108  std::thread threadSocketHandler;
1113 
1118 
1123  std::atomic_bool m_start_extra_block_relay_peers{false};
1124 
1129  std::vector<CService> m_onion_binds;
1130 
1135 
1143  std::queue<std::unique_ptr<i2p::sam::Session>> m_unused_i2p_sessions GUARDED_BY(m_unused_i2p_sessions_mutex);
1144 
1149  static constexpr size_t MAX_UNUSED_I2P_SESSIONS_SIZE{10};
1150 
1156  {
1157  public:
1158  explicit NodesSnapshot(const CConnman& connman, bool shuffle)
1159  {
1160  {
1161  LOCK(connman.m_nodes_mutex);
1162  m_nodes_copy = connman.m_nodes;
1163  for (auto& node : m_nodes_copy) {
1164  node->AddRef();
1165  }
1166  }
1167  if (shuffle) {
1169  }
1170  }
1171 
1173  {
1174  for (auto& node : m_nodes_copy) {
1175  node->Release();
1176  }
1177  }
1178 
1179  const std::vector<CNode*>& Nodes() const
1180  {
1181  return m_nodes_copy;
1182  }
1183 
1184  private:
1185  std::vector<CNode*> m_nodes_copy;
1186  };
1187 
1188  friend struct CConnmanTest;
1189  friend struct ConnmanTestMsg;
1190 };
1191 
1193 void CaptureMessageToFile(const CAddress& addr,
1194  const std::string& msg_type,
1196  bool is_incoming);
1197 
1199 extern std::function<void(const CAddress& addr,
1200  const std::string& msg_type,
1202  bool is_incoming)>
1204 
1205 #endif // BITCOIN_NET_H
bool RemoveAddedNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2562
std::chrono::microseconds m_min_ping_time
Definition: net.h:211
std::vector< CService > vBinds
Definition: net.h:688
int m_max_outbound_full_relay
Definition: net.h:674
std::atomic< bool > flagInterruptMsgProc
Definition: net.h:1090
uint256 data_hash
Definition: net.h:268
std::vector< CAddress > m_addrs_response_cache
Definition: net.h:1024
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:71
uint64_t CalculateKeyedNetGroup(const CAddress &ad) const
Definition: net.cpp:2856
std::string m_type
Definition: net.h:123
CONSTEXPR_IF_NOT_DEBUG Span< C > subspan(std::size_t offset) const noexcept
Definition: span.h:194
int nMaxFeeler
Definition: net.h:1068
int ret
bool IsReachable(enum Network net)
Definition: net.cpp:333
std::atomic_bool fPauseSend
Definition: net.h:419
CNetMessage GetMessage(std::chrono::microseconds time, bool &reject_message) override
Definition: net.cpp:779
AddrFetch connections are short lived connections used to solicit addresses from peers.
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:63
bool m_i2p_accept_incoming
Definition: net.h:696
CService MaybeFlipIPv6toCJDNS(const CService &service)
If an IPv6 address belongs to the address range used by the CJDNS network and the CJDNS network is re...
Definition: net.cpp:275
int m_max_outbound
Definition: net.h:1069
Mutex m_addr_local_mutex
Definition: net.h:610
void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:1408
std::atomic< bool > fNetworkActive
Definition: net.h:1003
mapMsgTypeSize mapSendBytesPerMsgType
Definition: net.h:206
Definition: banman.h:58
static void AddFlag(NetPermissionFlags &flags, NetPermissionFlags f)
ServiceFlags
nServices flags
Definition: protocol.h:267
void SetNull()
Definition: uint256.h:42
Inbound connections are those initiated by a peer.
int64_t nTimeOffset
Definition: net.h:197
int readData(Span< const uint8_t > msg_bytes)
Definition: net.cpp:754
assert(!tx.IsCoinBase())
bool fListen
Definition: net.cpp:116
int m_max_outbound_block_relay
Definition: net.h:675
uint32_t m_mapped_as
Definition: net.h:220
void SocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
Check connected and listening sockets for IO readiness and process them accordingly.
Definition: net.cpp:1250
unsigned int nonce
Definition: miner_tests.cpp:60
NetPermissionFlags permission_flags
Definition: net.h:341
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
Definition: net.cpp:2250
bool OutboundTargetReached(bool historicalBlockServingLimit) const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
check if the outbound target is reached if param historicalBlockServingLimit is set true...
Definition: net.cpp:2702
Feeler connections are short-lived connections made to check that a node is alive.
Mutex m_total_bytes_sent_mutex
Definition: net.h:983
std::shared_ptr< Sock > sock
Definition: net.h:871
std::list< CNode * > m_nodes_disconnected
Definition: net.h:1012
Bilingual messages:
Definition: translation.h:18
void SetVersion(int nVersionIn) override
Definition: net.h:307
BanMan * m_banman
Definition: net.h:680
std::atomic_bool m_has_all_wanted_services
Whether this peer provides all services that we want.
Definition: net.h:493
Mutex mutexMsgProc
Definition: net.h:1089
static constexpr size_t MAX_UNUSED_I2P_SESSIONS_SIZE
Cap on the size of m_unused_i2p_sessions, to ensure it does not unexpectedly use too much memory...
Definition: net.h:1149
const uint64_t nKeyedNetGroup
Definition: net.h:417
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:345
std::map< std::string, uint64_t > mapMsgTypeSize
Definition: net.h:186
CNode & operator=(const CNode &)=delete
CDataStream hdrbuf
Definition: net.h:270
bool IsOutboundOrBlockRelayConn() const
Definition: net.h:421
const std::chrono::seconds m_connected
Unix epoch time at peer connection.
Definition: net.h:389
const std::unique_ptr< TransportDeserializer > m_deserializer
Definition: net.h:353
std::vector< unsigned char > data
Definition: net.h:122
m_peer_connect_timeout
Definition: net.h:716
unsigned int nDataPos
Definition: net.h:274
const ConnectionType m_conn_type
Definition: net.h:603
uint64_t GetTotalBytesRecv() const
Definition: net.cpp:2733
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:997
m_max_outbound
Definition: net.h:710
bool IsFeelerConn() const
Definition: net.h:448
unsigned int nReceiveFloodSize
Definition: net.h:682
uint16_t GetListenPort()
Definition: net.cpp:128
int m_max_outbound_full_relay
Definition: net.h:1061
CClientUIInterface * uiInterface
Definition: net.h:678
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:1129
virtual void prepareForTransport(CSerializedNetMsg &msg, std::vector< unsigned char > &header) const =0
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:406
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, const CNetAddr &addr) const
Definition: net.cpp:595
CDataStream m_recv
received message data
Definition: net.h:231
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:75
CNetMessage(CDataStream &&recv_in)
Definition: net.h:237
int nMaxAddnode
Definition: net.h:1067
RAII-style semaphore lock.
Definition: sync.h:344
friend struct CConnmanTest
Definition: net.h:1188
void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:2409
void SetCommonVersion(int greatest_common_version)
Definition: net.h:563
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:69
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
Definition: net.cpp:2095
RecursiveMutex cs_vProcessMsg
Definition: net.h:378
uint32_t m_message_size
size of the payload
Definition: net.h:233
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
Definition: net.cpp:233
std::string cleanSubVer
Definition: net.h:200
Interface for message handling.
Definition: net.h:631
void SetVersion(int nVersionIn)
Definition: net.h:239
NetEventsInterface * m_msgproc
Definition: net.h:1072
int nMaxConnections
Definition: net.h:673
CSerializedNetMsg()=default
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:69
void ForEachNode(const NodeFn &func) const
Definition: net.h:765
int m_max_outbound_block_relay
Definition: net.h:1065
Mutex m_subver_mutex
Definition: net.h:399
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:185
std::chrono::seconds GetMaxOutboundTimeLeftInCycle_() const EXCLUSIVE_LOCKS_REQUIRED(m_total_bytes_sent_mutex)
returns the time left in the current max outbound cycle in case of no limit, it will always return 0 ...
Definition: net.cpp:2687
void SetTryNewOutboundPeer(bool flag)
Definition: net.cpp:1551
uint32_t nMessageSize
Definition: protocol.h:52
A hasher class for Bitcoin&#39;s 256-bit hash (double SHA-256).
Definition: hash.h:24
std::chrono::seconds m_last_recv
Definition: net.h:193
void RecordBytesSent(uint64_t bytes) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:2650
const bool m_prefer_evict
Definition: net.h:405
uint64_t GetLocalNonce() const
Definition: net.h:542
m_max_outbound_block_relay
Definition: net.h:706
bool AddNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2551
NetPermissionFlags
ConnectionType m_conn_type
Definition: net.h:221
These are the default connections that we use to connect with the network.
std::shared_ptr< Sock > m_sock GUARDED_BY(m_sock_mutex)
Socket used for communication with the node.
AddrMan & addrman
Definition: net.h:1005
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Definition: net.h:372
Netgroup manager.
Definition: netgroup.h:16
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:2496
void GetNodeStats(std::vector< CNodeStats > &vstats) const
Definition: net.cpp:2590
Definition: net.h:144
Signals for UI communication.
Definition: interface_ui.h:24
std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex)
Definition: net.h:989
static constexpr std::chrono::minutes TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:57
void StopThreads()
Definition: net.cpp:2433
std::list< CNetMessage > vRecvMsg
Definition: net.h:606
bool GetTryNewOutboundPeer() const
Definition: net.cpp:1546
void NotifyNumConnectionsChanged()
Definition: net.cpp:1152
const NodeId m_node_id
Definition: net.h:266
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:1042
void Init(const Options &connOptions) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
uint64_t GetMaxOutboundTarget() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:2668
void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:1528
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition: net.h:73
static bool HasFlag(NetPermissionFlags flags, NetPermissionFlags f)
Stochastic address manager.
Definition: addrman.h:86
bool fConnected
Definition: net.h:99
virtual ~TransportDeserializer()
Definition: net.h:259
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition: net.h:872
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:2838
int GetRefCount() const
Definition: net.h:546
NetPermissionFlags m_permission_flags
Definition: net.h:209
RecursiveMutex cs_sendProcessing
Definition: net.h:380
ServiceFlags nLocalServices
Services this node offers.
Definition: net.h:1054
bool ReceiveMsgBytes(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:669
Mutex m_unused_i2p_sessions_mutex
Mutex protecting m_i2p_sam_sessions.
Definition: net.h:1134
bool DisconnectNode(const std::string &node)
Definition: net.cpp:2602
CHash256 hasher
Definition: net.h:267
int GetExtraBlockRelayCount() const
Definition: net.cpp:1583
uint16_t nPort
Definition: net.h:179
void RecordBytesRecv(uint64_t bytes)
Definition: net.cpp:2645
std::function< void(const CAddress &addr, const std::string &msg_type, Span< const unsigned char > data, bool is_incoming)> CaptureMessage
Defaults to CaptureMessageToFile(), but can be overridden by unit tests.
Definition: net.cpp:2898
nLocalServices
Definition: net.h:703
void DumpAddresses()
Definition: net.cpp:1518
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:90
Mutex m_sock_mutex
Definition: net.h:375
std::thread threadI2PAcceptIncoming
Definition: net.h:1112
CService GetLocalAddress(const CNetAddr &addrPeer)
Definition: net.cpp:209
int nVersion
Definition: net.h:199
void SetAddrLocal(const CService &addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
May not be called more than once.
Definition: net.cpp:608
nMaxOutboundLimit
Definition: net.h:719
virtual void InitializeNode(CNode &node, ServiceFlags our_services)=0
Initialize a peer (setup state, queue any initial messages)
CSerializedNetMsg Copy() const
Definition: net.h:114
size_t nProcessQueueSize GUARDED_BY(cs_vProcessMsg)
Definition: net.h:380
ListenSocket(std::shared_ptr< Sock > sock_, NetPermissionFlags permissions_)
Definition: net.h:873
void Release()
Definition: net.h:583
std::atomic_bool m_bloom_filter_loaded
Whether this peer has loaded a bloom filter.
Definition: net.h:503
std::chrono::microseconds m_cache_entry_expiration
Definition: net.h:1025
bool GetLocal(CService &addr, const CNetAddr *paddrPeer=nullptr)
Definition: net.cpp:159
static bool NodeFullyConnected(const CNode *pnode)
Definition: net.cpp:2791
unsigned int nPrevNodeCount
Definition: net.h:1015
bool InactivityCheck(const CNode &node) const
Return true if the peer is inactive and should be disconnected.
Definition: net.cpp:1172
std::condition_variable condMsgProc
Definition: net.h:1088
std::atomic_bool m_start_extra_block_relay_peers
flag for initiating extra block-relay-only peer connections.
Definition: net.h:1123
void resize(size_type n, value_type c=value_type{})
Definition: streams.h:239
std::chrono::seconds m_connected
Definition: net.h:196
std::vector< AddedNodeInfo > GetAddedNodeInfo() const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:1895
Mutex m_added_nodes_mutex
Definition: net.h:1010
virtual int Read(Span< const uint8_t > &msg_bytes)=0
read and deserialize data, advances msg_bytes data pointer
GlobalMutex g_maplocalhost_mutex
Definition: net.cpp:117
We open manual connections to addresses that users explicitly requested via the addnode RPC or the -a...
size_t SocketSendData(CNode &node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend)
Definition: net.cpp:830
int m_starting_height
Definition: net.h:204
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition: net.h:1083
int Read(Span< const uint8_t > &msg_bytes) override
read and deserialize data, advances msg_bytes data pointer
Definition: net.h:312
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:499
std::thread threadOpenAddedConnections
Definition: net.h:1109
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
#define LOCK(cs)
Definition: sync.h:261
void StartExtraBlockRelayPeers()
Definition: net.cpp:1557
CNode * FindNode(const CNetAddr &ip)
Definition: net.cpp:362
ServiceFlags GetLocalServices() const
Used to convey which local services we are offering peers during node connection. ...
Definition: net.cpp:2745
bool IsPeerAddrLocalGood(CNode *pnode)
Definition: net.cpp:226
std::function< void(CNode *)> NodeFn
Definition: net.h:755
NetEventsInterface * m_msgproc
Definition: net.h:679
static const int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
Definition: version.h:15
std::string strAddedNode
Definition: net.h:97
void SocketHandlerListening(const Sock::EventsPerSock &events_per_sock)
Accept incoming connections, one from each read-ready listening socket.
Definition: net.cpp:1373
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:520
Fast randomness source.
Definition: random.h:142
Transport protocol agnostic message container.
Definition: net.h:229
const CAddress addrBind
Definition: net.h:394
std::vector< std::string > vSeedNodes
Definition: net.h:685
std::vector< std::string > m_specified_outgoing
Definition: net.h:694
bool m_bip152_highbandwidth_from
Definition: net.h:203
void DisconnectNodes()
Definition: net.cpp:1102
void prepareForTransport(CSerializedNetMsg &msg, std::vector< unsigned char > &header) const override
Definition: net.cpp:816
m_banman
Definition: net.h:712
uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex)
Definition: net.h:988
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *strDest, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Definition: net.cpp:1979
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:1056
std::thread threadMessageHandler
Definition: net.h:1111
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
Definition: net.h:85
nSendBufferMaxSize
Definition: net.h:714
bool AddConnection(const std::string &address, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Attempts to open a connection.
Definition: net.cpp:1065
Network m_network
Definition: net.h:219
bool fInbound
Definition: net.h:201
const uint256 & GetMessageHash() const
Definition: net.cpp:771
~NetEventsInterface()=default
Protected destructor so that instances can only be deleted by derived classes.
bool IsManualConn() const
Definition: net.h:440
virtual void FinalizeNode(const CNode &node)=0
Handle removal of a peer (clear state)
int GetExtraFullOutboundCount() const
Definition: net.cpp:1569
std::chrono::microseconds m_last_ping_time
Definition: net.h:210
A CService with information about it as peer.
Definition: protocol.h:354
std::chrono::seconds m_last_tx_time
Definition: net.h:194
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const
Return vector of current BLOCK_RELAY peers.
Definition: net.cpp:1882
uint64_t nRecvBytes
Definition: net.h:207
static constexpr bool DEFAULT_FIXEDSEEDS
Definition: net.h:89
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(g_maplocalhost_mutex)
bool fInbound
Definition: net.h:100
int nMaxFeeler
Definition: net.h:677
Network
A network type.
Definition: netaddress.h:44
static CService ip(uint32_t i)
bool m_bip152_highbandwidth_to
Definition: net.h:202
bool ExpectServicesFromConn() const
Definition: net.h:460
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:1117
int64_t NodeId
Definition: net.h:93
bool InitBinds(const Options &options)
Definition: net.cpp:2272
Definition: net.h:666
void SetNetworkActive(bool active)
Definition: net.cpp:2215
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:77
bool GetNetworkActive() const
Definition: net.h:745
static constexpr bool DEFAULT_DNSSEED
Definition: net.h:88
std::atomic< bool > m_bip152_highbandwidth_to
Definition: net.h:488
const NetPermissionFlags m_permission_flags
Definition: net.h:356
std::chrono::seconds m_last_send
Definition: net.h:192
NodeId GetId() const
Definition: net.h:538
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition: net.cpp:2851
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e. connected via our Tor onion service.
Definition: net.h:397
uint64_t nSendBytes
Definition: net.h:205
void PongReceived(std::chrono::microseconds ping_time)
A ping-pong round trip has completed successfully.
Definition: net.h:595
std::atomic_bool fDisconnect
Definition: net.h:413
int nMaxConnections
Definition: net.h:1058
void CreateNodeFromAcceptedSocket(std::unique_ptr< Sock > &&sock, NetPermissionFlags permission_flags, 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:961
void AddAddrFetch(const std::string &strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex)
Definition: net.cpp:122
The TransportSerializer prepares messages for the network transport.
Definition: net.h:327
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:516
mapMsgTypeSize mapRecvBytesPerMsgType
Definition: net.h:208
#define Assume(val)
Assume is the identity function.
Definition: check.h:86
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Definition: net.h:384
RecursiveMutex m_nodes_mutex
Definition: net.h:1013
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:2164
unsigned int GetReceiveFloodSize() const
Definition: net.cpp:2750
m_msgproc
Definition: net.h:713
void DeleteNode(CNode *pnode)
Definition: net.cpp:2483
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
Definition: net.h:1105
NetPermissionFlags m_permissions
Definition: net.h:879
bool CheckIncomingNonce(uint64_t nonce)
Definition: net.cpp:411
void CloseSocketDisconnect() EXCLUSIVE_LOCKS_REQUIRED(!m_sock_mutex)
Definition: net.cpp:584
void ThreadOpenConnections(std::vector< std::string > connect) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:1597
Definition: init.h:25
const CAddress addr
Definition: net.h:392
std::atomic< int > nRefCount
Definition: net.h:415
bool Complete() const override
Definition: net.h:301
void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition: net.cpp:1949
bool IsBlockOnlyConn() const
Definition: net.h:444
CDataStream vRecv
Definition: net.h:272
CMessageHeader hdr
Definition: net.h:271
virtual ~TransportSerializer()
Definition: net.h:331
Mutex m_addr_fetches_mutex
Definition: net.h:1008
int flags
Definition: bitcoin-tx.cpp:525
std::atomic< std::chrono::seconds > m_last_send
Definition: net.h:386
std::atomic< NodeId > nLastNodeId
Definition: net.h:1014
Network address.
Definition: netaddress.h:117
std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:2680
256-bit opaque blob.
Definition: uint256.h:119
void RemoveLocal(const CService &addr)
Definition: net.cpp:318
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:686
std::vector< CService > onion_binds
Definition: net.h:689
size_t GetNodeCount(ConnectionDirection) const
Definition: net.cpp:2574
void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
Definition: net.cpp:1386
uint32_t m_raw_message_size
used wire size of the message (including header/checksum)
Definition: net.h:234
void Shuffle(I first, I last, R &&rng)
More efficient than using std::shuffle on a FastRandomContext.
Definition: random.h:271
int nScore
Definition: net.h:178
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
m_use_addrman_outgoing
Definition: net.h:707
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
Definition: net.h:54
int nMaxAddnode
Definition: net.h:676
void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:1399
BanMan * m_banman
Pointer to this node&#39;s banman.
Definition: net.h:1074
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:2796
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:91
CAddress addrBind
Definition: net.h:217
Mutex cs_vRecv
Definition: net.h:376
~CConnman()
Definition: net.cpp:2490
CService resolvedAddress
Definition: net.h:98
std::thread threadOpenConnections
Definition: net.h:1110
bool AttemptToEvictConnection()
Try to find a connection to evict when the node is full.
Definition: net.cpp:890
uint64_t GetTotalBytesSent() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:2738
std::chrono::seconds m_peer_connect_timeout
Definition: net.h:993
int readHeader(Span< const uint8_t > msg_bytes)
Definition: net.cpp:714
CSemaphoreGrant grantOutbound
Definition: net.h:414
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Definition: net.cpp:437
The TransportDeserializer takes care of holding and deserializing the network receive buffer...
Definition: net.h:249
const CChainParams & m_chain_params
Definition: net.h:265
void SocketHandlerConnected(const std::vector< CNode *> &nodes, const Sock::EventsPerSock &events_per_sock) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
Do the read/write for connected sockets that are ready for IO.
Definition: net.cpp:1278
const NodeId id
Definition: net.h:601
NodeId GetNewNodeId()
Definition: net.cpp:2244
CConnman(uint64_t seed0, uint64_t seed1, AddrMan &addrman, const NetGroupManager &netgroupman, bool network_active=true)
Definition: net.cpp:2230
std::string m_type
Definition: net.h:235
std::string addrLocal
Definition: net.h:213
std::atomic< std::chrono::seconds > m_last_recv
Definition: net.h:387
bool fAddressesInitialized
Definition: net.h:1004
std::thread threadDNSAddressSeed
Definition: net.h:1107
ServiceFlags nLocalServices
Definition: net.h:672
uint64_t nMaxOutboundLimit
Definition: net.h:683
bool Start(CScheduler &scheduler, const Options &options) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
Definition: net.cpp:2294
std::vector< std::string > m_added_nodes
Definition: net.h:695
std::vector< ListenSocket > vhListenSocket
Definition: net.h:1002
std::chrono::seconds GetMaxOutboundTimeframe() const
Definition: net.cpp:2675
std::atomic< int > m_greatest_common_version
Definition: net.h:604
CService GetAddrLocal() const EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
Definition: net.cpp:601
Mutex cs_vSend
Definition: net.h:374
std::atomic< int64_t > nTimeOffset
Definition: net.h:390
size_t nSendOffset GUARDED_BY(cs_vSend)
Offset inside the first vSendMsg already sent.
Definition: net.h:371
std::chrono::seconds m_last_block_time
Definition: net.h:195
static constexpr bool DEFAULT_FORCEDNSSEED
Definition: net.h:87
const std::unique_ptr< const TransportSerializer > m_serializer
Definition: net.h:354
nMaxFeeler
Definition: net.h:709
std::atomic_bool fSuccessfullyConnected
fSuccessfullyConnected is set to true on receiving VERACK from the peer.
Definition: net.h:410
SipHash-2-4.
Definition: siphash.h:13
#define AssertLockNotHeld(cs)
Definition: sync.h:148
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:65
static constexpr auto FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes.
Definition: net.h:59
void StopNodes()
Definition: net.cpp:2450
std::atomic< int > nVersion
Definition: net.h:398
nMaxConnections
Definition: net.h:704
Sock::EventsPerSock GenerateWaitSockets(Span< CNode *const > nodes)
Generate a collection of sockets to check for IO readiness.
Definition: net.cpp:1205
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition: net.h:83
const std::string NET_MESSAGE_TYPE_OTHER
Definition: net.cpp:107
static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL
Run the extra block-relay-only connection loop once every 5 minutes.
Definition: net.h:61
uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex)
Definition: net.h:985
std::string ConnectionTypeAsString() const
Definition: net.h:592
ConnectionType
Different types of connections to a peer.
m_added_nodes
Definition: net.h:724
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:81
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:1167
const uint64_t nLocalHostNonce
Definition: net.h:602
unsigned int nSendBufferMaxSize
Definition: net.h:681
std::atomic< bool > m_bip152_highbandwidth_from
Definition: net.h:490
vWhitelistedRange
Definition: net.h:721
void ThreadI2PAcceptIncoming()
Definition: net.cpp:2056
void clear()
Definition: streams.h:243
RAII helper class that manages a socket.
Definition: sock.h:27
std::vector< CNode * > m_nodes_copy
Definition: net.h:1185
CNode(NodeId id, std::shared_ptr< Sock > sock, const CAddress &addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const CAddress &addrBindIn, const std::string &addrNameIn, ConnectionType conn_type_in, bool inbound_onion, CNodeOptions &&node_opts={})
Definition: net.cpp:2752
bool IsAddrFetchConn() const
Definition: net.h:452
std::string m_addr_name
Definition: net.h:198
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
Definition: net.h:52
RAII helper to atomically create a copy of m_nodes and add a reference to each of the nodes...
Definition: net.h:1155
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we&#39;ll relay everything (blocks, tx, addrs, etc)
Definition: net.h:67
void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:2015
nMaxAddnode
Definition: net.h:708
void AcceptConnection(const ListenSocket &hListenSocket)
Definition: net.cpp:933
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:96
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:120
Different type to mark Mutex at global scope.
Definition: sync.h:141
Definition: net.h:139
NodesSnapshot(const CConnman &connman, bool shuffle)
Definition: net.h:1158
Information about a peer.
Definition: net.h:347
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:510
void ForEachNode(const NodeFn &func)
Definition: net.h:756
std::thread threadSocketHandler
Definition: net.h:1108
Simple class for background tasks that should be run periodically or once "after a while"...
Definition: scheduler.h:38
m_onion_binds
Definition: net.h:726
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:325
virtual bool Complete() const =0
std::atomic< std::chrono::microseconds > m_last_ping_time
Last measured round-trip time.
Definition: net.h:519
Network ConnectedThroughNetwork() const
Get network the peer connected through.
Definition: net.cpp:618
V1TransportDeserializer(const CChainParams &chain_params, const NodeId node_id, int nTypeIn, int nVersionIn)
Definition: net.h:292
m_client_interface
Definition: net.h:711
std::chrono::microseconds m_time
time of message receipt
Definition: net.h:232
bool fDiscover
Definition: net.cpp:115
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
Definition: net.h:1080
void SetVersion(int n)
Definition: streams.h:277
bool prefer_evict
Definition: net.h:343
std::atomic< std::chrono::microseconds > m_min_ping_time
Lowest measured round-trip time.
Definition: net.h:523
const NetGroupManager & m_netgroupman
Definition: net.h:1006
std::atomic< uint64_t > nTotalBytesRecv
Definition: net.h:984
int GetCommonVersion() const
Definition: net.h:568
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
const std::string m_addr_name
Definition: net.h:395
std::atomic_bool fPauseRecv
Definition: net.h:418
CNode * AddRef()
Definition: net.h:577
std::unique_ptr< CSemaphore > semAddnode
Definition: net.h:1057
CThreadInterrupt interruptNet
This is signaled when network activity should cease.
Definition: net.h:1098
unsigned int nHdrPos
Definition: net.h:273
ConnectionDirection
Definition: netbase.h:32
bool HasPermission(NetPermissionFlags permission) const
Definition: net.h:406
virtual void SetVersion(int version)=0
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
Definition: net.cpp:285
bool IsInboundConn() const
Definition: net.h:456
const uint64_t nSeed1
Definition: net.h:1083
void Stop()
Definition: net.h:738
bool m_use_addrman_outgoing
Definition: net.h:693
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:687
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:356
size_t nSendSize GUARDED_BY(cs_vSend)
Total size of all vSendMsg entries.
Definition: net.h:369
const std::vector< CNode * > & Nodes() const
Definition: net.h:1179
CHash256 & Reset()
Definition: hash.h:42
nReceiveFloodSize
Definition: net.h:715
std::unique_ptr< i2p::sam::Session > i2p_sam_session
Definition: net.h:342
bool GetUseAddrmanOutgoing() const
Definition: net.h:746
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0...
Definition: net.h:692
virtual CNetMessage GetMessage(std::chrono::microseconds time, bool &reject_message)=0
uint64_t GetOutboundTargetBytesLeft() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
response the bytes left in the current max outbound cycle in case of no limit, it will always respons...
Definition: net.cpp:2723
m_max_outbound_full_relay
Definition: net.h:705
bool m_use_addrman_outgoing
Definition: net.h:1070
Cache responses to addr requests to minimize privacy leak.
Definition: net.h:1023
virtual bool ProcessMessages(CNode *pnode, std::atomic< bool > &interrupt)=0
Process protocol messages received from a given node.
bool IsFullOutboundConn() const
Definition: net.h:436
void CaptureMessageToFile(const CAddress &addr, const std::string &msg_type, Span< const unsigned char > data, bool is_incoming)
Dump binary message to file, with timestamp.
Definition: net.cpp:2863
NodeId nodeid
Definition: net.h:191
We use block-relay-only connections to help prevent against partition attacks.
void CopyStats(CNodeStats &stats) EXCLUSIVE_LOCKS_REQUIRED(!m_subver_mutex
Definition: net.cpp:625
CClientUIInterface * m_client_interface
Definition: net.h:1071
virtual bool SendMessages(CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(pnode -> cs_sendProcessing)=0
Send queued protocol messages to a given node.
CAddress addr
Definition: net.h:215
Message header.
Definition: protocol.h:26
static const std::string DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:79
int64_t m_peer_connect_timeout
Definition: net.h:684
std::string cleanSubVer GUARDED_BY(m_subver_mutex)
cleanSubVer is a sanitized string of the user agent byte array we read from the wire.
Definition: net.h:404