Bitcoin Core  31.0.0
P2P Digital Currency
net.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-present 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 <bip324.h>
10 #include <chainparams.h>
11 #include <common/bloom.h>
12 #include <compat/compat.h>
13 #include <consensus/amount.h>
14 #include <crypto/siphash.h>
15 #include <hash.h>
16 #include <i2p.h>
18 #include <net_permissions.h>
19 #include <netaddress.h>
20 #include <netbase.h>
21 #include <netgroup.h>
22 #include <node/connection_types.h>
23 #include <node/protocol_version.h>
24 #include <policy/feerate.h>
25 #include <protocol.h>
26 #include <random.h>
27 #include <semaphore_grant.h>
28 #include <span.h>
29 #include <streams.h>
30 #include <sync.h>
31 #include <uint256.h>
32 #include <util/check.h>
33 #include <util/sock.h>
34 #include <util/threadinterrupt.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 <optional>
45 #include <queue>
46 #include <string_view>
47 #include <thread>
48 #include <unordered_set>
49 #include <vector>
50 
51 class AddrMan;
52 class BanMan;
53 class CChainParams;
54 class CNode;
55 class CScheduler;
56 struct bilingual_str;
57 
59 static constexpr std::chrono::minutes TIMEOUT_INTERVAL{20};
61 static constexpr auto FEELER_INTERVAL = 2min;
63 static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL = 5min;
65 static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
67 static const unsigned int MAX_SUBVERSION_LENGTH = 256;
71 static const int MAX_ADDNODE_CONNECTIONS = 8;
73 static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS = 2;
75 static const int MAX_FEELER_CONNECTIONS = 1;
77 static constexpr size_t MAX_PRIVATE_BROADCAST_CONNECTIONS{64};
79 static const bool DEFAULT_LISTEN = true;
81 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
83 static const std::string DEFAULT_MAX_UPLOAD_TARGET{"0M"};
85 static const bool DEFAULT_BLOCKSONLY = false;
87 static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
89 static constexpr bool DEFAULT_PRIVATE_BROADCAST{false};
91 static const int NUM_FDS_MESSAGE_CAPTURE = 1;
93 static constexpr std::chrono::hours ASMAP_HEALTH_CHECK_INTERVAL{24};
94 
95 static constexpr bool DEFAULT_FORCEDNSSEED{false};
96 static constexpr bool DEFAULT_DNSSEED{true};
97 static constexpr bool DEFAULT_FIXEDSEEDS{true};
98 static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
99 static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
100 
101 static constexpr bool DEFAULT_V2_TRANSPORT{true};
102 
103 typedef int64_t NodeId;
104 
106  std::string m_added_node;
108 };
109 
114  bool fInbound;
115 };
116 
117 class CNodeStats;
118 class CClientUIInterface;
119 
121  CSerializedNetMsg() = default;
124  // No implicit copying, only moves.
125  CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
127 
129  {
130  CSerializedNetMsg copy;
131  copy.data = data;
132  copy.m_type = m_type;
133  return copy;
134  }
135 
136  std::vector<unsigned char> data;
137  std::string m_type;
138 
140  size_t GetMemoryUsage() const noexcept;
141 };
142 
148 void Discover();
149 
150 uint16_t GetListenPort();
151 
152 enum
153 {
154  LOCAL_NONE, // unknown
155  LOCAL_IF, // address a local interface listens on
156  LOCAL_BIND, // address explicit bound to
157  LOCAL_MAPPED, // address reported by PCP
158  LOCAL_MANUAL, // address explicitly specified (-externalip=)
159 
161 };
162 
164 std::optional<CService> GetLocalAddrForPeer(CNode& node);
165 
166 void ClearLocal();
167 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
168 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
169 void RemoveLocal(const CService& addr);
170 bool SeenLocal(const CService& addr);
171 bool IsLocal(const CService& addr);
172 CService GetLocalAddress(const CNode& peer);
173 
174 extern bool fDiscover;
175 extern bool fListen;
176 
178 extern std::string strSubVersion;
179 
181  int nScore;
182  uint16_t nPort;
183 };
184 
186 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(g_maplocalhost_mutex);
187 
188 extern const std::string NET_MESSAGE_TYPE_OTHER;
189 using mapMsgTypeSize = std::map</* message type */ std::string, /* total bytes */ uint64_t>;
190 
192 {
193 public:
195  std::chrono::seconds m_last_send;
196  std::chrono::seconds m_last_recv;
197  std::chrono::seconds m_last_tx_time;
198  std::chrono::seconds m_last_block_time;
199  std::chrono::seconds m_connected;
200  std::string m_addr_name;
201  int nVersion;
202  std::string cleanSubVer;
203  bool fInbound;
204  // We requested high bandwidth connection to peer
206  // Peer requested high bandwidth connection
209  uint64_t nSendBytes;
211  uint64_t nRecvBytes;
214  std::chrono::microseconds m_last_ping_time;
215  std::chrono::microseconds m_min_ping_time;
216  // Our address, as reported by the peer
217  std::string addrLocal;
218  // Address of this peer
220  // Bind address of our side of the connection
222  // Network the peer connected through
224  uint32_t m_mapped_as;
229  std::string m_session_id;
230 };
231 
232 
238 {
239 public:
241  std::chrono::microseconds m_time{0};
242  uint32_t m_message_size{0};
243  uint32_t m_raw_message_size{0};
244  std::string m_type;
245 
246  explicit CNetMessage(DataStream&& recv_in) : m_recv(std::move(recv_in)) {}
247  // Only one CNetMessage object will exist for the same message on either
248  // the receive or processing queue. For performance reasons we therefore
249  // delete the copy constructor and assignment operator to avoid the
250  // possibility of copying CNetMessage objects.
251  CNetMessage(CNetMessage&&) = default;
252  CNetMessage(const CNetMessage&) = delete;
253  CNetMessage& operator=(CNetMessage&&) = default;
254  CNetMessage& operator=(const CNetMessage&) = delete;
255 
257  size_t GetMemoryUsage() const noexcept;
258 };
259 
261 class Transport {
262 public:
263  virtual ~Transport() = default;
264 
265  struct Info
266  {
268  std::optional<uint256> session_id;
269  };
270 
272  virtual Info GetInfo() const noexcept = 0;
273 
274  // 1. Receiver side functions, for decoding bytes received on the wire into transport protocol
275  // agnostic CNetMessage (message type & payload) objects.
276 
278  virtual bool ReceivedMessageComplete() const = 0;
279 
286  virtual bool ReceivedBytes(std::span<const uint8_t>& msg_bytes) = 0;
287 
295  virtual CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) = 0;
296 
297  // 2. Sending side functions, for converting messages into bytes to be sent over the wire.
298 
305  virtual bool SetMessageToSend(CSerializedNetMsg& msg) noexcept = 0;
306 
314  using BytesToSend = std::tuple<
315  std::span<const uint8_t> /*to_send*/,
316  bool /*more*/,
317  const std::string& /*m_type*/
318  >;
319 
355  virtual BytesToSend GetBytesToSend(bool have_next_message) const noexcept = 0;
356 
363  virtual void MarkBytesSent(size_t bytes_sent) noexcept = 0;
364 
366  virtual size_t GetSendMemoryUsage() const noexcept = 0;
367 
368  // 3. Miscellaneous functions.
369 
371  virtual bool ShouldReconnectV1() const noexcept = 0;
372 };
373 
374 class V1Transport final : public Transport
375 {
376 private:
378  const NodeId m_node_id; // Only for logging
379  mutable Mutex m_recv_mutex;
380  mutable CHash256 hasher GUARDED_BY(m_recv_mutex);
381  mutable uint256 data_hash GUARDED_BY(m_recv_mutex);
382  bool in_data GUARDED_BY(m_recv_mutex); // parsing header (false) or data (true)
383  DataStream hdrbuf GUARDED_BY(m_recv_mutex){}; // partially received header
384  CMessageHeader hdr GUARDED_BY(m_recv_mutex); // complete header
385  DataStream vRecv GUARDED_BY(m_recv_mutex){}; // received message data
386  unsigned int nHdrPos GUARDED_BY(m_recv_mutex);
387  unsigned int nDataPos GUARDED_BY(m_recv_mutex);
388 
389  const uint256& GetMessageHash() const EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
390  int readHeader(std::span<const uint8_t> msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
391  int readData(std::span<const uint8_t> msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
392 
393  void Reset() EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex) {
394  AssertLockHeld(m_recv_mutex);
395  vRecv.clear();
396  hdrbuf.clear();
397  hdrbuf.resize(24);
398  in_data = false;
399  nHdrPos = 0;
400  nDataPos = 0;
401  data_hash.SetNull();
402  hasher.Reset();
403  }
404 
405  bool CompleteInternal() const noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
406  {
407  AssertLockHeld(m_recv_mutex);
408  if (!in_data) return false;
409  return hdr.nMessageSize == nDataPos;
410  }
411 
415  std::vector<uint8_t> m_header_to_send GUARDED_BY(m_send_mutex);
417  CSerializedNetMsg m_message_to_send GUARDED_BY(m_send_mutex);
419  bool m_sending_header GUARDED_BY(m_send_mutex) {false};
421  size_t m_bytes_sent GUARDED_BY(m_send_mutex) {0};
422 
423 public:
424  explicit V1Transport(NodeId node_id) noexcept;
425 
426  bool ReceivedMessageComplete() const override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
427  {
428  AssertLockNotHeld(m_recv_mutex);
429  return WITH_LOCK(m_recv_mutex, return CompleteInternal());
430  }
431 
432  Info GetInfo() const noexcept override;
433 
434  bool ReceivedBytes(std::span<const uint8_t>& msg_bytes) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
435  {
436  AssertLockNotHeld(m_recv_mutex);
437  LOCK(m_recv_mutex);
438  int ret = in_data ? readData(msg_bytes) : readHeader(msg_bytes);
439  if (ret < 0) {
440  Reset();
441  } else {
442  msg_bytes = msg_bytes.subspan(ret);
443  }
444  return ret >= 0;
445  }
446 
447  CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
448 
449  bool SetMessageToSend(CSerializedNetMsg& msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
450  BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
451  void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
452  size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
453  bool ShouldReconnectV1() const noexcept override { return false; }
454 };
455 
456 class V2Transport final : public Transport
457 {
458 private:
462  static constexpr std::array<std::byte, 0> VERSION_CONTENTS = {};
463 
466  static constexpr size_t V1_PREFIX_LEN = 16;
467 
468  // The sender side and receiver side of V2Transport are state machines that are transitioned
469  // through, based on what has been received. The receive state corresponds to the contents of,
470  // and bytes received to, the receive buffer. The send state controls what can be appended to
471  // the send buffer and what can be sent from it.
472 
487  enum class RecvState : uint8_t {
493  KEY_MAYBE_V1,
494 
500  KEY,
501 
508  GARB_GARBTERM,
509 
518  VERSION,
519 
525  APP,
526 
531  APP_READY,
532 
536  V1,
537  };
538 
552  enum class SendState : uint8_t {
559  MAYBE_V1,
560 
566  AWAITING_KEY,
567 
574  READY,
575 
579  V1,
580  };
581 
585  const bool m_initiating;
590 
592  mutable Mutex m_recv_mutex ACQUIRED_BEFORE(m_send_mutex);
595  uint32_t m_recv_len GUARDED_BY(m_recv_mutex) {0};
597  std::vector<uint8_t> m_recv_buffer GUARDED_BY(m_recv_mutex);
599  std::vector<uint8_t> m_recv_aad GUARDED_BY(m_recv_mutex);
601  std::vector<uint8_t> m_recv_decode_buffer GUARDED_BY(m_recv_mutex);
603  RecvState m_recv_state GUARDED_BY(m_recv_mutex);
604 
607  mutable Mutex m_send_mutex ACQUIRED_AFTER(m_recv_mutex);
609  std::vector<uint8_t> m_send_buffer GUARDED_BY(m_send_mutex);
611  uint32_t m_send_pos GUARDED_BY(m_send_mutex) {0};
613  std::vector<uint8_t> m_send_garbage GUARDED_BY(m_send_mutex);
615  std::string m_send_type GUARDED_BY(m_send_mutex);
617  SendState m_send_state GUARDED_BY(m_send_mutex);
619  bool m_sent_v1_header_worth GUARDED_BY(m_send_mutex) {false};
620 
622  void SetReceiveState(RecvState recv_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
624  void SetSendState(SendState send_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex);
626  static std::optional<std::string> GetMessageType(std::span<const uint8_t>& contents) noexcept;
628  size_t GetMaxBytesToProcess() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
630  void StartSendingHandshake() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex);
632  void ProcessReceivedMaybeV1Bytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex, !m_send_mutex);
634  bool ProcessReceivedKeyBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex, !m_send_mutex);
636  bool ProcessReceivedGarbageBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
638  bool ProcessReceivedPacketBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
639 
640 public:
641  static constexpr uint32_t MAX_GARBAGE_LEN = 4095;
642 
648  V2Transport(NodeId nodeid, bool initiating) noexcept;
649 
651  V2Transport(NodeId nodeid, bool initiating, const CKey& key, std::span<const std::byte> ent32, std::vector<uint8_t> garbage) noexcept;
652 
653  // Receive side functions.
654  bool ReceivedMessageComplete() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
655  bool ReceivedBytes(std::span<const uint8_t>& msg_bytes) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex, !m_send_mutex);
656  CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
657 
658  // Send side functions.
659  bool SetMessageToSend(CSerializedNetMsg& msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
660  BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
661  void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
662  size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
663 
664  // Miscellaneous functions.
665  bool ShouldReconnectV1() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex, !m_send_mutex);
666  Info GetInfo() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
667 };
668 
670 {
672  std::unique_ptr<i2p::sam::Session> i2p_sam_session = nullptr;
673  bool prefer_evict = false;
674  size_t recv_flood_size{DEFAULT_MAXRECEIVEBUFFER * 1000};
675  bool use_v2transport = false;
676 };
677 
679 class CNode
680 {
681 public:
684  const std::unique_ptr<Transport> m_transport;
685 
687 
696  std::shared_ptr<Sock> m_sock GUARDED_BY(m_sock_mutex);
697 
699  size_t m_send_memusage GUARDED_BY(cs_vSend){0};
701  uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
703  std::deque<CSerializedNetMsg> vSendMsg GUARDED_BY(cs_vSend);
707 
708  uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
709 
710  std::atomic<std::chrono::seconds> m_last_send{0s};
711  std::atomic<std::chrono::seconds> m_last_recv{0s};
713  const std::chrono::seconds m_connected;
714  // Address of this peer
715  const CAddress addr;
716  // Bind address of our side of the connection
718  const std::string m_addr_name;
720  const std::string m_dest;
722  const bool m_inbound_onion;
723  std::atomic<int> nVersion{0};
729  std::string cleanSubVer GUARDED_BY(m_subver_mutex){};
730  const bool m_prefer_evict{false}; // This peer is preferred for eviction.
731  bool HasPermission(NetPermissionFlags permission) const {
732  return NetPermissions::HasFlag(m_permission_flags, permission);
733  }
735  std::atomic_bool fSuccessfullyConnected{false};
736  // Setting fDisconnect to true will cause the node to be disconnected the
737  // next time DisconnectNodes() runs
738  std::atomic_bool fDisconnect{false};
740  std::atomic<int> nRefCount{0};
741 
742  const uint64_t nKeyedNetGroup;
743  std::atomic_bool fPauseRecv{false};
744  std::atomic_bool fPauseSend{false};
745 
748  const uint64_t m_network_key;
749 
751 
753  void MarkReceivedMsgsForProcessing()
754  EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex);
755 
761  std::optional<std::pair<CNetMessage, bool>> PollMessage()
762  EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex);
763 
765  void AccountForSentBytes(const std::string& msg_type, size_t sent_bytes)
766  EXCLUSIVE_LOCKS_REQUIRED(cs_vSend)
767  {
768  mapSendBytesPerMsgType[msg_type] += sent_bytes;
769  }
770 
772  switch (m_conn_type) {
775  return true;
781  return false;
782  } // no default case, so the compiler can warn about missing cases
783 
784  assert(false);
785  }
786 
787  bool IsFullOutboundConn() const {
788  return m_conn_type == ConnectionType::OUTBOUND_FULL_RELAY;
789  }
790 
791  bool IsManualConn() const {
792  return m_conn_type == ConnectionType::MANUAL;
793  }
794 
796  {
797  switch (m_conn_type) {
803  return false;
806  return true;
807  } // no default case, so the compiler can warn about missing cases
808 
809  assert(false);
810  }
811 
812  bool IsBlockOnlyConn() const {
813  return m_conn_type == ConnectionType::BLOCK_RELAY;
814  }
815 
816  bool IsFeelerConn() const {
817  return m_conn_type == ConnectionType::FEELER;
818  }
819 
820  bool IsAddrFetchConn() const {
821  return m_conn_type == ConnectionType::ADDR_FETCH;
822  }
823 
825  {
826  return m_conn_type == ConnectionType::PRIVATE_BROADCAST;
827  }
828 
829  bool IsInboundConn() const {
830  return m_conn_type == ConnectionType::INBOUND;
831  }
832 
833  bool ExpectServicesFromConn() const {
834  switch (m_conn_type) {
838  return false;
843  return true;
844  } // no default case, so the compiler can warn about missing cases
845 
846  assert(false);
847  }
848 
859  Network ConnectedThroughNetwork() const;
860 
862  [[nodiscard]] bool IsConnectedThroughPrivacyNet() const;
863 
864  // We selected peer as (compact blocks) high-bandwidth peer (BIP152)
865  std::atomic<bool> m_bip152_highbandwidth_to{false};
866  // Peer selected us as (compact blocks) high-bandwidth peer (BIP152)
867  std::atomic<bool> m_bip152_highbandwidth_from{false};
868 
870  std::atomic_bool m_has_all_wanted_services{false};
871 
874  std::atomic_bool m_relays_txs{false};
875 
878  std::atomic_bool m_bloom_filter_loaded{false};
879 
885  std::atomic<std::chrono::seconds> m_last_block_time{0s};
886 
891  std::atomic<std::chrono::seconds> m_last_tx_time{0s};
892 
894  std::atomic<std::chrono::microseconds> m_last_ping_time{0us};
895 
898  std::atomic<std::chrono::microseconds> m_min_ping_time{std::chrono::microseconds::max()};
899 
900  CNode(NodeId id,
901  std::shared_ptr<Sock> sock,
902  const CAddress& addrIn,
903  uint64_t nKeyedNetGroupIn,
904  uint64_t nLocalHostNonceIn,
905  const CService& addrBindIn,
906  const std::string& addrNameIn,
907  ConnectionType conn_type_in,
908  bool inbound_onion,
909  uint64_t network_key,
910  CNodeOptions&& node_opts = {});
911  CNode(const CNode&) = delete;
912  CNode& operator=(const CNode&) = delete;
913 
914  NodeId GetId() const {
915  return id;
916  }
917 
918  uint64_t GetLocalNonce() const {
919  return nLocalHostNonce;
920  }
921 
922  int GetRefCount() const
923  {
924  assert(nRefCount >= 0);
925  return nRefCount;
926  }
927 
937  bool ReceiveMsgBytes(std::span<const uint8_t> msg_bytes, bool& complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv);
938 
939  void SetCommonVersion(int greatest_common_version)
940  {
941  Assume(m_greatest_common_version == INIT_PROTO_VERSION);
942  m_greatest_common_version = greatest_common_version;
943  }
944  int GetCommonVersion() const
945  {
946  return m_greatest_common_version;
947  }
948 
949  CService GetAddrLocal() const EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex);
951  void SetAddrLocal(const CService& addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex);
952 
953  CNode* AddRef()
954  {
955  nRefCount++;
956  return this;
957  }
958 
959  void Release()
960  {
961  nRefCount--;
962  }
963 
964  void CloseSocketDisconnect() EXCLUSIVE_LOCKS_REQUIRED(!m_sock_mutex);
965 
966  void CopyStats(CNodeStats& stats) EXCLUSIVE_LOCKS_REQUIRED(!m_subver_mutex, !m_addr_local_mutex, !cs_vSend, !cs_vRecv);
967 
969 
976  std::string LogIP(bool log_ip) const;
977 
984  std::string DisconnectMsg(bool log_ip) const;
985 
987  void PongReceived(std::chrono::microseconds ping_time) {
988  m_last_ping_time = ping_time;
989  m_min_ping_time = std::min(m_min_ping_time.load(), ping_time);
990  }
991 
992 private:
993  const NodeId id;
994  const uint64_t nLocalHostNonce;
995  std::atomic<int> m_greatest_common_version{INIT_PROTO_VERSION};
996 
997  const size_t m_recv_flood_size;
998  std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
999 
1001  std::list<CNetMessage> m_msg_process_queue GUARDED_BY(m_msg_process_queue_mutex);
1002  size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex){0};
1003 
1004  // Our address, as reported by the peer
1005  CService m_addr_local GUARDED_BY(m_addr_local_mutex);
1007 
1008  mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend);
1009  mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv);
1010 
1021  std::unique_ptr<i2p::sam::Session> m_i2p_sam_session GUARDED_BY(m_sock_mutex);
1022 };
1023 
1028 {
1029 public:
1032 
1034  virtual void InitializeNode(const CNode& node, ServiceFlags our_services) = 0;
1035 
1037  virtual void FinalizeNode(const CNode& node) = 0;
1038 
1043  virtual bool HasAllDesirableServiceFlags(ServiceFlags services) const = 0;
1044 
1052  virtual bool ProcessMessages(CNode& node, std::atomic<bool>& interrupt) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) = 0;
1053 
1060  virtual bool SendMessages(CNode& node) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) = 0;
1061 
1062 
1063 protected:
1068  ~NetEventsInterface() = default;
1069 };
1070 
1072 {
1073 public:
1074 
1075  struct Options
1076  {
1077  ServiceFlags m_local_services = NODE_NONE;
1078  int m_max_automatic_connections = 0;
1080  NetEventsInterface* m_msgproc = nullptr;
1081  BanMan* m_banman = nullptr;
1082  unsigned int nSendBufferMaxSize = 0;
1083  unsigned int nReceiveFloodSize = 0;
1084  uint64_t nMaxOutboundLimit = 0;
1085  int64_t m_peer_connect_timeout = DEFAULT_PEER_CONNECT_TIMEOUT;
1086  std::vector<std::string> vSeedNodes;
1087  std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
1088  std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
1089  std::vector<NetWhitebindPermissions> vWhiteBinds;
1090  std::vector<CService> vBinds;
1091  std::vector<CService> onion_binds;
1095  bool m_use_addrman_outgoing = true;
1096  std::vector<std::string> m_specified_outgoing;
1097  std::vector<std::string> m_added_nodes;
1099  bool whitelist_forcerelay = DEFAULT_WHITELISTFORCERELAY;
1100  bool whitelist_relay = DEFAULT_WHITELISTRELAY;
1101  bool m_capture_messages = false;
1102  };
1103 
1104  void Init(const Options& connOptions) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex, !m_total_bytes_sent_mutex)
1105  {
1106  AssertLockNotHeld(m_total_bytes_sent_mutex);
1107 
1108  m_local_services = connOptions.m_local_services;
1109  m_max_automatic_connections = connOptions.m_max_automatic_connections;
1110  m_max_outbound_full_relay = std::min(MAX_OUTBOUND_FULL_RELAY_CONNECTIONS, m_max_automatic_connections);
1111  m_max_outbound_block_relay = std::min(MAX_BLOCK_RELAY_ONLY_CONNECTIONS, m_max_automatic_connections - m_max_outbound_full_relay);
1112  m_max_automatic_outbound = m_max_outbound_full_relay + m_max_outbound_block_relay + m_max_feeler;
1113  m_max_inbound = std::max(0, m_max_automatic_connections - m_max_automatic_outbound);
1114  m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
1115  m_client_interface = connOptions.uiInterface;
1116  m_banman = connOptions.m_banman;
1117  m_msgproc = connOptions.m_msgproc;
1118  nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
1119  nReceiveFloodSize = connOptions.nReceiveFloodSize;
1120  m_peer_connect_timeout = std::chrono::seconds{connOptions.m_peer_connect_timeout};
1121  {
1122  LOCK(m_total_bytes_sent_mutex);
1123  nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
1124  }
1125  vWhitelistedRangeIncoming = connOptions.vWhitelistedRangeIncoming;
1126  vWhitelistedRangeOutgoing = connOptions.vWhitelistedRangeOutgoing;
1127  {
1128  LOCK(m_added_nodes_mutex);
1129  // Attempt v2 connection if we support v2 - we'll reconnect with v1 if our
1130  // peer doesn't support it or immediately disconnects us for another reason.
1131  const bool use_v2transport(GetLocalServices() & NODE_P2P_V2);
1132  for (const std::string& added_node : connOptions.m_added_nodes) {
1133  m_added_node_params.push_back({added_node, use_v2transport});
1134  }
1135  }
1136  m_onion_binds = connOptions.onion_binds;
1137  whitelist_forcerelay = connOptions.whitelist_forcerelay;
1138  whitelist_relay = connOptions.whitelist_relay;
1139  m_capture_messages = connOptions.m_capture_messages;
1140  }
1141 
1142  // test only
1143  void SetCaptureMessages(bool cap) { m_capture_messages = cap; }
1144 
1145  CConnman(uint64_t seed0,
1146  uint64_t seed1,
1147  AddrMan& addrman,
1148  const NetGroupManager& netgroupman,
1149  const CChainParams& params,
1150  bool network_active = true,
1151  std::shared_ptr<CThreadInterrupt> interrupt_net = std::make_shared<CThreadInterrupt>());
1152 
1153  ~CConnman();
1154 
1155  bool Start(CScheduler& scheduler, const Options& options) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !m_added_nodes_mutex, !m_addr_fetches_mutex, !mutexMsgProc);
1156 
1157  void StopThreads();
1158  void StopNodes() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex);
1159  void Stop() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex)
1160  {
1161  AssertLockNotHeld(m_reconnections_mutex);
1162  StopThreads();
1163  StopNodes();
1164  };
1165 
1166  void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);
1167  bool GetNetworkActive() const { return fNetworkActive; };
1168  bool GetUseAddrmanOutgoing() const { return m_use_addrman_outgoing; };
1169  void SetNetworkActive(bool active);
1170 
1183  bool OpenNetworkConnection(const CAddress& addrConnect,
1184  bool fCountFailure,
1185  CountingSemaphoreGrant<>&& grant_outbound,
1186  const char* pszDest,
1187  ConnectionType conn_type,
1188  bool use_v2transport,
1189  const std::optional<Proxy>& proxy_override = std::nullopt)
1190  EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex);
1191 
1194  {
1195  public:
1204  std::atomic_bool m_outbound_tor_ok_at_least_once{false};
1205 
1210  std::counting_semaphore<> m_sem_conn_max{MAX_PRIVATE_BROADCAST_CONNECTIONS};
1211 
1221  std::optional<Network> PickNetwork(std::optional<Proxy>& proxy) const;
1222 
1224  size_t NumToOpen() const;
1225 
1231  void NumToOpenAdd(size_t n);
1232 
1239  size_t NumToOpenSub(size_t n);
1240 
1242  void NumToOpenWait() const;
1243 
1244  protected:
1250  std::optional<Proxy> ProxyForIPv4or6() const;
1251 
1253  std::atomic_size_t m_num_to_open{0};
1254 
1255  friend struct ConnmanTestMsg;
1257 
1258  bool CheckIncomingNonce(uint64_t nonce);
1259  void ASMapHealthCheck();
1260 
1261  // alias for thread safety annotations only, not defined
1263 
1264  bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
1265 
1267 
1268  using NodeFn = std::function<void(CNode*)>;
1269  void ForEachNode(const NodeFn& func)
1270  {
1272  for (auto&& node : m_nodes) {
1273  if (NodeFullyConnected(node))
1274  func(node);
1275  }
1276  };
1277 
1278  void ForEachNode(const NodeFn& func) const
1279  {
1281  for (auto&& node : m_nodes) {
1282  if (NodeFullyConnected(node))
1283  func(node);
1284  }
1285  };
1286 
1287  // Addrman functions
1299  std::vector<CAddress> GetAddressesUnsafe(size_t max_addresses, size_t max_pct, std::optional<Network> network, bool filtered = true) const;
1314  std::vector<CAddress> GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct);
1315 
1316  // This allows temporarily exceeding m_max_outbound_full_relay, with the goal of finding
1317  // a peer that is better than all our current peers.
1318  void SetTryNewOutboundPeer(bool flag);
1319  bool GetTryNewOutboundPeer() const;
1320 
1322 
1323  // Count the number of full-relay peer we have.
1324  int GetFullOutboundConnCount() const;
1325  // Return the number of outbound peers we have in excess of our target (eg,
1326  // if we previously called SetTryNewOutboundPeer(true), and have since set
1327  // to false, we may have extra peers that we wish to disconnect). This may
1328  // return a value less than (num_outbound_connections - num_outbound_slots)
1329  // in cases where some outbound connections are not yet fully connected, or
1330  // not yet fully disconnected.
1331  int GetExtraFullOutboundCount() const;
1332  // Count the number of block-relay-only peers we have over our limit.
1333  int GetExtraBlockRelayCount() const;
1334 
1338  std::vector<AddedNodeInfo> GetAddedNodeInfo(bool include_connected) const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1339 
1353  bool AddConnection(const std::string& address, ConnectionType conn_type, bool use_v2transport) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex);
1354 
1355  size_t GetNodeCount(ConnectionDirection) const;
1356  std::map<CNetAddr, LocalServiceInfo> getNetLocalAddresses() const;
1357  uint32_t GetMappedAS(const CNetAddr& addr) const;
1358  void GetNodeStats(std::vector<CNodeStats>& vstats) const;
1359  bool DisconnectNode(std::string_view node);
1360  bool DisconnectNode(const CSubNet& subnet);
1361  bool DisconnectNode(const CNetAddr& addr);
1362  bool DisconnectNode(NodeId id);
1363 
1371 
1376 
1378  std::chrono::seconds GetMaxOutboundTimeframe() const;
1379 
1383  bool OutboundTargetReached(bool historicalBlockServingLimit) const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1384 
1388 
1390 
1391  uint64_t GetTotalBytesRecv() const;
1393 
1395  CSipHasher GetDeterministicRandomizer(uint64_t id) const;
1396 
1398 
1400  bool ShouldRunInactivityChecks(const CNode& node, std::chrono::microseconds now) const;
1401 
1403 
1404 private:
1405  struct ListenSocket {
1406  public:
1407  std::shared_ptr<Sock> sock;
1409  ListenSocket(std::shared_ptr<Sock> sock_, NetPermissionFlags permissions_)
1410  : sock{sock_}, m_permissions{permissions_}
1411  {
1412  }
1413 
1414  private:
1416  };
1417 
1421 
1422  bool BindListenPort(const CService& bindAddr, bilingual_str& strError, NetPermissionFlags permissions);
1423  bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions);
1424  bool InitBinds(const Options& options);
1425 
1427  void AddAddrFetch(const std::string& strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex);
1431  void ThreadI2PAcceptIncoming();
1433  void AcceptConnection(const ListenSocket& hListenSocket);
1434 
1443  void CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock,
1444  NetPermissionFlags permission_flags,
1445  const CService& addr_bind,
1446  const CService& addr);
1447 
1451  bool InactivityCheck(const CNode& node, std::chrono::microseconds now) const;
1452 
1458  Sock::EventsPerSock GenerateWaitSockets(std::span<CNode* const> nodes);
1459 
1464 
1470  void SocketHandlerConnected(const std::vector<CNode*>& nodes,
1471  const Sock::EventsPerSock& events_per_sock)
1473 
1478  void SocketHandlerListening(const Sock::EventsPerSock& events_per_sock);
1479 
1482 
1483  uint64_t CalculateKeyedNetGroup(const CNetAddr& ad) const;
1484 
1492  bool AlreadyConnectedToHost(std::string_view host) const;
1493 
1501  bool AlreadyConnectedToAddressPort(const CService& addr_port) const;
1502 
1506  bool AlreadyConnectedToAddress(const CNetAddr& addr) const;
1507 
1508  bool AttemptToEvictConnection();
1509 
1520  CNode* ConnectNode(CAddress addrConnect,
1521  const char* pszDest,
1522  bool fCountFailure,
1523  ConnectionType conn_type,
1524  bool use_v2transport,
1525  const std::optional<Proxy>& proxy_override)
1527 
1528  void AddWhitelistPermissionFlags(NetPermissionFlags& flags, std::optional<CNetAddr> addr, const std::vector<NetWhitelistPermissions>& ranges) const;
1529 
1530  void DeleteNode(CNode* pnode);
1531 
1532  NodeId GetNewNodeId();
1533 
1535  std::pair<size_t, bool> SocketSendData(CNode& node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend);
1536 
1537  void DumpAddresses();
1538 
1539  // Network stats
1540  void RecordBytesRecv(uint64_t bytes);
1542 
1547  std::unordered_set<Network> GetReachableEmptyNetworks() const;
1548 
1552  std::vector<CAddress> GetCurrentBlockRelayOnlyConns() const;
1553 
1564  bool MaybePickPreferredNetwork(std::optional<Network>& network);
1565 
1566  // Whether the node should be passed out in ForEach* callbacks
1567  static bool NodeFullyConnected(const CNode* pnode);
1568 
1569  uint16_t GetDefaultPort(Network net) const;
1570  uint16_t GetDefaultPort(const std::string& addr) const;
1571 
1572  // Network usage totals
1574  std::atomic<uint64_t> nTotalBytesRecv{0};
1575  uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex) {0};
1576 
1577  // outbound limit & stats
1578  uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex) {0};
1579  std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex) {0};
1581 
1582  // P2P timeout in seconds
1583  std::chrono::seconds m_peer_connect_timeout;
1584 
1585  // Whitelisted ranges. Any node connecting from these is automatically
1586  // whitelisted (as well as those connecting to whitelisted binds).
1587  std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
1588  // Whitelisted ranges for outgoing connections.
1589  std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
1590 
1591  unsigned int nSendBufferMaxSize{0};
1592  unsigned int nReceiveFloodSize{0};
1593 
1594  std::vector<ListenSocket> vhListenSocket;
1595  std::atomic<bool> fNetworkActive{true};
1597  std::reference_wrapper<AddrMan> addrman;
1599  std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
1601 
1602  // connection string and whether to use v2 p2p
1603  std::vector<AddedNodeParams> m_added_node_params GUARDED_BY(m_added_nodes_mutex);
1604 
1606  std::vector<CNode*> m_nodes GUARDED_BY(m_nodes_mutex);
1607  std::list<CNode*> m_nodes_disconnected;
1609  std::atomic<NodeId> nLastNodeId{0};
1610  unsigned int nPrevNodeCount{0};
1611 
1612  // Stores number of full-tx connections (outbound and manual) per network
1613  std::array<unsigned int, Network::NET_MAX> m_network_conn_counts GUARDED_BY(m_nodes_mutex) = {};
1614 
1622  std::vector<CAddress> m_addrs_response_cache;
1623  std::chrono::microseconds m_cache_entry_expiration{0};
1624  };
1625 
1640  std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
1641 
1653  std::atomic<ServiceFlags> m_local_services;
1654 
1655  std::unique_ptr<std::counting_semaphore<>> semOutbound;
1656  std::unique_ptr<std::counting_semaphore<>> semAddnode;
1657 
1664 
1665  /*
1666  * Maximum number of peers by connection type. Might vary from defaults
1667  * based on -maxconnections init value.
1668  */
1669 
1670  // How many full-relay (tx, block, addr) outbound peers we want
1672 
1673  // How many block-relay only outbound peers we want
1674  // We do not relay tx or addr messages with these peers
1676 
1677  int m_max_addnode{MAX_ADDNODE_CONNECTIONS};
1678  int m_max_feeler{MAX_FEELER_CONNECTIONS};
1681 
1687 
1692  std::vector<CAddress> m_anchors;
1693 
1695  const uint64_t nSeed0, nSeed1;
1696 
1698  bool fMsgProcWake GUARDED_BY(mutexMsgProc);
1699 
1700  std::condition_variable condMsgProc;
1702  std::atomic<bool> flagInterruptMsgProc{false};
1703 
1708  const std::shared_ptr<CThreadInterrupt> m_interrupt_net;
1709 
1715  std::unique_ptr<i2p::sam::Session> m_i2p_sam_session;
1716 
1718  std::thread threadSocketHandler;
1724 
1729 
1734  std::atomic_bool m_start_extra_block_relay_peers{false};
1735 
1740  std::vector<CService> m_onion_binds;
1741 
1747 
1753 
1757  bool m_capture_messages{false};
1758 
1763 
1771  std::queue<std::unique_ptr<i2p::sam::Session>> m_unused_i2p_sessions GUARDED_BY(m_unused_i2p_sessions_mutex);
1772 
1777 
1780  {
1783  std::string destination;
1786  };
1787 
1791  std::list<ReconnectionInfo> m_reconnections GUARDED_BY(m_reconnections_mutex);
1792 
1794  void PerformReconnections() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex, !m_unused_i2p_sessions_mutex);
1795 
1800  static constexpr size_t MAX_UNUSED_I2P_SESSIONS_SIZE{10};
1801 
1807  {
1808  public:
1809  explicit NodesSnapshot(const CConnman& connman, bool shuffle)
1810  {
1811  {
1812  LOCK(connman.m_nodes_mutex);
1813  m_nodes_copy = connman.m_nodes;
1814  for (auto& node : m_nodes_copy) {
1815  node->AddRef();
1816  }
1817  }
1818  if (shuffle) {
1819  std::shuffle(m_nodes_copy.begin(), m_nodes_copy.end(), FastRandomContext{});
1820  }
1821  }
1822 
1824  {
1825  for (auto& node : m_nodes_copy) {
1826  node->Release();
1827  }
1828  }
1829 
1830  const std::vector<CNode*>& Nodes() const
1831  {
1832  return m_nodes_copy;
1833  }
1834 
1835  private:
1836  std::vector<CNode*> m_nodes_copy;
1837  };
1838 
1840 
1841  friend struct ConnmanTestMsg;
1842 };
1843 
1845 extern std::function<void(const CAddress& addr,
1846  const std::string& msg_type,
1847  std::span<const unsigned char> data,
1848  bool is_incoming)>
1850 
1851 #endif // BITCOIN_NET_H
std::thread threadPrivateBroadcast
Definition: net.h:1723
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition: net.h:1031
std::chrono::microseconds m_min_ping_time
Definition: net.h:215
std::vector< CService > vBinds
Definition: net.h:1090
bool ShouldRunInactivityChecks(const CNode &node, std::chrono::microseconds now) const
Return true if we should disconnect the peer for failing an inactivity check.
Definition: net.cpp:2003
std::vector< CAddress > m_addrs_response_cache
Definition: net.h:1622
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:73
Mutex m_send_mutex
Lock for sending state.
Definition: net.h:413
static constexpr bool DEFAULT_PRIVATE_BROADCAST
Default for -privatebroadcast.
Definition: net.h:89
std::string m_type
Definition: net.h:137
const std::string m_dest
The pszDest argument provided to ConnectNode().
Definition: net.h:720
int ret
AddrFetch connections are short lived connections used to solicit addresses from peers.
std::reference_wrapper< AddrMan > addrman
Definition: net.h:1597
CNetMessage(DataStream &&recv_in)
Definition: net.h:246
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:65
BIP324Cipher m_cipher
Cipher state.
Definition: net.h:583
bool m_i2p_accept_incoming
Definition: net.h:1098
size_t m_bytes_sent GUARDED_BY(m_send_mutex)
How many bytes have been sent so far (from m_header_to_send, or from m_message_to_send.data).
Definition: net.h:421
Mutex m_addr_local_mutex
Definition: net.h:1006
AssertLockHeld(pool.cs)
void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:2255
std::atomic< bool > fNetworkActive
Definition: net.h:1595
mapMsgTypeSize mapSendBytesPerMsgType
Definition: net.h:210
Definition: banman.h:63
static void AddFlag(NetPermissionFlags &flags, NetPermissionFlags f)
ServiceFlags
nServices flags
Definition: protocol.h:309
ConnectionType conn_type
Definition: net.h:1784
CClientUIInterface uiInterface
bool AddedNodesContain(const CAddress &addr) const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:3758
Inbound connections are those initiated by a peer.
assert(!tx.IsCoinBase())
bool fListen
Definition: net.cpp:117
uint32_t m_mapped_as
Definition: net.h:224
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:2092
Unencrypted, plaintext protocol.
unsigned int nonce
Definition: miner_tests.cpp:82
const uint64_t m_network_key
Network key used to prevent fingerprinting our node across networks.
Definition: net.h:748
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
Definition: net.cpp:3406
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:3911
Feeler connections are short-lived connections made to check that a node is alive.
Mutex m_total_bytes_sent_mutex
Definition: net.h:1573
RecursiveMutex & GetNodesMutex() const LOCK_RETURNED(m_nodes_mutex)
std::shared_ptr< Sock > sock
Definition: net.h:1407
bool m_sending_header GUARDED_BY(m_send_mutex)
Whether we&#39;re currently sending header bytes or message bytes.
Definition: net.h:419
std::list< CNode * > m_nodes_disconnected
Definition: net.h:1607
Bilingual messages:
Definition: translation.h:24
size_t m_send_memusage GUARDED_BY(cs_vSend)
Sum of GetMemoryUsage of all vSendMsg entries.
Definition: net.h:699
Mutex mutexMsgProc
Definition: net.h:1701
const uint64_t nKeyedNetGroup
Definition: net.h:742
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:318
constexpr bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
std::map< std::string, uint64_t > mapMsgTypeSize
Definition: net.h:189
int m_max_automatic_outbound
Definition: net.h:1679
bool IsOutboundOrBlockRelayConn() const
Definition: net.h:771
const std::chrono::seconds m_connected
Unix epoch time at peer connection.
Definition: net.h:713
int m_max_automatic_connections
Maximum number of automatic connections permitted, excluding manual connections but including inbound...
Definition: net.h:1663
std::vector< unsigned char > data
Definition: net.h:136
AddedNodeParams m_params
Definition: net.h:111
const ConnectionType m_conn_type
Definition: net.h:750
uint64_t GetTotalBytesRecv() const
Definition: net.cpp:3942
uint32_t m_send_pos GUARDED_BY(m_send_mutex)
How many bytes from the send buffer have been sent so far.
Definition: net.h:611
std::unordered_set< Network > GetReachableEmptyNetworks() const
Return reachable networks for which we have no addresses in addrman and therefore may require loadin...
Definition: net.cpp:2490
std::string destination
Definition: net.h:1783
bool IsFeelerConn() const
Definition: net.h:816
uint16_t GetListenPort()
Definition: net.cpp:138
int m_max_outbound_full_relay
Definition: net.h:1671
std::vector< AddedNodeInfo > GetAddedNodeInfo(bool include_connected) const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2909
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:1740
DataStream hdrbuf GUARDED_BY(m_recv_mutex)
Definition: net.h:383
#define LOCK_RETURNED(x)
Definition: threadsafety.h:49
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:79
void SetCommonVersion(int greatest_common_version)
Definition: net.h:939
Interrupt(node)
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:71
void AddLocalServices(ServiceFlags services)
Updates the local services that this node advertises to other peers during connection handshake...
Definition: net.h:1374
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
Definition: net.cpp:3274
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
Definition: net.cpp:240
std::string cleanSubVer
Definition: net.h:202
Interface for message handling.
Definition: net.h:1027
const std::string KEY
Definition: walletdb.cpp:44
void ThreadPrivateBroadcast() EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Definition: net.cpp:3206
static const unsigned char VERSION[]
Definition: netaddress.cpp:188
static constexpr size_t MAX_PRIVATE_BROADCAST_CONNECTIONS
Maximum number of private broadcast connections.
Definition: net.h:77
NetEventsInterface * m_msgproc
Definition: net.h:1684
CountingSemaphoreGrant grantOutbound
Definition: net.h:739
const NodeId m_nodeid
NodeId (for debug logging).
Definition: net.h:587
Definition: common.h:29
CSerializedNetMsg()=default
TransportProtocolType
Transport layer version.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:76
bool InactivityCheck(const CNode &node, std::chrono::microseconds now) const
Return true if the peer is inactive and should be disconnected.
Definition: net.cpp:2008
void ForEachNode(const NodeFn &func) const
Definition: net.h:1278
int m_max_outbound_block_relay
Definition: net.h:1675
Mutex m_subver_mutex
Definition: net.h:724
void DisconnectNodes() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex
Definition: net.cpp:1909
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:3896
void SetTryNewOutboundPeer(bool flag)
Definition: net.cpp:2431
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:196
size_t GetMemoryUsage() const noexcept
Compute total memory usage of this object (own memory + any dynamic memory).
Definition: net.cpp:122
void RecordBytesSent(uint64_t bytes) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:3859
static const int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
uint64_t GetLocalNonce() const
Definition: net.h:918
Sock::EventsPerSock GenerateWaitSockets(std::span< CNode *const > nodes)
Generate a collection of sockets to check for IO readiness.
Definition: net.cpp:2061
bool m_sent_v1_header_worth GUARDED_BY(m_send_mutex)
Whether we&#39;ve sent at least 24 bytes (which would trigger disconnect for V1 peers).
Definition: net.h:619
NetPermissionFlags
V1Transport m_v1_fallback
Encapsulate a V1Transport to fall back to.
Definition: net.h:589
ConnectionType m_conn_type
Definition: net.h:225
These are the default connections that we use to connect with the network.
DataStream vRecv GUARDED_BY(m_recv_mutex)
Definition: net.h:385
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Total number of bytes sent on the wire to this peer.
Definition: net.h:701
Netgroup manager.
Definition: netgroup.h:17
The BIP324 packet cipher, encapsulating its key derivation, stream cipher, and AEAD.
Definition: bip324.h:19
void GetNodeStats(std::vector< CNodeStats > &vstats) const
Definition: net.cpp:3797
Definition: net.h:160
bool AlreadyConnectedToAddressPort(const CService &addr_port) const
Determine whether we&#39;re already connected to a given address:port.
Definition: net.cpp:341
bool MultipleManualOrFullOutboundConns(Network net) const EXCLUSIVE_LOCKS_REQUIRED(m_nodes_mutex)
Definition: net.cpp:2503
Signals for UI communication.
Definition: interface_ui.h:25
std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex)
Definition: net.h:1579
static constexpr std::chrono::minutes TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:59
std::list< CNetMessage > vRecvMsg
Definition: net.h:998
const NodeId m_node_id
Definition: net.h:378
bool GetTryNewOutboundPeer() const
Definition: net.cpp:2426
void NotifyNumConnectionsChanged()
Definition: net.cpp:1988
SendState
State type that controls the sender side.
Definition: net.h:552
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:1640
uint64_t GetMaxOutboundTarget() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:3877
void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:2405
#define ACQUIRED_AFTER(...)
Definition: threadsafety.h:41
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition: net.h:75
static bool HasFlag(NetPermissionFlags flags, NetPermissionFlags f)
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition: net.h:1587
Stochastic address manager.
Definition: addrman.h:88
bool fConnected
Definition: net.h:113
void SetCaptureMessages(bool cap)
Definition: net.h:1143
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition: net.h:1408
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:4118
int GetRefCount() const
Definition: net.h:922
NetPermissionFlags m_permission_flags
Definition: net.h:213
Definition: init.h:12
std::unique_ptr< std::counting_semaphore<> > semAddnode
Definition: net.h:1656
Mutex m_unused_i2p_sessions_mutex
Mutex protecting m_i2p_sam_sessions.
Definition: net.h:1762
int GetExtraBlockRelayCount() const
Definition: net.cpp:2476
uint16_t nPort
Definition: net.h:182
TransportProtocolType m_transport_type
Transport protocol type.
Definition: net.h:227
void RecordBytesRecv(uint64_t bytes)
Definition: net.cpp:3854
std::array< uint8_t, 4 > MessageStartChars
void DumpAddresses()
Definition: net.cpp:2395
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:98
Mutex m_sock_mutex
Definition: net.h:705
std::thread threadI2PAcceptIncoming
Definition: net.h:1722
bool CompleteInternal() const noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Definition: net.h:405
DataStream m_recv
received message data
Definition: net.h:240
CService GetLocalAddress(const CNode &peer)
Definition: net.cpp:220
int nVersion
Definition: net.h:201
nMaxOutboundLimit
Definition: net.h:1123
CSerializedNetMsg Copy() const
Definition: net.h:128
int m_max_inbound
Definition: net.h:1680
CountingSemaphoreGrant grant
Definition: net.h:1782
std::optional< uint256 > session_id
Definition: net.h:268
ListenSocket(std::shared_ptr< Sock > sock_, NetPermissionFlags permissions_)
Definition: net.h:1409
void Release()
Definition: net.h:959
static bool NodeFullyConnected(const CNode *pnode)
Definition: net.cpp:4042
unsigned int nPrevNodeCount
Definition: net.h:1610
std::map< CNetAddr, LocalServiceInfo > getNetLocalAddresses() const
Definition: net.cpp:3786
constexpr bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
std::condition_variable condMsgProc
Definition: net.h:1700
const std::unique_ptr< Transport > m_transport
Transport serializer/deserializer.
Definition: net.h:684
std::chrono::seconds m_connected
Definition: net.h:199
bool IsManualOrFullOutboundConn() const
Definition: net.h:795
Mutex m_added_nodes_mutex
Definition: net.h:1605
GlobalMutex g_maplocalhost_mutex
Definition: net.cpp:118
We open manual connections to addresses that users explicitly requested via the addnode RPC or the -a...
int m_starting_height
Definition: net.h:208
std::thread threadOpenAddedConnections
Definition: net.h:1719
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
#define LOCK(cs)
Definition: sync.h:258
void StartExtraBlockRelayPeers()
Definition: net.cpp:2437
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:132
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition: net.h:1087
const CService addrBind
Definition: net.h:717
ServiceFlags GetLocalServices() const
Used to convey which local services we are offering peers during node connection. ...
Definition: net.cpp:3954
std::function< void(CNode *)> NodeFn
Definition: net.h:1268
std::string m_added_node
Definition: net.h:106
void SocketHandlerListening(const Sock::EventsPerSock &events_per_sock)
Accept incoming connections, one from each read-ready listening socket.
Definition: net.cpp:2222
TransportProtocolType transport_type
Definition: net.h:267
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:529
Fast randomness source.
Definition: random.h:385
Transport protocol agnostic message container.
Definition: net.h:237
bool whitelist_forcerelay
flag for adding &#39;forcerelay&#39; permission to whitelisted inbound and manual peers with default permissi...
Definition: net.h:1746
std::vector< std::string > vSeedNodes
Definition: net.h:1086
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, std::optional< CNetAddr > addr, const std::vector< NetWhitelistPermissions > &ranges) const
Definition: net.cpp:572
std::vector< std::string > m_specified_outgoing
Definition: net.h:1096
bool m_bip152_highbandwidth_from
Definition: net.h:207
uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex)
Definition: net.h:1578
std::thread threadMessageHandler
Definition: net.h:1721
void RemoveLocalServices(ServiceFlags services)
Definition: net.h:1375
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
Definition: net.h:91
const std::shared_ptr< CThreadInterrupt > m_interrupt_net
This is signaled when network activity should cease.
Definition: net.h:1708
nSendBufferMaxSize
Definition: net.h:1118
bool AlreadyConnectedToHost(std::string_view host) const
Determine whether we&#39;re already connected to a given "host:port".
Definition: net.cpp:335
Network m_network
Definition: net.h:223
bool fInbound
Definition: net.h:203
bool IsManualConn() const
Definition: net.h:791
int GetExtraFullOutboundCount() const
Definition: net.cpp:2462
std::chrono::microseconds m_last_ping_time
Definition: net.h:214
A CService with information about it as peer.
Definition: protocol.h:366
std::chrono::seconds m_last_tx_time
Definition: net.h:197
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const
Return vector of current BLOCK_RELAY peers.
Definition: net.cpp:2896
uint64_t nRecvBytes
Definition: net.h:211
bool DisconnectNode(std::string_view node)
Definition: net.cpp:3809
static constexpr bool DEFAULT_FIXEDSEEDS
Definition: net.h:97
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(g_maplocalhost_mutex)
bool fInbound
Definition: net.h:114
Network
A network type.
Definition: netaddress.h:33
bool m_bip152_highbandwidth_to
Definition: net.h:205
bool ExpectServicesFromConn() const
Definition: net.h:833
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:1728
int64_t NodeId
Definition: net.h:103
bool InitBinds(const Options &options)
Definition: net.cpp:3425
void ForEachNode(const Node< Key > &root, Fn &&fn)
Unordered traversal of a miniscript node tree.
Definition: miniscript.h:197
Definition: net.h:1071
void CreateNodeFromAcceptedSocket(std::unique_ptr< Sock > &&sock, NetPermissionFlags permission_flags, const CService &addr_bind, const CService &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:1761
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:81
static constexpr bool DEFAULT_V2_TRANSPORT
Definition: net.h:101
static constexpr bool DEFAULT_DNSSEED
Definition: net.h:96
const CChainParams & m_params
Definition: net.h:1839
Mutex m_recv_mutex
Lock for receive state.
Definition: net.h:379
std::vector< CAddress > GetAddressesUnsafe(size_t max_addresses, size_t max_pct, std::optional< Network > network, bool filtered=true) const
Return randomly selected addresses.
Definition: net.cpp:3683
const bool m_initiating
Whether we are the initiator side.
Definition: net.h:585
const NetPermissionFlags m_permission_flags
Definition: net.h:686
std::chrono::seconds m_last_send
Definition: net.h:195
NodeId GetId() const
Definition: net.h:914
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition: net.cpp:4131
std::vector< CAddress > GetAddresses(CNode &requestor, size_t max_addresses, size_t max_pct)
Return addresses from the per-requestor cache.
Definition: net.cpp:3694
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e. connected via our Tor onion service.
Definition: net.h:722
uint64_t nSendBytes
Definition: net.h:209
void PongReceived(std::chrono::microseconds ping_time)
A ping-pong round trip has completed successfully.
Definition: net.h:987
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type, bool use_v2transport, const std::optional< Proxy > &proxy_override) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Open a new P2P connection.
Definition: net.cpp:372
void AddAddrFetch(const std::string &strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex)
Definition: net.cpp:132
void ASMapHealthCheck()
Definition: net.cpp:4170
mapMsgTypeSize mapRecvBytesPerMsgType
Definition: net.h:212
const bool use_v2transport(GetLocalServices() &NODE_P2P_V2)
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:289
#define Assume(val)
Assume is the identity function.
Definition: check.h:125
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Definition: net.h:708
RecursiveMutex m_nodes_mutex
Definition: net.h:1608
const size_t m_recv_flood_size
Definition: net.h:997
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:3343
static constexpr std::chrono::hours ASMAP_HEALTH_CHECK_INTERVAL
Interval for ASMap Health Check.
Definition: net.h:93
void DeleteNode(CNode *pnode)
Definition: net.cpp:3670
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
Definition: net.h:1715
NetPermissionFlags m_permissions
Definition: net.h:1415
bool CheckIncomingNonce(uint64_t nonce)
Definition: net.cpp:353
Definition: messages.h:21
const CAddress addr
Definition: net.h:715
Definition: netbase.h:58
void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition: net.cpp:2969
bool IsBlockOnlyConn() const
Definition: net.h:812
std::atomic< ServiceFlags > m_local_services
Services this node offers.
Definition: net.h:1653
Mutex m_addr_fetches_mutex
Definition: net.h:1600
int flags
Definition: bitcoin-tx.cpp:529
std::atomic< NodeId > nLastNodeId
Definition: net.h:1609
Network address.
Definition: netaddress.h:112
void ClearLocal()
Definition: net.cpp:270
std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:3889
256-bit opaque blob.
Definition: uint256.h:195
void RemoveLocal(const CService &addr)
Definition: net.cpp:310
std::vector< CService > onion_binds
Definition: net.h:1091
size_t GetNodeCount(ConnectionDirection) const
Definition: net.cpp:3769
void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
Definition: net.cpp:2235
int nScore
Definition: net.h:181
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:51
The Transport converts one connection&#39;s sent messages to wire bytes, and received bytes back...
Definition: net.h:261
void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:2246
BanMan * m_banman
Pointer to this node&#39;s banman.
Definition: net.h:1686
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:4058
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:99
Mutex cs_vRecv
Definition: net.h:706
CService resolvedAddress
Definition: net.h:112
std::thread threadOpenConnections
Definition: net.h:1720
bool AttemptToEvictConnection()
Try to find a connection to evict when the node is full.
Definition: net.cpp:1684
bool IsPrivateBroadcastConn() const
Definition: net.h:824
uint64_t GetTotalBytesSent() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:3947
std::chrono::seconds m_peer_connect_timeout
Definition: net.h:1583
uint32_t GetMappedAS(const CNetAddr &addr) const
Definition: net.cpp:3792
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:2120
class CConnman::PrivateBroadcast m_private_broadcast
const NodeId id
Definition: net.h:993
NodeId GetNewNodeId()
Definition: net.cpp:3390
std::string m_type
Definition: net.h:244
std::string addrLocal
Definition: net.h:217
bool fAddressesInitialized
Definition: net.h:1596
std::thread threadDNSAddressSeed
Definition: net.h:1717
bool MaybePickPreferredNetwork(std::optional< Network > &network)
Search for a "preferred" network, a reachable network to which we currently don&#39;t have any OUTBOUND_F...
Definition: net.cpp:2509
std::unique_ptr< std::counting_semaphore<> > semOutbound
Definition: net.h:1655
#define ACQUIRED_BEFORE(...)
Definition: threadsafety.h:42
Group of private broadcast related members.
Definition: net.h:1193
int GetFullOutboundConnCount() const
Definition: net.cpp:2444
std::vector< std::string > m_added_nodes
Definition: net.h:1097
std::vector< ListenSocket > vhListenSocket
Definition: net.h:1594
std::chrono::seconds GetMaxOutboundTimeframe() const
Definition: net.cpp:3884
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition: net.h:1589
Mutex cs_vSend
Definition: net.h:704
CService addrBind
Definition: net.h:221
std::chrono::seconds m_last_block_time
Definition: net.h:198
std::function< void(const CAddress &addr, const std::string &msg_type, std::span< const unsigned char > data, bool is_incoming)> CaptureMessage
Defaults to CaptureMessageToFile(), but can be overridden by unit tests.
Definition: net.cpp:4224
static constexpr bool DEFAULT_FORCEDNSSEED
Definition: net.h:95
bool AlreadyConnectedToAddress(const CNetAddr &addr) const
Determine whether we&#39;re already connected to a given address.
Definition: net.cpp:347
General SipHash-2-4 implementation.
Definition: siphash.h:26
#define AssertLockNotHeld(cs)
Definition: sync.h:141
std::string m_session_id
BIP324 session id string in hex, if any.
Definition: net.h:229
size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex)
Definition: net.h:1002
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:67
RecvState
State type that defines the current contents of the receive buffer and/or how the next received bytes...
Definition: net.h:487
static constexpr auto FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes.
Definition: net.h:61
bool AddNode(const AddedNodeParams &add) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:3732
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition: net.h:87
const std::string NET_MESSAGE_TYPE_OTHER
Definition: net.cpp:108
static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL
Run the extra block-relay-only connection loop once every 5 minutes.
Definition: net.h:63
uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex)
Definition: net.h:1575
ConnectionType
Different types of connections to a peer.
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:85
const uint64_t nLocalHostNonce
Definition: net.h:994
Mutex m_msg_process_queue_mutex
Definition: net.h:1000
void ThreadI2PAcceptIncoming()
Definition: net.cpp:3163
RAII helper class that manages a socket and closes it automatically when it goes out of scope...
Definition: sock.h:27
std::vector< CNode * > m_nodes_copy
Definition: net.h:1836
Mutex m_reconnections_mutex
Mutex protecting m_reconnections.
Definition: net.h:1776
bool IsAddrFetchConn() const
Definition: net.h:820
std::pair< size_t, bool > SocketSendData(CNode &node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend)
(Try to) send data from node&#39;s vSendMsg.
Definition: net.cpp:1597
Private broadcast connections are short-lived and only opened to privacy networks (Tor...
std::string m_addr_name
Definition: net.h:200
RAII helper to atomically create a copy of m_nodes and add a reference to each of the nodes...
Definition: net.h:1806
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:69
void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:3124
An encapsulated private key.
Definition: key.h:35
void AcceptConnection(const ListenSocket &hListenSocket)
Definition: net.cpp:1733
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:134
Definition: net.h:155
NodesSnapshot(const CConnman &connman, bool shuffle)
Definition: net.h:1809
Information about a peer.
Definition: net.h:679
std::thread threadSocketHandler
Definition: net.h:1718
Simple class for background tasks that should be run periodically or once "after a while"...
Definition: scheduler.h:39
Struct for entries in m_reconnections.
Definition: net.h:1779
m_local_services
Definition: net.h:1108
std::tuple< std::span< const uint8_t >, bool, const std::string &> BytesToSend
Return type for GetBytesToSend, consisting of:
Definition: net.h:318
bool fDiscover
Definition: net.cpp:116
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
Definition: net.h:1692
uint64_t CalculateKeyedNetGroup(const CNetAddr &ad) const
Definition: net.cpp:4136
bool m_use_v2transport
Definition: net.h:107
const NetGroupManager & m_netgroupman
Definition: net.h:1598
std::atomic< uint64_t > nTotalBytesRecv
Definition: net.h:1574
int GetCommonVersion() const
Definition: net.h:944
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
const std::string m_addr_name
Definition: net.h:718
const MessageStartChars m_magic_bytes
Definition: net.h:377
bool ReceivedMessageComplete() const override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Returns true if the current message is complete (so GetReceivedMessage can be called).
Definition: net.h:426
ConnectionDirection
Definition: netbase.h:33
bool HasPermission(NetPermissionFlags permission) const
Definition: net.h:731
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
Definition: net.cpp:277
bool IsInboundConn() const
Definition: net.h:829
const uint64_t nSeed1
Definition: net.h:1695
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:1089
bool whitelist_relay
flag for adding &#39;relay&#39; permission to whitelisted inbound and manual peers with default permissions...
Definition: net.h:1752
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:329
uint32_t m_recv_len GUARDED_BY(m_recv_mutex)
In {VERSION, APP}, the decrypted packet length, if m_recv_buffer.size() >= BIP324Cipher::LENGTH_LEN.
Definition: net.h:595
RAII-style semaphore lock.
const std::vector< CNode * > & Nodes() const
Definition: net.h:1830
uint16_t GetDefaultPort(Network net) const
Definition: net.cpp:3395
void ThreadOpenConnections(std::vector< std::string > connect, std::span< const std::string > seed_nodes) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:2525
nReceiveFloodSize
Definition: net.h:1119
bool GetUseAddrmanOutgoing() const
Definition: net.h:1168
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0...
Definition: net.h:1094
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:3932
bool m_use_addrman_outgoing
Definition: net.h:1682
Cache responses to addr requests to minimize privacy leak.
Definition: net.h:1621
bool IsFullOutboundConn() const
Definition: net.h:787
NodeId nodeid
Definition: net.h:194
We use block-relay-only connections to help prevent against partition attacks.
CClientUIInterface * m_client_interface
Definition: net.h:1683
bool RemoveAddedNode(std::string_view node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:3746
bool AddConnection(const std::string &address, ConnectionType conn_type, bool use_v2transport) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Attempts to open a connection.
Definition: net.cpp:1871
CAddress addr
Definition: net.h:219
Message header.
Definition: protocol.h:28
static const std::string DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:83
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition: net.h:1088
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:729