Bitcoin Core  26.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-2022 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 <policy/feerate.h>
24 #include <protocol.h>
25 #include <random.h>
26 #include <span.h>
27 #include <streams.h>
28 #include <sync.h>
29 #include <uint256.h>
30 #include <util/check.h>
31 #include <util/sock.h>
32 #include <util/threadinterrupt.h>
33 
34 #include <atomic>
35 #include <condition_variable>
36 #include <cstdint>
37 #include <deque>
38 #include <functional>
39 #include <list>
40 #include <map>
41 #include <memory>
42 #include <optional>
43 #include <queue>
44 #include <thread>
45 #include <unordered_set>
46 #include <vector>
47 
48 class AddrMan;
49 class BanMan;
50 class CChainParams;
51 class CNode;
52 class CScheduler;
53 struct bilingual_str;
54 
56 static const bool DEFAULT_WHITELISTRELAY = true;
58 static const bool DEFAULT_WHITELISTFORCERELAY = false;
59 
61 static constexpr std::chrono::minutes TIMEOUT_INTERVAL{20};
63 static constexpr auto FEELER_INTERVAL = 2min;
65 static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL = 5min;
67 static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
69 static const unsigned int MAX_SUBVERSION_LENGTH = 256;
73 static const int MAX_ADDNODE_CONNECTIONS = 8;
75 static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS = 2;
77 static const int MAX_FEELER_CONNECTIONS = 1;
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 const int NUM_FDS_MESSAGE_CAPTURE = 1;
90 
91 static constexpr bool DEFAULT_FORCEDNSSEED{false};
92 static constexpr bool DEFAULT_DNSSEED{true};
93 static constexpr bool DEFAULT_FIXEDSEEDS{true};
94 static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
95 static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
96 
97 static constexpr bool DEFAULT_V2_TRANSPORT{false};
98 
99 typedef int64_t NodeId;
100 
102  std::string m_added_node;
104 };
105 
110  bool fInbound;
111 };
112 
113 class CNodeStats;
114 class CClientUIInterface;
115 
117  CSerializedNetMsg() = default;
120  // No implicit copying, only moves.
121  CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
123 
125  {
126  CSerializedNetMsg copy;
127  copy.data = data;
128  copy.m_type = m_type;
129  return copy;
130  }
131 
132  std::vector<unsigned char> data;
133  std::string m_type;
134 
136  size_t GetMemoryUsage() const noexcept;
137 };
138 
145 void Discover();
146 
147 uint16_t GetListenPort();
148 
149 enum
150 {
151  LOCAL_NONE, // unknown
152  LOCAL_IF, // address a local interface listens on
153  LOCAL_BIND, // address explicit bound to
154  LOCAL_MAPPED, // address reported by UPnP or NAT-PMP
155  LOCAL_MANUAL, // address explicitly specified (-externalip=)
156 
158 };
159 
161 std::optional<CService> GetLocalAddrForPeer(CNode& node);
162 
163 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
164 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
165 void RemoveLocal(const CService& addr);
166 bool SeenLocal(const CService& addr);
167 bool IsLocal(const CService& addr);
168 CService GetLocalAddress(const CNode& peer);
169 
170 extern bool fDiscover;
171 extern bool fListen;
172 
174 extern std::string strSubVersion;
175 
177  int nScore;
178  uint16_t nPort;
179 };
180 
182 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(g_maplocalhost_mutex);
183 
184 extern const std::string NET_MESSAGE_TYPE_OTHER;
185 using mapMsgTypeSize = std::map</* message type */ std::string, /* total bytes */ uint64_t>;
186 
188 {
189 public:
191  std::chrono::seconds m_last_send;
192  std::chrono::seconds m_last_recv;
193  std::chrono::seconds m_last_tx_time;
194  std::chrono::seconds m_last_block_time;
195  std::chrono::seconds m_connected;
196  int64_t nTimeOffset;
197  std::string m_addr_name;
198  int nVersion;
199  std::string cleanSubVer;
200  bool fInbound;
201  // We requested high bandwidth connection to peer
203  // Peer requested high bandwidth connection
206  uint64_t nSendBytes;
208  uint64_t nRecvBytes;
211  std::chrono::microseconds m_last_ping_time;
212  std::chrono::microseconds m_min_ping_time;
213  // Our address, as reported by the peer
214  std::string addrLocal;
215  // Address of this peer
217  // Bind address of our side of the connection
219  // Network the peer connected through
221  uint32_t m_mapped_as;
226  std::string m_session_id;
227 };
228 
229 
234 class CNetMessage {
235 public:
237  std::chrono::microseconds m_time{0};
238  uint32_t m_message_size{0};
239  uint32_t m_raw_message_size{0};
240  std::string m_type;
241 
242  CNetMessage(CDataStream&& recv_in) : m_recv(std::move(recv_in)) {}
243  // Only one CNetMessage object will exist for the same message on either
244  // the receive or processing queue. For performance reasons we therefore
245  // delete the copy constructor and assignment operator to avoid the
246  // possibility of copying CNetMessage objects.
247  CNetMessage(CNetMessage&&) = default;
248  CNetMessage(const CNetMessage&) = delete;
249  CNetMessage& operator=(CNetMessage&&) = default;
250  CNetMessage& operator=(const CNetMessage&) = delete;
251 
252  void SetVersion(int nVersionIn)
253  {
254  m_recv.SetVersion(nVersionIn);
255  }
256 };
257 
259 class Transport {
260 public:
261  virtual ~Transport() {}
262 
263  struct Info
264  {
266  std::optional<uint256> session_id;
267  };
268 
270  virtual Info GetInfo() const noexcept = 0;
271 
272  // 1. Receiver side functions, for decoding bytes received on the wire into transport protocol
273  // agnostic CNetMessage (message type & payload) objects.
274 
276  virtual bool ReceivedMessageComplete() const = 0;
277 
284  virtual bool ReceivedBytes(Span<const uint8_t>& msg_bytes) = 0;
285 
293  virtual CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) = 0;
294 
295  // 2. Sending side functions, for converting messages into bytes to be sent over the wire.
296 
303  virtual bool SetMessageToSend(CSerializedNetMsg& msg) noexcept = 0;
304 
312  using BytesToSend = std::tuple<
313  Span<const uint8_t> /*to_send*/,
314  bool /*more*/,
315  const std::string& /*m_type*/
316  >;
317 
353  virtual BytesToSend GetBytesToSend(bool have_next_message) const noexcept = 0;
354 
361  virtual void MarkBytesSent(size_t bytes_sent) noexcept = 0;
362 
364  virtual size_t GetSendMemoryUsage() const noexcept = 0;
365 
366  // 3. Miscellaneous functions.
367 
369  virtual bool ShouldReconnectV1() const noexcept = 0;
370 };
371 
372 class V1Transport final : public Transport
373 {
374 private:
376  const NodeId m_node_id; // Only for logging
377  mutable Mutex m_recv_mutex;
378  mutable CHash256 hasher GUARDED_BY(m_recv_mutex);
379  mutable uint256 data_hash GUARDED_BY(m_recv_mutex);
380  bool in_data GUARDED_BY(m_recv_mutex); // parsing header (false) or data (true)
381  CDataStream hdrbuf GUARDED_BY(m_recv_mutex); // partially received header
382  CMessageHeader hdr GUARDED_BY(m_recv_mutex); // complete header
383  CDataStream vRecv GUARDED_BY(m_recv_mutex); // received message data
384  unsigned int nHdrPos GUARDED_BY(m_recv_mutex);
385  unsigned int nDataPos GUARDED_BY(m_recv_mutex);
386 
387  const uint256& GetMessageHash() const EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
388  int readHeader(Span<const uint8_t> msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
389  int readData(Span<const uint8_t> msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
390 
391  void Reset() EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex) {
392  AssertLockHeld(m_recv_mutex);
393  vRecv.clear();
394  hdrbuf.clear();
395  hdrbuf.resize(24);
396  in_data = false;
397  nHdrPos = 0;
398  nDataPos = 0;
399  data_hash.SetNull();
400  hasher.Reset();
401  }
402 
403  bool CompleteInternal() const noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
404  {
405  AssertLockHeld(m_recv_mutex);
406  if (!in_data) return false;
407  return hdr.nMessageSize == nDataPos;
408  }
409 
413  std::vector<uint8_t> m_header_to_send GUARDED_BY(m_send_mutex);
415  CSerializedNetMsg m_message_to_send GUARDED_BY(m_send_mutex);
417  bool m_sending_header GUARDED_BY(m_send_mutex) {false};
419  size_t m_bytes_sent GUARDED_BY(m_send_mutex) {0};
420 
421 public:
422  V1Transport(const NodeId node_id, int nTypeIn, int nVersionIn) noexcept;
423 
424  bool ReceivedMessageComplete() const override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
425  {
426  AssertLockNotHeld(m_recv_mutex);
427  return WITH_LOCK(m_recv_mutex, return CompleteInternal());
428  }
429 
430  Info GetInfo() const noexcept override;
431 
432  bool ReceivedBytes(Span<const uint8_t>& msg_bytes) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
433  {
434  AssertLockNotHeld(m_recv_mutex);
435  LOCK(m_recv_mutex);
436  int ret = in_data ? readData(msg_bytes) : readHeader(msg_bytes);
437  if (ret < 0) {
438  Reset();
439  } else {
440  msg_bytes = msg_bytes.subspan(ret);
441  }
442  return ret >= 0;
443  }
444 
445  CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
446 
447  bool SetMessageToSend(CSerializedNetMsg& msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
448  BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
449  void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
450  size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
451  bool ShouldReconnectV1() const noexcept override { return false; }
452 };
453 
454 class V2Transport final : public Transport
455 {
456 private:
460  static constexpr std::array<std::byte, 0> VERSION_CONTENTS = {};
461 
464  static constexpr size_t V1_PREFIX_LEN = 16;
465 
466  // The sender side and receiver side of V2Transport are state machines that are transitioned
467  // through, based on what has been received. The receive state corresponds to the contents of,
468  // and bytes received to, the receive buffer. The send state controls what can be appended to
469  // the send buffer and what can be sent from it.
470 
485  enum class RecvState : uint8_t {
491  KEY_MAYBE_V1,
492 
498  KEY,
499 
506  GARB_GARBTERM,
507 
516  VERSION,
517 
523  APP,
524 
529  APP_READY,
530 
534  V1,
535  };
536 
550  enum class SendState : uint8_t {
557  MAYBE_V1,
558 
564  AWAITING_KEY,
565 
572  READY,
573 
577  V1,
578  };
579 
583  const bool m_initiating;
588 
590  mutable Mutex m_recv_mutex ACQUIRED_BEFORE(m_send_mutex);
593  uint32_t m_recv_len GUARDED_BY(m_recv_mutex) {0};
595  std::vector<uint8_t> m_recv_buffer GUARDED_BY(m_recv_mutex);
597  std::vector<uint8_t> m_recv_aad GUARDED_BY(m_recv_mutex);
599  std::vector<uint8_t> m_recv_decode_buffer GUARDED_BY(m_recv_mutex);
601  const int m_recv_type;
603  const int m_recv_version;
605  RecvState m_recv_state GUARDED_BY(m_recv_mutex);
606 
609  mutable Mutex m_send_mutex ACQUIRED_AFTER(m_recv_mutex);
611  std::vector<uint8_t> m_send_buffer GUARDED_BY(m_send_mutex);
613  uint32_t m_send_pos GUARDED_BY(m_send_mutex) {0};
615  std::vector<uint8_t> m_send_garbage GUARDED_BY(m_send_mutex);
617  std::string m_send_type GUARDED_BY(m_send_mutex);
619  SendState m_send_state GUARDED_BY(m_send_mutex);
621  bool m_sent_v1_header_worth GUARDED_BY(m_send_mutex) {false};
622 
624  void SetReceiveState(RecvState recv_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
626  void SetSendState(SendState send_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex);
628  static std::optional<std::string> GetMessageType(Span<const uint8_t>& contents) noexcept;
630  size_t GetMaxBytesToProcess() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
632  void StartSendingHandshake() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex);
634  void ProcessReceivedMaybeV1Bytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex, !m_send_mutex);
636  bool ProcessReceivedKeyBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex, !m_send_mutex);
638  bool ProcessReceivedGarbageBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
640  bool ProcessReceivedPacketBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
641 
642 public:
643  static constexpr uint32_t MAX_GARBAGE_LEN = 4095;
644 
652  V2Transport(NodeId nodeid, bool initiating, int type_in, int version_in) noexcept;
653 
655  V2Transport(NodeId nodeid, bool initiating, int type_in, int version_in, const CKey& key, Span<const std::byte> ent32, std::vector<uint8_t> garbage) noexcept;
656 
657  // Receive side functions.
658  bool ReceivedMessageComplete() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
659  bool ReceivedBytes(Span<const uint8_t>& msg_bytes) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex, !m_send_mutex);
660  CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
661 
662  // Send side functions.
663  bool SetMessageToSend(CSerializedNetMsg& msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
664  BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
665  void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
666  size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
667 
668  // Miscellaneous functions.
669  bool ShouldReconnectV1() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex, !m_send_mutex);
670  Info GetInfo() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
671 };
672 
674 {
676  std::unique_ptr<i2p::sam::Session> i2p_sam_session = nullptr;
677  bool prefer_evict = false;
678  size_t recv_flood_size{DEFAULT_MAXRECEIVEBUFFER * 1000};
679  bool use_v2transport = false;
680 };
681 
683 class CNode
684 {
685 public:
688  const std::unique_ptr<Transport> m_transport;
689 
691 
700  std::shared_ptr<Sock> m_sock GUARDED_BY(m_sock_mutex);
701 
703  size_t m_send_memusage GUARDED_BY(cs_vSend){0};
705  uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
707  std::deque<CSerializedNetMsg> vSendMsg GUARDED_BY(cs_vSend);
711 
712  uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
713 
714  std::atomic<std::chrono::seconds> m_last_send{0s};
715  std::atomic<std::chrono::seconds> m_last_recv{0s};
717  const std::chrono::seconds m_connected;
718  std::atomic<int64_t> nTimeOffset{0};
719  // Address of this peer
720  const CAddress addr;
721  // Bind address of our side of the connection
723  const std::string m_addr_name;
725  const std::string m_dest;
727  const bool m_inbound_onion;
728  std::atomic<int> nVersion{0};
734  std::string cleanSubVer GUARDED_BY(m_subver_mutex){};
735  const bool m_prefer_evict{false}; // This peer is preferred for eviction.
736  bool HasPermission(NetPermissionFlags permission) const {
737  return NetPermissions::HasFlag(m_permission_flags, permission);
738  }
740  std::atomic_bool fSuccessfullyConnected{false};
741  // Setting fDisconnect to true will cause the node to be disconnected the
742  // next time DisconnectNodes() runs
743  std::atomic_bool fDisconnect{false};
745  std::atomic<int> nRefCount{0};
746 
747  const uint64_t nKeyedNetGroup;
748  std::atomic_bool fPauseRecv{false};
749  std::atomic_bool fPauseSend{false};
750 
752 
754  void MarkReceivedMsgsForProcessing()
755  EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex);
756 
762  std::optional<std::pair<CNetMessage, bool>> PollMessage()
763  EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex);
764 
766  void AccountForSentBytes(const std::string& msg_type, size_t sent_bytes)
767  EXCLUSIVE_LOCKS_REQUIRED(cs_vSend)
768  {
769  mapSendBytesPerMsgType[msg_type] += sent_bytes;
770  }
771 
773  switch (m_conn_type) {
776  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) {
802  return false;
805  return true;
806  } // no default case, so the compiler can warn about missing cases
807 
808  assert(false);
809  }
810 
811  bool IsBlockOnlyConn() const {
812  return m_conn_type == ConnectionType::BLOCK_RELAY;
813  }
814 
815  bool IsFeelerConn() const {
816  return m_conn_type == ConnectionType::FEELER;
817  }
818 
819  bool IsAddrFetchConn() const {
820  return m_conn_type == ConnectionType::ADDR_FETCH;
821  }
822 
823  bool IsInboundConn() const {
824  return m_conn_type == ConnectionType::INBOUND;
825  }
826 
827  bool ExpectServicesFromConn() const {
828  switch (m_conn_type) {
832  return false;
836  return true;
837  } // no default case, so the compiler can warn about missing cases
838 
839  assert(false);
840  }
841 
852  Network ConnectedThroughNetwork() const;
853 
855  [[nodiscard]] bool IsConnectedThroughPrivacyNet() const;
856 
857  // We selected peer as (compact blocks) high-bandwidth peer (BIP152)
858  std::atomic<bool> m_bip152_highbandwidth_to{false};
859  // Peer selected us as (compact blocks) high-bandwidth peer (BIP152)
860  std::atomic<bool> m_bip152_highbandwidth_from{false};
861 
863  std::atomic_bool m_has_all_wanted_services{false};
864 
867  std::atomic_bool m_relays_txs{false};
868 
871  std::atomic_bool m_bloom_filter_loaded{false};
872 
878  std::atomic<std::chrono::seconds> m_last_block_time{0s};
879 
884  std::atomic<std::chrono::seconds> m_last_tx_time{0s};
885 
887  std::atomic<std::chrono::microseconds> m_last_ping_time{0us};
888 
891  std::atomic<std::chrono::microseconds> m_min_ping_time{std::chrono::microseconds::max()};
892 
893  CNode(NodeId id,
894  std::shared_ptr<Sock> sock,
895  const CAddress& addrIn,
896  uint64_t nKeyedNetGroupIn,
897  uint64_t nLocalHostNonceIn,
898  const CAddress& addrBindIn,
899  const std::string& addrNameIn,
900  ConnectionType conn_type_in,
901  bool inbound_onion,
902  CNodeOptions&& node_opts = {});
903  CNode(const CNode&) = delete;
904  CNode& operator=(const CNode&) = delete;
905 
906  NodeId GetId() const {
907  return id;
908  }
909 
910  uint64_t GetLocalNonce() const {
911  return nLocalHostNonce;
912  }
913 
914  int GetRefCount() const
915  {
916  assert(nRefCount >= 0);
917  return nRefCount;
918  }
919 
929  bool ReceiveMsgBytes(Span<const uint8_t> msg_bytes, bool& complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv);
930 
931  void SetCommonVersion(int greatest_common_version)
932  {
933  Assume(m_greatest_common_version == INIT_PROTO_VERSION);
934  m_greatest_common_version = greatest_common_version;
935  }
936  int GetCommonVersion() const
937  {
938  return m_greatest_common_version;
939  }
940 
941  CService GetAddrLocal() const EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex);
943  void SetAddrLocal(const CService& addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex);
944 
945  CNode* AddRef()
946  {
947  nRefCount++;
948  return this;
949  }
950 
951  void Release()
952  {
953  nRefCount--;
954  }
955 
956  void CloseSocketDisconnect() EXCLUSIVE_LOCKS_REQUIRED(!m_sock_mutex);
957 
958  void CopyStats(CNodeStats& stats) EXCLUSIVE_LOCKS_REQUIRED(!m_subver_mutex, !m_addr_local_mutex, !cs_vSend, !cs_vRecv);
959 
961 
963  void PongReceived(std::chrono::microseconds ping_time) {
964  m_last_ping_time = ping_time;
965  m_min_ping_time = std::min(m_min_ping_time.load(), ping_time);
966  }
967 
968 private:
969  const NodeId id;
970  const uint64_t nLocalHostNonce;
971  std::atomic<int> m_greatest_common_version{INIT_PROTO_VERSION};
972 
973  const size_t m_recv_flood_size;
974  std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
975 
977  std::list<CNetMessage> m_msg_process_queue GUARDED_BY(m_msg_process_queue_mutex);
978  size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex){0};
979 
980  // Our address, as reported by the peer
981  CService addrLocal GUARDED_BY(m_addr_local_mutex);
983 
984  mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend);
985  mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv);
986 
997  std::unique_ptr<i2p::sam::Session> m_i2p_sam_session GUARDED_BY(m_sock_mutex);
998 };
999 
1004 {
1005 public:
1008 
1010  virtual void InitializeNode(CNode& node, ServiceFlags our_services) = 0;
1011 
1013  virtual void FinalizeNode(const CNode& node) = 0;
1014 
1022  virtual bool ProcessMessages(CNode* pnode, std::atomic<bool>& interrupt) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) = 0;
1023 
1030  virtual bool SendMessages(CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) = 0;
1031 
1032 
1033 protected:
1038  ~NetEventsInterface() = default;
1039 };
1040 
1042 {
1043 public:
1044 
1045  struct Options
1046  {
1047  ServiceFlags nLocalServices = NODE_NONE;
1048  int nMaxConnections = 0;
1049  int m_max_outbound_full_relay = 0;
1050  int m_max_outbound_block_relay = 0;
1051  int nMaxAddnode = 0;
1052  int nMaxFeeler = 0;
1054  NetEventsInterface* m_msgproc = nullptr;
1055  BanMan* m_banman = nullptr;
1056  unsigned int nSendBufferMaxSize = 0;
1057  unsigned int nReceiveFloodSize = 0;
1058  uint64_t nMaxOutboundLimit = 0;
1059  int64_t m_peer_connect_timeout = DEFAULT_PEER_CONNECT_TIMEOUT;
1060  std::vector<std::string> vSeedNodes;
1061  std::vector<NetWhitelistPermissions> vWhitelistedRange;
1062  std::vector<NetWhitebindPermissions> vWhiteBinds;
1063  std::vector<CService> vBinds;
1064  std::vector<CService> onion_binds;
1068  bool m_use_addrman_outgoing = true;
1069  std::vector<std::string> m_specified_outgoing;
1070  std::vector<std::string> m_added_nodes;
1072  };
1073 
1074  void Init(const Options& connOptions) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex, !m_total_bytes_sent_mutex)
1075  {
1076  AssertLockNotHeld(m_total_bytes_sent_mutex);
1077 
1078  nLocalServices = connOptions.nLocalServices;
1079  nMaxConnections = connOptions.nMaxConnections;
1080  m_max_outbound_full_relay = std::min(connOptions.m_max_outbound_full_relay, connOptions.nMaxConnections);
1081  m_max_outbound_block_relay = connOptions.m_max_outbound_block_relay;
1082  m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
1083  nMaxAddnode = connOptions.nMaxAddnode;
1084  nMaxFeeler = connOptions.nMaxFeeler;
1085  m_max_outbound = m_max_outbound_full_relay + m_max_outbound_block_relay + nMaxFeeler;
1086  m_client_interface = connOptions.uiInterface;
1087  m_banman = connOptions.m_banman;
1088  m_msgproc = connOptions.m_msgproc;
1089  nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
1090  nReceiveFloodSize = connOptions.nReceiveFloodSize;
1091  m_peer_connect_timeout = std::chrono::seconds{connOptions.m_peer_connect_timeout};
1092  {
1093  LOCK(m_total_bytes_sent_mutex);
1094  nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
1095  }
1096  vWhitelistedRange = connOptions.vWhitelistedRange;
1097  {
1098  LOCK(m_added_nodes_mutex);
1099 
1100  for (const std::string& added_node : connOptions.m_added_nodes) {
1101  // -addnode cli arg does not currently have a way to signal BIP324 support
1102  m_added_node_params.push_back({added_node, false});
1103  }
1104  }
1105  m_onion_binds = connOptions.onion_binds;
1106  }
1107 
1108  CConnman(uint64_t seed0, uint64_t seed1, AddrMan& addrman, const NetGroupManager& netgroupman,
1109  const CChainParams& params, bool network_active = true);
1110 
1111  ~CConnman();
1112 
1113  bool Start(CScheduler& scheduler, const Options& options) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !m_added_nodes_mutex, !m_addr_fetches_mutex, !mutexMsgProc);
1114 
1115  void StopThreads();
1116  void StopNodes();
1117  void Stop()
1118  {
1119  StopThreads();
1120  StopNodes();
1121  };
1122 
1123  void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);
1124  bool GetNetworkActive() const { return fNetworkActive; };
1125  bool GetUseAddrmanOutgoing() const { return m_use_addrman_outgoing; };
1126  void SetNetworkActive(bool active);
1127  void OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant&& grant_outbound, const char* strDest, ConnectionType conn_type, bool use_v2transport) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex);
1128  bool CheckIncomingNonce(uint64_t nonce);
1129 
1130  // alias for thread safety annotations only, not defined
1131  RecursiveMutex& GetNodesMutex() const LOCK_RETURNED(m_nodes_mutex);
1132 
1133  bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
1134 
1135  void PushMessage(CNode* pnode, CSerializedNetMsg&& msg) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1136 
1137  using NodeFn = std::function<void(CNode*)>;
1138  void ForEachNode(const NodeFn& func)
1139  {
1140  LOCK(m_nodes_mutex);
1141  for (auto&& node : m_nodes) {
1142  if (NodeFullyConnected(node))
1143  func(node);
1144  }
1145  };
1146 
1147  void ForEachNode(const NodeFn& func) const
1148  {
1149  LOCK(m_nodes_mutex);
1150  for (auto&& node : m_nodes) {
1151  if (NodeFullyConnected(node))
1152  func(node);
1153  }
1154  };
1155 
1156  // Addrman functions
1164  std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct, std::optional<Network> network) const;
1171  std::vector<CAddress> GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct);
1172 
1173  // This allows temporarily exceeding m_max_outbound_full_relay, with the goal of finding
1174  // a peer that is better than all our current peers.
1175  void SetTryNewOutboundPeer(bool flag);
1176  bool GetTryNewOutboundPeer() const;
1177 
1178  void StartExtraBlockRelayPeers();
1179 
1180  // Return the number of outbound peers we have in excess of our target (eg,
1181  // if we previously called SetTryNewOutboundPeer(true), and have since set
1182  // to false, we may have extra peers that we wish to disconnect). This may
1183  // return a value less than (num_outbound_connections - num_outbound_slots)
1184  // in cases where some outbound connections are not yet fully connected, or
1185  // not yet fully disconnected.
1186  int GetExtraFullOutboundCount() const;
1187  // Count the number of block-relay-only peers we have over our limit.
1188  int GetExtraBlockRelayCount() const;
1189 
1190  bool AddNode(const AddedNodeParams& add) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1191  bool RemoveAddedNode(const std::string& node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1192  bool AddedNodesContain(const CAddress& addr) const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1193  std::vector<AddedNodeInfo> GetAddedNodeInfo() const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1194 
1207  bool AddConnection(const std::string& address, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex);
1208 
1209  size_t GetNodeCount(ConnectionDirection) const;
1210  uint32_t GetMappedAS(const CNetAddr& addr) const;
1211  void GetNodeStats(std::vector<CNodeStats>& vstats) const;
1212  bool DisconnectNode(const std::string& node);
1213  bool DisconnectNode(const CSubNet& subnet);
1214  bool DisconnectNode(const CNetAddr& addr);
1215  bool DisconnectNode(NodeId id);
1216 
1223  ServiceFlags GetLocalServices() const;
1224 
1225  uint64_t GetMaxOutboundTarget() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1226  std::chrono::seconds GetMaxOutboundTimeframe() const;
1227 
1231  bool OutboundTargetReached(bool historicalBlockServingLimit) const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1232 
1235  uint64_t GetOutboundTargetBytesLeft() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1236 
1237  std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1238 
1239  uint64_t GetTotalBytesRecv() const;
1240  uint64_t GetTotalBytesSent() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1241 
1243  CSipHasher GetDeterministicRandomizer(uint64_t id) const;
1244 
1245  void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);
1246 
1248  bool ShouldRunInactivityChecks(const CNode& node, std::chrono::seconds now) const;
1249 
1250  bool MultipleManualOrFullOutboundConns(Network net) const EXCLUSIVE_LOCKS_REQUIRED(m_nodes_mutex);
1251 
1252 private:
1253  struct ListenSocket {
1254  public:
1255  std::shared_ptr<Sock> sock;
1257  ListenSocket(std::shared_ptr<Sock> sock_, NetPermissionFlags permissions_)
1258  : sock{sock_}, m_permissions{permissions_}
1259  {
1260  }
1261 
1262  private:
1264  };
1265 
1268  std::chrono::seconds GetMaxOutboundTimeLeftInCycle_() const EXCLUSIVE_LOCKS_REQUIRED(m_total_bytes_sent_mutex);
1269 
1270  bool BindListenPort(const CService& bindAddr, bilingual_str& strError, NetPermissionFlags permissions);
1271  bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions);
1272  bool InitBinds(const Options& options);
1273 
1274  void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex, !m_unused_i2p_sessions_mutex, !m_reconnections_mutex);
1275  void AddAddrFetch(const std::string& strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex);
1276  void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex, !m_unused_i2p_sessions_mutex);
1277  void ThreadOpenConnections(std::vector<std::string> connect) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex, !m_added_nodes_mutex, !m_nodes_mutex, !m_unused_i2p_sessions_mutex, !m_reconnections_mutex);
1278  void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);
1279  void ThreadI2PAcceptIncoming();
1280  void AcceptConnection(const ListenSocket& hListenSocket);
1281 
1290  void CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock,
1291  NetPermissionFlags permission_flags,
1292  const CAddress& addr_bind,
1293  const CAddress& addr);
1294 
1295  void DisconnectNodes() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex, !m_nodes_mutex);
1296  void NotifyNumConnectionsChanged();
1298  bool InactivityCheck(const CNode& node) const;
1299 
1305  Sock::EventsPerSock GenerateWaitSockets(Span<CNode* const> nodes);
1306 
1310  void SocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !mutexMsgProc);
1311 
1317  void SocketHandlerConnected(const std::vector<CNode*>& nodes,
1318  const Sock::EventsPerSock& events_per_sock)
1319  EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !mutexMsgProc);
1320 
1325  void SocketHandlerListening(const Sock::EventsPerSock& events_per_sock);
1326 
1327  void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !mutexMsgProc, !m_nodes_mutex, !m_reconnections_mutex);
1328  void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex, !m_nodes_mutex);
1329 
1330  uint64_t CalculateKeyedNetGroup(const CAddress& ad) const;
1331 
1332  CNode* FindNode(const CNetAddr& ip);
1333  CNode* FindNode(const std::string& addrName);
1334  CNode* FindNode(const CService& addr);
1335 
1340  bool AlreadyConnectedToAddress(const CAddress& addr);
1341 
1342  bool AttemptToEvictConnection();
1343  CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type, bool use_v2transport) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex);
1344  void AddWhitelistPermissionFlags(NetPermissionFlags& flags, const CNetAddr &addr) const;
1345 
1346  void DeleteNode(CNode* pnode);
1347 
1348  NodeId GetNewNodeId();
1349 
1351  std::pair<size_t, bool> SocketSendData(CNode& node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend);
1352 
1353  void DumpAddresses();
1354 
1355  // Network stats
1356  void RecordBytesRecv(uint64_t bytes);
1357  void RecordBytesSent(uint64_t bytes) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1358 
1363  std::unordered_set<Network> GetReachableEmptyNetworks() const;
1364 
1368  std::vector<CAddress> GetCurrentBlockRelayOnlyConns() const;
1369 
1380  bool MaybePickPreferredNetwork(std::optional<Network>& network);
1381 
1382  // Whether the node should be passed out in ForEach* callbacks
1383  static bool NodeFullyConnected(const CNode* pnode);
1384 
1385  uint16_t GetDefaultPort(Network net) const;
1386  uint16_t GetDefaultPort(const std::string& addr) const;
1387 
1388  // Network usage totals
1389  mutable Mutex m_total_bytes_sent_mutex;
1390  std::atomic<uint64_t> nTotalBytesRecv{0};
1391  uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex) {0};
1392 
1393  // outbound limit & stats
1394  uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex) {0};
1395  std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex) {0};
1396  uint64_t nMaxOutboundLimit GUARDED_BY(m_total_bytes_sent_mutex);
1397 
1398  // P2P timeout in seconds
1399  std::chrono::seconds m_peer_connect_timeout;
1400 
1401  // Whitelisted ranges. Any node connecting from these is automatically
1402  // whitelisted (as well as those connecting to whitelisted binds).
1403  std::vector<NetWhitelistPermissions> vWhitelistedRange;
1404 
1405  unsigned int nSendBufferMaxSize{0};
1406  unsigned int nReceiveFloodSize{0};
1407 
1408  std::vector<ListenSocket> vhListenSocket;
1409  std::atomic<bool> fNetworkActive{true};
1410  bool fAddressesInitialized{false};
1413  std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
1415 
1416  // connection string and whether to use v2 p2p
1417  std::vector<AddedNodeParams> m_added_node_params GUARDED_BY(m_added_nodes_mutex);
1418 
1420  std::vector<CNode*> m_nodes GUARDED_BY(m_nodes_mutex);
1421  std::list<CNode*> m_nodes_disconnected;
1423  std::atomic<NodeId> nLastNodeId{0};
1424  unsigned int nPrevNodeCount{0};
1425 
1426  // Stores number of full-tx connections (outbound and manual) per network
1427  std::array<unsigned int, Network::NET_MAX> m_network_conn_counts GUARDED_BY(m_nodes_mutex) = {};
1428 
1436  std::vector<CAddress> m_addrs_response_cache;
1437  std::chrono::microseconds m_cache_entry_expiration{0};
1438  };
1439 
1454  std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
1455 
1467 
1468  std::unique_ptr<CSemaphore> semOutbound;
1469  std::unique_ptr<CSemaphore> semAddnode;
1471 
1472  // How many full-relay (tx, block, addr) outbound peers we want
1474 
1475  // How many block-relay only outbound peers we want
1476  // We do not relay tx or addr messages with these peers
1478 
1487 
1492  std::vector<CAddress> m_anchors;
1493 
1495  const uint64_t nSeed0, nSeed1;
1496 
1498  bool fMsgProcWake GUARDED_BY(mutexMsgProc);
1499 
1500  std::condition_variable condMsgProc;
1502  std::atomic<bool> flagInterruptMsgProc{false};
1503 
1511 
1517  std::unique_ptr<i2p::sam::Session> m_i2p_sam_session;
1518 
1520  std::thread threadSocketHandler;
1525 
1530 
1535  std::atomic_bool m_start_extra_block_relay_peers{false};
1536 
1541  std::vector<CService> m_onion_binds;
1542 
1547 
1555  std::queue<std::unique_ptr<i2p::sam::Session>> m_unused_i2p_sessions GUARDED_BY(m_unused_i2p_sessions_mutex);
1556 
1561 
1564  {
1567  std::string destination;
1570  };
1571 
1575  std::list<ReconnectionInfo> m_reconnections GUARDED_BY(m_reconnections_mutex);
1576 
1578  void PerformReconnections() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex, !m_unused_i2p_sessions_mutex);
1579 
1584  static constexpr size_t MAX_UNUSED_I2P_SESSIONS_SIZE{10};
1585 
1591  {
1592  public:
1593  explicit NodesSnapshot(const CConnman& connman, bool shuffle)
1594  {
1595  {
1596  LOCK(connman.m_nodes_mutex);
1597  m_nodes_copy = connman.m_nodes;
1598  for (auto& node : m_nodes_copy) {
1599  node->AddRef();
1600  }
1601  }
1602  if (shuffle) {
1603  Shuffle(m_nodes_copy.begin(), m_nodes_copy.end(), FastRandomContext{});
1604  }
1605  }
1606 
1608  {
1609  for (auto& node : m_nodes_copy) {
1610  node->Release();
1611  }
1612  }
1613 
1614  const std::vector<CNode*>& Nodes() const
1615  {
1616  return m_nodes_copy;
1617  }
1618 
1619  private:
1620  std::vector<CNode*> m_nodes_copy;
1621  };
1622 
1624 
1625  friend struct ConnmanTestMsg;
1626 };
1627 
1629 extern std::function<void(const CAddress& addr,
1630  const std::string& msg_type,
1632  bool is_incoming)>
1634 
1635 #endif // BITCOIN_NET_H
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition: net.h:1007
std::chrono::microseconds m_min_ping_time
Definition: net.h:212
std::vector< CService > vBinds
Definition: net.h:1063
std::vector< CAddress > m_addrs_response_cache
Definition: net.h:1436
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:75
Mutex m_send_mutex
Lock for sending state.
Definition: net.h:411
std::string m_type
Definition: net.h:133
int nMaxFeeler
Definition: net.h:1480
const std::string m_dest
The pszDest argument provided to ConnectNode().
Definition: net.h:725
int ret
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:67
BIP324Cipher m_cipher
Cipher state.
Definition: net.h:581
bool m_i2p_accept_incoming
Definition: net.h:1071
CSemaphoreGrant grant
Definition: net.h:1566
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:419
int m_max_outbound
Definition: net.h:1481
Mutex m_addr_local_mutex
Definition: net.h:982
AssertLockHeld(pool.cs)
mapMsgTypeSize mapSendBytesPerMsgType
Definition: net.h:207
Definition: banman.h:58
static void AddFlag(NetPermissionFlags &flags, NetPermissionFlags f)
ServiceFlags
nServices flags
Definition: protocol.h:274
ConnectionType conn_type
Definition: net.h:1568
CClientUIInterface uiInterface
Inbound connections are those initiated by a peer.
int64_t nTimeOffset
Definition: net.h:196
assert(!tx.IsCoinBase())
bool fListen
Definition: net.cpp:115
uint32_t m_mapped_as
Definition: net.h:221
Unencrypted, plaintext protocol.
unsigned int nonce
Definition: miner_tests.cpp:72
Feeler connections are short-lived connections made to check that a node is alive.
std::shared_ptr< Sock > sock
Definition: net.h:1255
bool m_sending_header GUARDED_BY(m_send_mutex)
Whether we&#39;re currently sending header bytes or message bytes.
Definition: net.h:417
std::list< CNode * > m_nodes_disconnected
Definition: net.h:1421
Bilingual messages:
Definition: translation.h:18
size_t m_send_memusage GUARDED_BY(cs_vSend)
Sum of GetMemoryUsage of all vSendMsg entries.
Definition: net.h:703
Mutex mutexMsgProc
Definition: net.h:1501
const uint64_t nKeyedNetGroup
Definition: net.h:747
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:314
std::map< std::string, uint64_t > mapMsgTypeSize
Definition: net.h:185
bool IsOutboundOrBlockRelayConn() const
Definition: net.h:772
const std::chrono::seconds m_connected
Unix epoch time at peer connection.
Definition: net.h:717
const int m_recv_version
Deserialization version number.
Definition: net.h:603
std::vector< unsigned char > data
Definition: net.h:132
AddedNodeParams m_params
Definition: net.h:107
const ConnectionType m_conn_type
Definition: net.h:751
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:613
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:1403
std::string destination
Definition: net.h:1567
bool IsFeelerConn() const
Definition: net.h:815
uint16_t GetListenPort()
Definition: net.cpp:134
int m_max_outbound_full_relay
Definition: net.h:1473
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:1541
#define LOCK_RETURNED(x)
Definition: threadsafety.h:47
CDataStream m_recv
received message data
Definition: net.h:236
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:79
CNetMessage(CDataStream &&recv_in)
Definition: net.h:242
int nMaxAddnode
Definition: net.h:1479
RAII-style semaphore lock.
Definition: sync.h:353
void SetCommonVersion(int greatest_common_version)
Definition: net.h:931
Interrupt(node)
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:73
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
Definition: net.cpp:237
std::string cleanSubVer
Definition: net.h:199
Interface for message handling.
Definition: net.h:1003
void SetVersion(int nVersionIn)
Definition: net.h:252
const std::string KEY
Definition: walletdb.cpp:45
static const unsigned char VERSION[]
Definition: netaddress.cpp:184
NetEventsInterface * m_msgproc
Definition: net.h:1484
const NodeId m_nodeid
NodeId (for debug logging).
Definition: net.h:585
CSerializedNetMsg()=default
TransportProtocolType
Transport layer version.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:80
void ForEachNode(const NodeFn &func) const
Definition: net.h:1147
int m_max_outbound_block_relay
Definition: net.h:1477
Mutex m_subver_mutex
Definition: net.h:729
A hasher class for Bitcoin&#39;s 256-bit hash (double SHA-256).
Definition: hash.h:25
std::chrono::seconds m_last_recv
Definition: net.h:192
size_t GetMemoryUsage() const noexcept
Compute total memory usage of this object (own memory + any dynamic memory).
Definition: net.cpp:120
uint64_t GetLocalNonce() const
Definition: net.h:910
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:621
NetPermissionFlags
V1Transport m_v1_fallback
Encapsulate a V1Transport to fall back to.
Definition: net.h:587
ConnectionType m_conn_type
Definition: net.h:222
These are the default connections that we use to connect with the network.
AddrMan & addrman
Definition: net.h:1411
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Total number of bytes sent on the wire to this peer.
Definition: net.h:705
Netgroup manager.
Definition: netgroup.h:16
The BIP324 packet cipher, encapsulating its key derivation, stream cipher, and AEAD.
Definition: bip324.h:19
Definition: net.h:157
Signals for UI communication.
Definition: interface_ui.h:24
std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex)
Definition: net.h:1395
static constexpr std::chrono::minutes TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:61
std::list< CNetMessage > vRecvMsg
Definition: net.h:974
const NodeId m_node_id
Definition: net.h:376
SendState
State type that controls the sender side.
Definition: net.h:550
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:1454
#define ACQUIRED_AFTER(...)
Definition: threadsafety.h:40
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition: net.h:77
static bool HasFlag(NetPermissionFlags flags, NetPermissionFlags f)
Stochastic address manager.
Definition: addrman.h:87
bool fConnected
Definition: net.h:109
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition: net.h:1256
int GetRefCount() const
Definition: net.h:914
NetPermissionFlags m_permission_flags
Definition: net.h:210
ServiceFlags nLocalServices
Services this node offers.
Definition: net.h:1466
Mutex m_unused_i2p_sessions_mutex
Mutex protecting m_i2p_sam_sessions.
Definition: net.h:1546
uint16_t nPort
Definition: net.h:178
TransportProtocolType m_transport_type
Transport protocol type.
Definition: net.h:224
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:3873
std::array< uint8_t, 4 > MessageStartChars
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:94
Mutex m_sock_mutex
Definition: net.h:709
std::thread threadI2PAcceptIncoming
Definition: net.h:1524
std::tuple< Span< const uint8_t >, bool, const std::string &> BytesToSend
Return type for GetBytesToSend, consisting of:
Definition: net.h:316
bool CompleteInternal() const noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Definition: net.h:403
CService GetLocalAddress(const CNode &peer)
Definition: net.cpp:217
int nVersion
Definition: net.h:198
CSerializedNetMsg Copy() const
Definition: net.h:124
std::optional< uint256 > session_id
Definition: net.h:266
ListenSocket(std::shared_ptr< Sock > sock_, NetPermissionFlags permissions_)
Definition: net.h:1257
void Release()
Definition: net.h:951
static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it)
Definition: txmempool.cpp:835
std::condition_variable condMsgProc
Definition: net.h:1500
const std::unique_ptr< Transport > m_transport
Transport serializer/deserializer.
Definition: net.h:688
std::chrono::seconds m_connected
Definition: net.h:195
bool IsManualOrFullOutboundConn() const
Definition: net.h:795
Mutex m_added_nodes_mutex
Definition: net.h:1419
GlobalMutex g_maplocalhost_mutex
Definition: net.cpp:116
We open manual connections to addresses that users explicitly requested via the addnode RPC or the -a...
int m_starting_height
Definition: net.h:205
virtual ~Transport()
Definition: net.h:261
std::thread threadOpenAddedConnections
Definition: net.h:1521
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
#define LOCK(cs)
Definition: sync.h:258
std::function< void(CNode *)> NodeFn
Definition: net.h:1137
std::string m_added_node
Definition: net.h:102
static const int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
Definition: version.h:15
TransportProtocolType transport_type
Definition: net.h:265
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:534
Fast randomness source.
Definition: random.h:143
Transport protocol agnostic message container.
Definition: net.h:234
const CAddress addrBind
Definition: net.h:722
std::vector< std::string > vSeedNodes
Definition: net.h:1060
std::vector< std::string > m_specified_outgoing
Definition: net.h:1069
bool m_bip152_highbandwidth_from
Definition: net.h:204
uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex)
Definition: net.h:1394
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:1468
std::thread threadMessageHandler
Definition: net.h:1523
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
Definition: net.h:89
Network m_network
Definition: net.h:220
bool fInbound
Definition: net.h:200
bool IsManualConn() const
Definition: net.h:791
std::chrono::microseconds m_last_ping_time
Definition: net.h:211
A CService with information about it as peer.
Definition: protocol.h:362
std::chrono::seconds m_last_tx_time
Definition: net.h:193
uint64_t nRecvBytes
Definition: net.h:208
static constexpr bool DEFAULT_FIXEDSEEDS
Definition: net.h:93
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(g_maplocalhost_mutex)
bool fInbound
Definition: net.h:110
Network
A network type.
Definition: netaddress.h:36
static CService ip(uint32_t i)
bool m_bip152_highbandwidth_to
Definition: net.h:202
bool ExpectServicesFromConn() const
Definition: net.h:827
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:1529
int64_t NodeId
Definition: net.h:99
Definition: net.h:1041
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:97
static constexpr bool DEFAULT_DNSSEED
Definition: net.h:92
const CChainParams & m_params
Definition: net.h:1623
Mutex m_recv_mutex
Lock for receive state.
Definition: net.h:377
const bool m_initiating
Whether we are the initiator side.
Definition: net.h:583
const NetPermissionFlags m_permission_flags
Definition: net.h:690
std::chrono::seconds m_last_send
Definition: net.h:191
NodeId GetId() const
Definition: net.h:906
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e. connected via our Tor onion service.
Definition: net.h:727
uint64_t nSendBytes
Definition: net.h:206
void PongReceived(std::chrono::microseconds ping_time)
A ping-pong round trip has completed successfully.
Definition: net.h:963
int nMaxConnections
Definition: net.h:1470
A helper class for interruptible sleeps.
mapMsgTypeSize mapRecvBytesPerMsgType
Definition: net.h:209
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:302
#define Assume(val)
Assume is the identity function.
Definition: check.h:85
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Definition: net.h:712
RecursiveMutex m_nodes_mutex
Definition: net.h:1422
const size_t m_recv_flood_size
Definition: net.h:973
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:3046
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
Definition: net.h:1517
NetPermissionFlags m_permissions
Definition: net.h:1263
Definition: init.h:25
const CAddress addr
Definition: net.h:720
bool IsBlockOnlyConn() const
Definition: net.h:811
Mutex m_addr_fetches_mutex
Definition: net.h:1414
int flags
Definition: bitcoin-tx.cpp:528
Network address.
Definition: netaddress.h:115
256-bit opaque blob.
Definition: uint256.h:106
void RemoveLocal(const CService &addr)
Definition: net.cpp:306
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:1061
std::vector< CService > onion_binds
Definition: net.h:1064
MessageStartChars m_magic_bytes
Definition: net.h:375
void Shuffle(I first, I last, R &&rng)
More efficient than using std::shuffle on a FastRandomContext.
Definition: random.h:264
int nScore
Definition: net.h:177
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
Definition: net.h:58
The Transport converts one connection&#39;s sent messages to wire bytes, and received bytes back...
Definition: net.h:259
BanMan * m_banman
Pointer to this node&#39;s banman.
Definition: net.h:1486
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:95
CAddress addrBind
Definition: net.h:218
Mutex cs_vRecv
Definition: net.h:710
CService resolvedAddress
Definition: net.h:108
std::thread threadOpenConnections
Definition: net.h:1522
std::chrono::seconds m_peer_connect_timeout
Definition: net.h:1399
CSemaphoreGrant grantOutbound
Definition: net.h:744
const NodeId id
Definition: net.h:969
std::string m_type
Definition: net.h:240
std::string addrLocal
Definition: net.h:214
std::thread threadDNSAddressSeed
Definition: net.h:1519
#define ACQUIRED_BEFORE(...)
Definition: threadsafety.h:41
std::vector< std::string > m_added_nodes
Definition: net.h:1070
std::vector< ListenSocket > vhListenSocket
Definition: net.h:1408
Mutex cs_vSend
Definition: net.h:708
std::chrono::seconds m_last_block_time
Definition: net.h:194
static constexpr bool DEFAULT_FORCEDNSSEED
Definition: net.h:91
SipHash-2-4.
Definition: siphash.h:14
#define AssertLockNotHeld(cs)
Definition: sync.h:148
std::string m_session_id
BIP324 session id string in hex, if any.
Definition: net.h:226
size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex)
Definition: net.h:978
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:69
RecvState
State type that defines the current contents of the receive buffer and/or how the next received bytes...
Definition: net.h:485
static constexpr auto FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes.
Definition: net.h:63
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition: net.h:87
const std::string NET_MESSAGE_TYPE_OTHER
Definition: net.cpp:106
static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL
Run the extra block-relay-only connection loop once every 5 minutes.
Definition: net.h:65
uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex)
Definition: net.h:1391
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:970
Mutex m_msg_process_queue_mutex
Definition: net.h:976
RAII helper class that manages a socket and closes it automatically when it goes out of scope...
Definition: sock.h:26
std::vector< CNode * > m_nodes_copy
Definition: net.h:1620
Mutex m_reconnections_mutex
Mutex protecting m_reconnections.
Definition: net.h:1560
bool IsAddrFetchConn() const
Definition: net.h:819
std::string m_addr_name
Definition: net.h:197
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
Definition: net.h:56
RAII helper to atomically create a copy of m_nodes and add a reference to each of the nodes...
Definition: net.h:1590
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:71
An encapsulated private key.
Definition: key.h:32
A Span is an object that can refer to a contiguous sequence of objects.
Definition: solver.h:20
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:118
Different type to mark Mutex at global scope.
Definition: sync.h:141
Definition: net.h:152
NodesSnapshot(const CConnman &connman, bool shuffle)
Definition: net.h:1593
Information about a peer.
Definition: net.h:683
std::thread threadSocketHandler
Definition: net.h:1520
Simple class for background tasks that should be run periodically or once "after a while"...
Definition: scheduler.h:38
Struct for entries in m_reconnections.
Definition: net.h:1563
const int m_recv_type
Deserialization type.
Definition: net.h:601
bool fDiscover
Definition: net.cpp:114
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
Definition: net.h:1492
void SetVersion(int n)
Definition: streams.h:346
bool m_use_v2transport
Definition: net.h:103
const NetGroupManager & m_netgroupman
Definition: net.h:1412
int GetCommonVersion() const
Definition: net.h:936
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
const std::string m_addr_name
Definition: net.h:723
std::unique_ptr< CSemaphore > semAddnode
Definition: net.h:1469
CThreadInterrupt interruptNet
This is signaled when network activity should cease.
Definition: net.h:1510
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:424
ConnectionDirection
Definition: netbase.h:33
bool HasPermission(NetPermissionFlags permission) const
Definition: net.h:736
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
Definition: net.cpp:273
bool IsInboundConn() const
Definition: net.h:823
const uint64_t nSeed1
Definition: net.h:1495
void Stop()
Definition: net.h:1117
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:1062
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:325
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:593
const std::vector< CNode * > & Nodes() const
Definition: net.h:1614
bool GetUseAddrmanOutgoing() const
Definition: net.h:1125
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0...
Definition: net.h:1067
bool m_use_addrman_outgoing
Definition: net.h:1482
Cache responses to addr requests to minimize privacy leak.
Definition: net.h:1435
bool IsFullOutboundConn() const
Definition: net.h:787
NodeId nodeid
Definition: net.h:190
We use block-relay-only connections to help prevent against partition attacks.
CClientUIInterface * m_client_interface
Definition: net.h:1483
CAddress addr
Definition: net.h:216
Message header.
Definition: protocol.h:28
static const std::string DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:83
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:734