Bitcoin Core  29.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 <node/protocol_version.h>
24 #include <policy/feerate.h>
25 #include <protocol.h>
26 #include <random.h>
27 #include <span.h>
28 #include <streams.h>
29 #include <sync.h>
30 #include <uint256.h>
31 #include <util/check.h>
32 #include <util/sock.h>
33 #include <util/threadinterrupt.h>
34 
35 #include <atomic>
36 #include <condition_variable>
37 #include <cstdint>
38 #include <deque>
39 #include <functional>
40 #include <list>
41 #include <map>
42 #include <memory>
43 #include <optional>
44 #include <queue>
45 #include <thread>
46 #include <unordered_set>
47 #include <vector>
48 
49 class AddrMan;
50 class BanMan;
51 class CChainParams;
52 class CNode;
53 class CScheduler;
54 struct bilingual_str;
55 
57 static constexpr std::chrono::minutes TIMEOUT_INTERVAL{20};
59 static constexpr auto FEELER_INTERVAL = 2min;
61 static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL = 5min;
63 static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
65 static const unsigned int MAX_SUBVERSION_LENGTH = 256;
69 static const int MAX_ADDNODE_CONNECTIONS = 8;
71 static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS = 2;
73 static const int MAX_FEELER_CONNECTIONS = 1;
75 static const bool DEFAULT_LISTEN = true;
77 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
79 static const std::string DEFAULT_MAX_UPLOAD_TARGET{"0M"};
81 static const bool DEFAULT_BLOCKSONLY = false;
83 static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
85 static const int NUM_FDS_MESSAGE_CAPTURE = 1;
87 static constexpr std::chrono::hours ASMAP_HEALTH_CHECK_INTERVAL{24};
88 
89 static constexpr bool DEFAULT_FORCEDNSSEED{false};
90 static constexpr bool DEFAULT_DNSSEED{true};
91 static constexpr bool DEFAULT_FIXEDSEEDS{true};
92 static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
93 static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
94 
95 static constexpr bool DEFAULT_V2_TRANSPORT{true};
96 
97 typedef int64_t NodeId;
98 
100  std::string m_added_node;
102 };
103 
108  bool fInbound;
109 };
110 
111 class CNodeStats;
112 class CClientUIInterface;
113 
115  CSerializedNetMsg() = default;
118  // No implicit copying, only moves.
119  CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
121 
123  {
124  CSerializedNetMsg copy;
125  copy.data = data;
126  copy.m_type = m_type;
127  return copy;
128  }
129 
130  std::vector<unsigned char> data;
131  std::string m_type;
132 
134  size_t GetMemoryUsage() const noexcept;
135 };
136 
142 void Discover();
143 
144 uint16_t GetListenPort();
145 
146 enum
147 {
148  LOCAL_NONE, // unknown
149  LOCAL_IF, // address a local interface listens on
150  LOCAL_BIND, // address explicit bound to
151  LOCAL_MAPPED, // address reported by PCP
152  LOCAL_MANUAL, // address explicitly specified (-externalip=)
153 
155 };
156 
158 std::optional<CService> GetLocalAddrForPeer(CNode& node);
159 
160 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
161 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
162 void RemoveLocal(const CService& addr);
163 bool SeenLocal(const CService& addr);
164 bool IsLocal(const CService& addr);
165 CService GetLocalAddress(const CNode& peer);
166 
167 extern bool fDiscover;
168 extern bool fListen;
169 
171 extern std::string strSubVersion;
172 
174  int nScore;
175  uint16_t nPort;
176 };
177 
179 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(g_maplocalhost_mutex);
180 
181 extern const std::string NET_MESSAGE_TYPE_OTHER;
182 using mapMsgTypeSize = std::map</* message type */ std::string, /* total bytes */ uint64_t>;
183 
185 {
186 public:
188  std::chrono::seconds m_last_send;
189  std::chrono::seconds m_last_recv;
190  std::chrono::seconds m_last_tx_time;
191  std::chrono::seconds m_last_block_time;
192  std::chrono::seconds m_connected;
193  std::string m_addr_name;
194  int nVersion;
195  std::string cleanSubVer;
196  bool fInbound;
197  // We requested high bandwidth connection to peer
199  // Peer requested high bandwidth connection
202  uint64_t nSendBytes;
204  uint64_t nRecvBytes;
207  std::chrono::microseconds m_last_ping_time;
208  std::chrono::microseconds m_min_ping_time;
209  // Our address, as reported by the peer
210  std::string addrLocal;
211  // Address of this peer
213  // Bind address of our side of the connection
215  // Network the peer connected through
217  uint32_t m_mapped_as;
222  std::string m_session_id;
223 };
224 
225 
231 {
232 public:
234  std::chrono::microseconds m_time{0};
235  uint32_t m_message_size{0};
236  uint32_t m_raw_message_size{0};
237  std::string m_type;
238 
239  explicit CNetMessage(DataStream&& recv_in) : m_recv(std::move(recv_in)) {}
240  // Only one CNetMessage object will exist for the same message on either
241  // the receive or processing queue. For performance reasons we therefore
242  // delete the copy constructor and assignment operator to avoid the
243  // possibility of copying CNetMessage objects.
244  CNetMessage(CNetMessage&&) = default;
245  CNetMessage(const CNetMessage&) = delete;
246  CNetMessage& operator=(CNetMessage&&) = default;
247  CNetMessage& operator=(const CNetMessage&) = delete;
248 
250  size_t GetMemoryUsage() const noexcept;
251 };
252 
254 class Transport {
255 public:
256  virtual ~Transport() = default;
257 
258  struct Info
259  {
261  std::optional<uint256> session_id;
262  };
263 
265  virtual Info GetInfo() const noexcept = 0;
266 
267  // 1. Receiver side functions, for decoding bytes received on the wire into transport protocol
268  // agnostic CNetMessage (message type & payload) objects.
269 
271  virtual bool ReceivedMessageComplete() const = 0;
272 
279  virtual bool ReceivedBytes(Span<const uint8_t>& msg_bytes) = 0;
280 
288  virtual CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) = 0;
289 
290  // 2. Sending side functions, for converting messages into bytes to be sent over the wire.
291 
298  virtual bool SetMessageToSend(CSerializedNetMsg& msg) noexcept = 0;
299 
307  using BytesToSend = std::tuple<
308  Span<const uint8_t> /*to_send*/,
309  bool /*more*/,
310  const std::string& /*m_type*/
311  >;
312 
348  virtual BytesToSend GetBytesToSend(bool have_next_message) const noexcept = 0;
349 
356  virtual void MarkBytesSent(size_t bytes_sent) noexcept = 0;
357 
359  virtual size_t GetSendMemoryUsage() const noexcept = 0;
360 
361  // 3. Miscellaneous functions.
362 
364  virtual bool ShouldReconnectV1() const noexcept = 0;
365 };
366 
367 class V1Transport final : public Transport
368 {
369 private:
371  const NodeId m_node_id; // Only for logging
372  mutable Mutex m_recv_mutex;
373  mutable CHash256 hasher GUARDED_BY(m_recv_mutex);
374  mutable uint256 data_hash GUARDED_BY(m_recv_mutex);
375  bool in_data GUARDED_BY(m_recv_mutex); // parsing header (false) or data (true)
376  DataStream hdrbuf GUARDED_BY(m_recv_mutex){}; // partially received header
377  CMessageHeader hdr GUARDED_BY(m_recv_mutex); // complete header
378  DataStream vRecv GUARDED_BY(m_recv_mutex){}; // received message data
379  unsigned int nHdrPos GUARDED_BY(m_recv_mutex);
380  unsigned int nDataPos GUARDED_BY(m_recv_mutex);
381 
382  const uint256& GetMessageHash() const EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
383  int readHeader(Span<const uint8_t> msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
384  int readData(Span<const uint8_t> msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
385 
386  void Reset() EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex) {
387  AssertLockHeld(m_recv_mutex);
388  vRecv.clear();
389  hdrbuf.clear();
390  hdrbuf.resize(24);
391  in_data = false;
392  nHdrPos = 0;
393  nDataPos = 0;
394  data_hash.SetNull();
395  hasher.Reset();
396  }
397 
398  bool CompleteInternal() const noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
399  {
400  AssertLockHeld(m_recv_mutex);
401  if (!in_data) return false;
402  return hdr.nMessageSize == nDataPos;
403  }
404 
408  std::vector<uint8_t> m_header_to_send GUARDED_BY(m_send_mutex);
410  CSerializedNetMsg m_message_to_send GUARDED_BY(m_send_mutex);
412  bool m_sending_header GUARDED_BY(m_send_mutex) {false};
414  size_t m_bytes_sent GUARDED_BY(m_send_mutex) {0};
415 
416 public:
417  explicit V1Transport(const NodeId node_id) noexcept;
418 
419  bool ReceivedMessageComplete() const override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
420  {
421  AssertLockNotHeld(m_recv_mutex);
422  return WITH_LOCK(m_recv_mutex, return CompleteInternal());
423  }
424 
425  Info GetInfo() const noexcept override;
426 
427  bool ReceivedBytes(Span<const uint8_t>& msg_bytes) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
428  {
429  AssertLockNotHeld(m_recv_mutex);
430  LOCK(m_recv_mutex);
431  int ret = in_data ? readData(msg_bytes) : readHeader(msg_bytes);
432  if (ret < 0) {
433  Reset();
434  } else {
435  msg_bytes = msg_bytes.subspan(ret);
436  }
437  return ret >= 0;
438  }
439 
440  CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
441 
442  bool SetMessageToSend(CSerializedNetMsg& msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
443  BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
444  void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
445  size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
446  bool ShouldReconnectV1() const noexcept override { return false; }
447 };
448 
449 class V2Transport final : public Transport
450 {
451 private:
455  static constexpr std::array<std::byte, 0> VERSION_CONTENTS = {};
456 
459  static constexpr size_t V1_PREFIX_LEN = 16;
460 
461  // The sender side and receiver side of V2Transport are state machines that are transitioned
462  // through, based on what has been received. The receive state corresponds to the contents of,
463  // and bytes received to, the receive buffer. The send state controls what can be appended to
464  // the send buffer and what can be sent from it.
465 
480  enum class RecvState : uint8_t {
486  KEY_MAYBE_V1,
487 
493  KEY,
494 
501  GARB_GARBTERM,
502 
511  VERSION,
512 
518  APP,
519 
524  APP_READY,
525 
529  V1,
530  };
531 
545  enum class SendState : uint8_t {
552  MAYBE_V1,
553 
559  AWAITING_KEY,
560 
567  READY,
568 
572  V1,
573  };
574 
578  const bool m_initiating;
583 
585  mutable Mutex m_recv_mutex ACQUIRED_BEFORE(m_send_mutex);
588  uint32_t m_recv_len GUARDED_BY(m_recv_mutex) {0};
590  std::vector<uint8_t> m_recv_buffer GUARDED_BY(m_recv_mutex);
592  std::vector<uint8_t> m_recv_aad GUARDED_BY(m_recv_mutex);
594  std::vector<uint8_t> m_recv_decode_buffer GUARDED_BY(m_recv_mutex);
596  RecvState m_recv_state GUARDED_BY(m_recv_mutex);
597 
600  mutable Mutex m_send_mutex ACQUIRED_AFTER(m_recv_mutex);
602  std::vector<uint8_t> m_send_buffer GUARDED_BY(m_send_mutex);
604  uint32_t m_send_pos GUARDED_BY(m_send_mutex) {0};
606  std::vector<uint8_t> m_send_garbage GUARDED_BY(m_send_mutex);
608  std::string m_send_type GUARDED_BY(m_send_mutex);
610  SendState m_send_state GUARDED_BY(m_send_mutex);
612  bool m_sent_v1_header_worth GUARDED_BY(m_send_mutex) {false};
613 
615  void SetReceiveState(RecvState recv_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
617  void SetSendState(SendState send_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex);
619  static std::optional<std::string> GetMessageType(Span<const uint8_t>& contents) noexcept;
621  size_t GetMaxBytesToProcess() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
623  void StartSendingHandshake() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex);
625  void ProcessReceivedMaybeV1Bytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex, !m_send_mutex);
627  bool ProcessReceivedKeyBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex, !m_send_mutex);
629  bool ProcessReceivedGarbageBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
631  bool ProcessReceivedPacketBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
632 
633 public:
634  static constexpr uint32_t MAX_GARBAGE_LEN = 4095;
635 
641  V2Transport(NodeId nodeid, bool initiating) noexcept;
642 
644  V2Transport(NodeId nodeid, bool initiating, const CKey& key, Span<const std::byte> ent32, std::vector<uint8_t> garbage) noexcept;
645 
646  // Receive side functions.
647  bool ReceivedMessageComplete() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
648  bool ReceivedBytes(Span<const uint8_t>& msg_bytes) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex, !m_send_mutex);
649  CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
650 
651  // Send side functions.
652  bool SetMessageToSend(CSerializedNetMsg& msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
653  BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
654  void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
655  size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
656 
657  // Miscellaneous functions.
658  bool ShouldReconnectV1() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex, !m_send_mutex);
659  Info GetInfo() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
660 };
661 
663 {
665  std::unique_ptr<i2p::sam::Session> i2p_sam_session = nullptr;
666  bool prefer_evict = false;
667  size_t recv_flood_size{DEFAULT_MAXRECEIVEBUFFER * 1000};
668  bool use_v2transport = false;
669 };
670 
672 class CNode
673 {
674 public:
677  const std::unique_ptr<Transport> m_transport;
678 
680 
689  std::shared_ptr<Sock> m_sock GUARDED_BY(m_sock_mutex);
690 
692  size_t m_send_memusage GUARDED_BY(cs_vSend){0};
694  uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
696  std::deque<CSerializedNetMsg> vSendMsg GUARDED_BY(cs_vSend);
700 
701  uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
702 
703  std::atomic<std::chrono::seconds> m_last_send{0s};
704  std::atomic<std::chrono::seconds> m_last_recv{0s};
706  const std::chrono::seconds m_connected;
707  // Address of this peer
708  const CAddress addr;
709  // Bind address of our side of the connection
711  const std::string m_addr_name;
713  const std::string m_dest;
715  const bool m_inbound_onion;
716  std::atomic<int> nVersion{0};
722  std::string cleanSubVer GUARDED_BY(m_subver_mutex){};
723  const bool m_prefer_evict{false}; // This peer is preferred for eviction.
724  bool HasPermission(NetPermissionFlags permission) const {
725  return NetPermissions::HasFlag(m_permission_flags, permission);
726  }
728  std::atomic_bool fSuccessfullyConnected{false};
729  // Setting fDisconnect to true will cause the node to be disconnected the
730  // next time DisconnectNodes() runs
731  std::atomic_bool fDisconnect{false};
733  std::atomic<int> nRefCount{0};
734 
735  const uint64_t nKeyedNetGroup;
736  std::atomic_bool fPauseRecv{false};
737  std::atomic_bool fPauseSend{false};
738 
740 
742  void MarkReceivedMsgsForProcessing()
743  EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex);
744 
750  std::optional<std::pair<CNetMessage, bool>> PollMessage()
751  EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex);
752 
754  void AccountForSentBytes(const std::string& msg_type, size_t sent_bytes)
755  EXCLUSIVE_LOCKS_REQUIRED(cs_vSend)
756  {
757  mapSendBytesPerMsgType[msg_type] += sent_bytes;
758  }
759 
761  switch (m_conn_type) {
764  return true;
769  return false;
770  } // no default case, so the compiler can warn about missing cases
771 
772  assert(false);
773  }
774 
775  bool IsFullOutboundConn() const {
776  return m_conn_type == ConnectionType::OUTBOUND_FULL_RELAY;
777  }
778 
779  bool IsManualConn() const {
780  return m_conn_type == ConnectionType::MANUAL;
781  }
782 
784  {
785  switch (m_conn_type) {
790  return false;
793  return true;
794  } // no default case, so the compiler can warn about missing cases
795 
796  assert(false);
797  }
798 
799  bool IsBlockOnlyConn() const {
800  return m_conn_type == ConnectionType::BLOCK_RELAY;
801  }
802 
803  bool IsFeelerConn() const {
804  return m_conn_type == ConnectionType::FEELER;
805  }
806 
807  bool IsAddrFetchConn() const {
808  return m_conn_type == ConnectionType::ADDR_FETCH;
809  }
810 
811  bool IsInboundConn() const {
812  return m_conn_type == ConnectionType::INBOUND;
813  }
814 
815  bool ExpectServicesFromConn() const {
816  switch (m_conn_type) {
820  return false;
824  return true;
825  } // no default case, so the compiler can warn about missing cases
826 
827  assert(false);
828  }
829 
840  Network ConnectedThroughNetwork() const;
841 
843  [[nodiscard]] bool IsConnectedThroughPrivacyNet() const;
844 
845  // We selected peer as (compact blocks) high-bandwidth peer (BIP152)
846  std::atomic<bool> m_bip152_highbandwidth_to{false};
847  // Peer selected us as (compact blocks) high-bandwidth peer (BIP152)
848  std::atomic<bool> m_bip152_highbandwidth_from{false};
849 
851  std::atomic_bool m_has_all_wanted_services{false};
852 
855  std::atomic_bool m_relays_txs{false};
856 
859  std::atomic_bool m_bloom_filter_loaded{false};
860 
866  std::atomic<std::chrono::seconds> m_last_block_time{0s};
867 
872  std::atomic<std::chrono::seconds> m_last_tx_time{0s};
873 
875  std::atomic<std::chrono::microseconds> m_last_ping_time{0us};
876 
879  std::atomic<std::chrono::microseconds> m_min_ping_time{std::chrono::microseconds::max()};
880 
881  CNode(NodeId id,
882  std::shared_ptr<Sock> sock,
883  const CAddress& addrIn,
884  uint64_t nKeyedNetGroupIn,
885  uint64_t nLocalHostNonceIn,
886  const CService& addrBindIn,
887  const std::string& addrNameIn,
888  ConnectionType conn_type_in,
889  bool inbound_onion,
890  CNodeOptions&& node_opts = {});
891  CNode(const CNode&) = delete;
892  CNode& operator=(const CNode&) = delete;
893 
894  NodeId GetId() const {
895  return id;
896  }
897 
898  uint64_t GetLocalNonce() const {
899  return nLocalHostNonce;
900  }
901 
902  int GetRefCount() const
903  {
904  assert(nRefCount >= 0);
905  return nRefCount;
906  }
907 
917  bool ReceiveMsgBytes(Span<const uint8_t> msg_bytes, bool& complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv);
918 
919  void SetCommonVersion(int greatest_common_version)
920  {
921  Assume(m_greatest_common_version == INIT_PROTO_VERSION);
922  m_greatest_common_version = greatest_common_version;
923  }
924  int GetCommonVersion() const
925  {
926  return m_greatest_common_version;
927  }
928 
929  CService GetAddrLocal() const EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex);
931  void SetAddrLocal(const CService& addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex);
932 
933  CNode* AddRef()
934  {
935  nRefCount++;
936  return this;
937  }
938 
939  void Release()
940  {
941  nRefCount--;
942  }
943 
944  void CloseSocketDisconnect() EXCLUSIVE_LOCKS_REQUIRED(!m_sock_mutex);
945 
946  void CopyStats(CNodeStats& stats) EXCLUSIVE_LOCKS_REQUIRED(!m_subver_mutex, !m_addr_local_mutex, !cs_vSend, !cs_vRecv);
947 
949 
956  std::string LogIP(bool log_ip) const;
957 
964  std::string DisconnectMsg(bool log_ip) const;
965 
967  void PongReceived(std::chrono::microseconds ping_time) {
968  m_last_ping_time = ping_time;
969  m_min_ping_time = std::min(m_min_ping_time.load(), ping_time);
970  }
971 
972 private:
973  const NodeId id;
974  const uint64_t nLocalHostNonce;
975  std::atomic<int> m_greatest_common_version{INIT_PROTO_VERSION};
976 
977  const size_t m_recv_flood_size;
978  std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
979 
981  std::list<CNetMessage> m_msg_process_queue GUARDED_BY(m_msg_process_queue_mutex);
982  size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex){0};
983 
984  // Our address, as reported by the peer
985  CService m_addr_local GUARDED_BY(m_addr_local_mutex);
987 
988  mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend);
989  mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv);
990 
1001  std::unique_ptr<i2p::sam::Session> m_i2p_sam_session GUARDED_BY(m_sock_mutex);
1002 };
1003 
1008 {
1009 public:
1012 
1014  virtual void InitializeNode(const CNode& node, ServiceFlags our_services) = 0;
1015 
1017  virtual void FinalizeNode(const CNode& node) = 0;
1018 
1023  virtual bool HasAllDesirableServiceFlags(ServiceFlags services) const = 0;
1024 
1032  virtual bool ProcessMessages(CNode* pnode, std::atomic<bool>& interrupt) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) = 0;
1033 
1040  virtual bool SendMessages(CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) = 0;
1041 
1042 
1043 protected:
1048  ~NetEventsInterface() = default;
1049 };
1050 
1052 {
1053 public:
1054 
1055  struct Options
1056  {
1057  ServiceFlags m_local_services = NODE_NONE;
1058  int m_max_automatic_connections = 0;
1060  NetEventsInterface* m_msgproc = nullptr;
1061  BanMan* m_banman = nullptr;
1062  unsigned int nSendBufferMaxSize = 0;
1063  unsigned int nReceiveFloodSize = 0;
1064  uint64_t nMaxOutboundLimit = 0;
1065  int64_t m_peer_connect_timeout = DEFAULT_PEER_CONNECT_TIMEOUT;
1066  std::vector<std::string> vSeedNodes;
1067  std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
1068  std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
1069  std::vector<NetWhitebindPermissions> vWhiteBinds;
1070  std::vector<CService> vBinds;
1071  std::vector<CService> onion_binds;
1075  bool m_use_addrman_outgoing = true;
1076  std::vector<std::string> m_specified_outgoing;
1077  std::vector<std::string> m_added_nodes;
1079  bool whitelist_forcerelay = DEFAULT_WHITELISTFORCERELAY;
1080  bool whitelist_relay = DEFAULT_WHITELISTRELAY;
1081  };
1082 
1083  void Init(const Options& connOptions) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex, !m_total_bytes_sent_mutex)
1084  {
1085  AssertLockNotHeld(m_total_bytes_sent_mutex);
1086 
1087  m_local_services = connOptions.m_local_services;
1088  m_max_automatic_connections = connOptions.m_max_automatic_connections;
1089  m_max_outbound_full_relay = std::min(MAX_OUTBOUND_FULL_RELAY_CONNECTIONS, m_max_automatic_connections);
1090  m_max_outbound_block_relay = std::min(MAX_BLOCK_RELAY_ONLY_CONNECTIONS, m_max_automatic_connections - m_max_outbound_full_relay);
1091  m_max_automatic_outbound = m_max_outbound_full_relay + m_max_outbound_block_relay + m_max_feeler;
1092  m_max_inbound = std::max(0, m_max_automatic_connections - m_max_automatic_outbound);
1093  m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
1094  m_client_interface = connOptions.uiInterface;
1095  m_banman = connOptions.m_banman;
1096  m_msgproc = connOptions.m_msgproc;
1097  nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
1098  nReceiveFloodSize = connOptions.nReceiveFloodSize;
1099  m_peer_connect_timeout = std::chrono::seconds{connOptions.m_peer_connect_timeout};
1100  {
1101  LOCK(m_total_bytes_sent_mutex);
1102  nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
1103  }
1104  vWhitelistedRangeIncoming = connOptions.vWhitelistedRangeIncoming;
1105  vWhitelistedRangeOutgoing = connOptions.vWhitelistedRangeOutgoing;
1106  {
1107  LOCK(m_added_nodes_mutex);
1108  // Attempt v2 connection if we support v2 - we'll reconnect with v1 if our
1109  // peer doesn't support it or immediately disconnects us for another reason.
1110  const bool use_v2transport(GetLocalServices() & NODE_P2P_V2);
1111  for (const std::string& added_node : connOptions.m_added_nodes) {
1112  m_added_node_params.push_back({added_node, use_v2transport});
1113  }
1114  }
1115  m_onion_binds = connOptions.onion_binds;
1116  whitelist_forcerelay = connOptions.whitelist_forcerelay;
1117  whitelist_relay = connOptions.whitelist_relay;
1118  }
1119 
1120  CConnman(uint64_t seed0, uint64_t seed1, AddrMan& addrman, const NetGroupManager& netgroupman,
1121  const CChainParams& params, bool network_active = true);
1122 
1123  ~CConnman();
1124 
1125  bool Start(CScheduler& scheduler, const Options& options) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !m_added_nodes_mutex, !m_addr_fetches_mutex, !mutexMsgProc);
1126 
1127  void StopThreads();
1128  void StopNodes();
1129  void Stop()
1130  {
1131  StopThreads();
1132  StopNodes();
1133  };
1134 
1135  void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);
1136  bool GetNetworkActive() const { return fNetworkActive; };
1137  bool GetUseAddrmanOutgoing() const { return m_use_addrman_outgoing; };
1138  void SetNetworkActive(bool active);
1139  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);
1140  bool CheckIncomingNonce(uint64_t nonce);
1141  void ASMapHealthCheck();
1142 
1143  // alias for thread safety annotations only, not defined
1144  RecursiveMutex& GetNodesMutex() const LOCK_RETURNED(m_nodes_mutex);
1145 
1146  bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
1147 
1148  void PushMessage(CNode* pnode, CSerializedNetMsg&& msg) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1149 
1150  using NodeFn = std::function<void(CNode*)>;
1151  void ForEachNode(const NodeFn& func)
1152  {
1153  LOCK(m_nodes_mutex);
1154  for (auto&& node : m_nodes) {
1155  if (NodeFullyConnected(node))
1156  func(node);
1157  }
1158  };
1159 
1160  void ForEachNode(const NodeFn& func) const
1161  {
1162  LOCK(m_nodes_mutex);
1163  for (auto&& node : m_nodes) {
1164  if (NodeFullyConnected(node))
1165  func(node);
1166  }
1167  };
1168 
1169  // Addrman functions
1178  std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct, std::optional<Network> network, const bool filtered = true) const;
1185  std::vector<CAddress> GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct);
1186 
1187  // This allows temporarily exceeding m_max_outbound_full_relay, with the goal of finding
1188  // a peer that is better than all our current peers.
1189  void SetTryNewOutboundPeer(bool flag);
1190  bool GetTryNewOutboundPeer() const;
1191 
1192  void StartExtraBlockRelayPeers();
1193 
1194  // Count the number of full-relay peer we have.
1195  int GetFullOutboundConnCount() const;
1196  // Return the number of outbound peers we have in excess of our target (eg,
1197  // if we previously called SetTryNewOutboundPeer(true), and have since set
1198  // to false, we may have extra peers that we wish to disconnect). This may
1199  // return a value less than (num_outbound_connections - num_outbound_slots)
1200  // in cases where some outbound connections are not yet fully connected, or
1201  // not yet fully disconnected.
1202  int GetExtraFullOutboundCount() const;
1203  // Count the number of block-relay-only peers we have over our limit.
1204  int GetExtraBlockRelayCount() const;
1205 
1206  bool AddNode(const AddedNodeParams& add) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1207  bool RemoveAddedNode(const std::string& node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1208  bool AddedNodesContain(const CAddress& addr) const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1209  std::vector<AddedNodeInfo> GetAddedNodeInfo(bool include_connected) const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1210 
1224  bool AddConnection(const std::string& address, ConnectionType conn_type, bool use_v2transport) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex);
1225 
1226  size_t GetNodeCount(ConnectionDirection) const;
1227  std::map<CNetAddr, LocalServiceInfo> getNetLocalAddresses() const;
1228  uint32_t GetMappedAS(const CNetAddr& addr) const;
1229  void GetNodeStats(std::vector<CNodeStats>& vstats) const;
1230  bool DisconnectNode(const std::string& node);
1231  bool DisconnectNode(const CSubNet& subnet);
1232  bool DisconnectNode(const CNetAddr& addr);
1233  bool DisconnectNode(NodeId id);
1234 
1241  ServiceFlags GetLocalServices() const;
1242 
1245  void AddLocalServices(ServiceFlags services) { m_local_services = ServiceFlags(m_local_services | services); };
1246  void RemoveLocalServices(ServiceFlags services) { m_local_services = ServiceFlags(m_local_services & ~services); }
1247 
1248  uint64_t GetMaxOutboundTarget() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1249  std::chrono::seconds GetMaxOutboundTimeframe() const;
1250 
1254  bool OutboundTargetReached(bool historicalBlockServingLimit) const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1255 
1258  uint64_t GetOutboundTargetBytesLeft() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1259 
1260  std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1261 
1262  uint64_t GetTotalBytesRecv() const;
1263  uint64_t GetTotalBytesSent() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1264 
1266  CSipHasher GetDeterministicRandomizer(uint64_t id) const;
1267 
1268  void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);
1269 
1271  bool ShouldRunInactivityChecks(const CNode& node, std::chrono::seconds now) const;
1272 
1273  bool MultipleManualOrFullOutboundConns(Network net) const EXCLUSIVE_LOCKS_REQUIRED(m_nodes_mutex);
1274 
1275 private:
1276  struct ListenSocket {
1277  public:
1278  std::shared_ptr<Sock> sock;
1280  ListenSocket(std::shared_ptr<Sock> sock_, NetPermissionFlags permissions_)
1281  : sock{sock_}, m_permissions{permissions_}
1282  {
1283  }
1284 
1285  private:
1287  };
1288 
1291  std::chrono::seconds GetMaxOutboundTimeLeftInCycle_() const EXCLUSIVE_LOCKS_REQUIRED(m_total_bytes_sent_mutex);
1292 
1293  bool BindListenPort(const CService& bindAddr, bilingual_str& strError, NetPermissionFlags permissions);
1294  bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions);
1295  bool InitBinds(const Options& options);
1296 
1297  void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex, !m_unused_i2p_sessions_mutex, !m_reconnections_mutex);
1298  void AddAddrFetch(const std::string& strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex);
1299  void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex, !m_unused_i2p_sessions_mutex);
1300  void ThreadOpenConnections(std::vector<std::string> connect, Span<const std::string> seed_nodes) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex, !m_added_nodes_mutex, !m_nodes_mutex, !m_unused_i2p_sessions_mutex, !m_reconnections_mutex);
1301  void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);
1302  void ThreadI2PAcceptIncoming();
1303  void AcceptConnection(const ListenSocket& hListenSocket);
1304 
1313  void CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock,
1314  NetPermissionFlags permission_flags,
1315  const CService& addr_bind,
1316  const CService& addr);
1317 
1318  void DisconnectNodes() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex, !m_nodes_mutex);
1319  void NotifyNumConnectionsChanged();
1321  bool InactivityCheck(const CNode& node) const;
1322 
1328  Sock::EventsPerSock GenerateWaitSockets(Span<CNode* const> nodes);
1329 
1333  void SocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !mutexMsgProc);
1334 
1340  void SocketHandlerConnected(const std::vector<CNode*>& nodes,
1341  const Sock::EventsPerSock& events_per_sock)
1342  EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !mutexMsgProc);
1343 
1348  void SocketHandlerListening(const Sock::EventsPerSock& events_per_sock);
1349 
1350  void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !mutexMsgProc, !m_nodes_mutex, !m_reconnections_mutex);
1351  void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex, !m_nodes_mutex);
1352 
1353  uint64_t CalculateKeyedNetGroup(const CNetAddr& ad) const;
1354 
1355  CNode* FindNode(const CNetAddr& ip);
1356  CNode* FindNode(const std::string& addrName);
1357  CNode* FindNode(const CService& addr);
1358 
1363  bool AlreadyConnectedToAddress(const CAddress& addr);
1364 
1365  bool AttemptToEvictConnection();
1366  CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type, bool use_v2transport) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex);
1367  void AddWhitelistPermissionFlags(NetPermissionFlags& flags, const CNetAddr &addr, const std::vector<NetWhitelistPermissions>& ranges) const;
1368 
1369  void DeleteNode(CNode* pnode);
1370 
1371  NodeId GetNewNodeId();
1372 
1374  std::pair<size_t, bool> SocketSendData(CNode& node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend);
1375 
1376  void DumpAddresses();
1377 
1378  // Network stats
1379  void RecordBytesRecv(uint64_t bytes);
1380  void RecordBytesSent(uint64_t bytes) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1381 
1386  std::unordered_set<Network> GetReachableEmptyNetworks() const;
1387 
1391  std::vector<CAddress> GetCurrentBlockRelayOnlyConns() const;
1392 
1403  bool MaybePickPreferredNetwork(std::optional<Network>& network);
1404 
1405  // Whether the node should be passed out in ForEach* callbacks
1406  static bool NodeFullyConnected(const CNode* pnode);
1407 
1408  uint16_t GetDefaultPort(Network net) const;
1409  uint16_t GetDefaultPort(const std::string& addr) const;
1410 
1411  // Network usage totals
1412  mutable Mutex m_total_bytes_sent_mutex;
1413  std::atomic<uint64_t> nTotalBytesRecv{0};
1414  uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex) {0};
1415 
1416  // outbound limit & stats
1417  uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex) {0};
1418  std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex) {0};
1419  uint64_t nMaxOutboundLimit GUARDED_BY(m_total_bytes_sent_mutex);
1420 
1421  // P2P timeout in seconds
1422  std::chrono::seconds m_peer_connect_timeout;
1423 
1424  // Whitelisted ranges. Any node connecting from these is automatically
1425  // whitelisted (as well as those connecting to whitelisted binds).
1426  std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
1427  // Whitelisted ranges for outgoing connections.
1428  std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
1429 
1430  unsigned int nSendBufferMaxSize{0};
1431  unsigned int nReceiveFloodSize{0};
1432 
1433  std::vector<ListenSocket> vhListenSocket;
1434  std::atomic<bool> fNetworkActive{true};
1435  bool fAddressesInitialized{false};
1438  std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
1440 
1441  // connection string and whether to use v2 p2p
1442  std::vector<AddedNodeParams> m_added_node_params GUARDED_BY(m_added_nodes_mutex);
1443 
1445  std::vector<CNode*> m_nodes GUARDED_BY(m_nodes_mutex);
1446  std::list<CNode*> m_nodes_disconnected;
1448  std::atomic<NodeId> nLastNodeId{0};
1449  unsigned int nPrevNodeCount{0};
1450 
1451  // Stores number of full-tx connections (outbound and manual) per network
1452  std::array<unsigned int, Network::NET_MAX> m_network_conn_counts GUARDED_BY(m_nodes_mutex) = {};
1453 
1461  std::vector<CAddress> m_addrs_response_cache;
1462  std::chrono::microseconds m_cache_entry_expiration{0};
1463  };
1464 
1479  std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
1480 
1492  std::atomic<ServiceFlags> m_local_services;
1493 
1494  std::unique_ptr<CSemaphore> semOutbound;
1495  std::unique_ptr<CSemaphore> semAddnode;
1496 
1503 
1504  /*
1505  * Maximum number of peers by connection type. Might vary from defaults
1506  * based on -maxconnections init value.
1507  */
1508 
1509  // How many full-relay (tx, block, addr) outbound peers we want
1511 
1512  // How many block-relay only outbound peers we want
1513  // We do not relay tx or addr messages with these peers
1515 
1516  int m_max_addnode{MAX_ADDNODE_CONNECTIONS};
1517  int m_max_feeler{MAX_FEELER_CONNECTIONS};
1520 
1526 
1531  std::vector<CAddress> m_anchors;
1532 
1534  const uint64_t nSeed0, nSeed1;
1535 
1537  bool fMsgProcWake GUARDED_BY(mutexMsgProc);
1538 
1539  std::condition_variable condMsgProc;
1541  std::atomic<bool> flagInterruptMsgProc{false};
1542 
1550 
1556  std::unique_ptr<i2p::sam::Session> m_i2p_sam_session;
1557 
1559  std::thread threadSocketHandler;
1564 
1569 
1574  std::atomic_bool m_start_extra_block_relay_peers{false};
1575 
1580  std::vector<CService> m_onion_binds;
1581 
1587 
1593 
1598 
1606  std::queue<std::unique_ptr<i2p::sam::Session>> m_unused_i2p_sessions GUARDED_BY(m_unused_i2p_sessions_mutex);
1607 
1612 
1615  {
1618  std::string destination;
1621  };
1622 
1626  std::list<ReconnectionInfo> m_reconnections GUARDED_BY(m_reconnections_mutex);
1627 
1629  void PerformReconnections() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex, !m_unused_i2p_sessions_mutex);
1630 
1635  static constexpr size_t MAX_UNUSED_I2P_SESSIONS_SIZE{10};
1636 
1642  {
1643  public:
1644  explicit NodesSnapshot(const CConnman& connman, bool shuffle)
1645  {
1646  {
1647  LOCK(connman.m_nodes_mutex);
1648  m_nodes_copy = connman.m_nodes;
1649  for (auto& node : m_nodes_copy) {
1650  node->AddRef();
1651  }
1652  }
1653  if (shuffle) {
1654  std::shuffle(m_nodes_copy.begin(), m_nodes_copy.end(), FastRandomContext{});
1655  }
1656  }
1657 
1659  {
1660  for (auto& node : m_nodes_copy) {
1661  node->Release();
1662  }
1663  }
1664 
1665  const std::vector<CNode*>& Nodes() const
1666  {
1667  return m_nodes_copy;
1668  }
1669 
1670  private:
1671  std::vector<CNode*> m_nodes_copy;
1672  };
1673 
1675 
1676  friend struct ConnmanTestMsg;
1677 };
1678 
1680 extern std::function<void(const CAddress& addr,
1681  const std::string& msg_type,
1683  bool is_incoming)>
1685 
1686 #endif // BITCOIN_NET_H
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition: net.h:1011
std::chrono::microseconds m_min_ping_time
Definition: net.h:208
std::vector< CService > vBinds
Definition: net.h:1070
std::vector< CAddress > m_addrs_response_cache
Definition: net.h:1461
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:71
Mutex m_send_mutex
Lock for sending state.
Definition: net.h:406
std::string m_type
Definition: net.h:131
const std::string m_dest
The pszDest argument provided to ConnectNode().
Definition: net.h:713
int ret
AddrFetch connections are short lived connections used to solicit addresses from peers.
CNetMessage(DataStream &&recv_in)
Definition: net.h:239
static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH
Maximum length of incoming protocol messages (no message over 4 MB is currently acceptable).
Definition: net.h:63
BIP324Cipher m_cipher
Cipher state.
Definition: net.h:576
bool m_i2p_accept_incoming
Definition: net.h:1078
CSemaphoreGrant grant
Definition: net.h:1617
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:414
Mutex m_addr_local_mutex
Definition: net.h:986
AssertLockHeld(pool.cs)
mapMsgTypeSize mapSendBytesPerMsgType
Definition: net.h:203
Definition: banman.h:58
static void AddFlag(NetPermissionFlags &flags, NetPermissionFlags f)
ServiceFlags
nServices flags
Definition: protocol.h:309
ConnectionType conn_type
Definition: net.h:1619
CClientUIInterface uiInterface
Inbound connections are those initiated by a peer.
assert(!tx.IsCoinBase())
bool fListen
Definition: net.cpp:123
uint32_t m_mapped_as
Definition: net.h:217
Unencrypted, plaintext protocol.
unsigned int nonce
Definition: miner_tests.cpp:75
Feeler connections are short-lived connections made to check that a node is alive.
std::shared_ptr< Sock > sock
Definition: net.h:1278
bool m_sending_header GUARDED_BY(m_send_mutex)
Whether we&#39;re currently sending header bytes or message bytes.
Definition: net.h:412
std::list< CNode * > m_nodes_disconnected
Definition: net.h:1446
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:692
Mutex mutexMsgProc
Definition: net.h:1540
const uint64_t nKeyedNetGroup
Definition: net.h:735
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:182
int m_max_automatic_outbound
Definition: net.h:1518
bool IsOutboundOrBlockRelayConn() const
Definition: net.h:760
const std::chrono::seconds m_connected
Unix epoch time at peer connection.
Definition: net.h:706
int m_max_automatic_connections
Maximum number of automatic connections permitted, excluding manual connections but including inbound...
Definition: net.h:1502
std::vector< unsigned char > data
Definition: net.h:130
AddedNodeParams m_params
Definition: net.h:105
const ConnectionType m_conn_type
Definition: net.h:739
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:604
std::string destination
Definition: net.h:1618
bool IsFeelerConn() const
Definition: net.h:803
uint16_t GetListenPort()
Definition: net.cpp:144
int m_max_outbound_full_relay
Definition: net.h:1510
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:1580
DataStream hdrbuf GUARDED_BY(m_recv_mutex)
Definition: net.h:376
#define LOCK_RETURNED(x)
Definition: threadsafety.h:47
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:75
RAII-style semaphore lock.
Definition: sync.h:352
void SetCommonVersion(int greatest_common_version)
Definition: net.h:919
Interrupt(node)
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:69
void AddLocalServices(ServiceFlags services)
Updates the local services that this node advertises to other peers during connection handshake...
Definition: net.h:1245
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
Definition: net.cpp:246
std::string cleanSubVer
Definition: net.h:195
Interface for message handling.
Definition: net.h:1007
const std::string KEY
Definition: walletdb.cpp:48
static const unsigned char VERSION[]
Definition: netaddress.cpp:187
NetEventsInterface * m_msgproc
Definition: net.h:1523
const NodeId m_nodeid
NodeId (for debug logging).
Definition: net.h:580
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:1160
int m_max_outbound_block_relay
Definition: net.h:1514
Mutex m_subver_mutex
Definition: net.h:717
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:189
size_t GetMemoryUsage() const noexcept
Compute total memory usage of this object (own memory + any dynamic memory).
Definition: net.cpp:128
static const int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
uint64_t GetLocalNonce() const
Definition: net.h:898
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:612
NetPermissionFlags
V1Transport m_v1_fallback
Encapsulate a V1Transport to fall back to.
Definition: net.h:582
ConnectionType m_conn_type
Definition: net.h:218
These are the default connections that we use to connect with the network.
DataStream vRecv GUARDED_BY(m_recv_mutex)
Definition: net.h:378
AddrMan & addrman
Definition: net.h:1436
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Total number of bytes sent on the wire to this peer.
Definition: net.h:694
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:154
Signals for UI communication.
Definition: interface_ui.h:25
std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex)
Definition: net.h:1418
static constexpr std::chrono::minutes TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:57
std::list< CNetMessage > vRecvMsg
Definition: net.h:978
const NodeId m_node_id
Definition: net.h:371
SendState
State type that controls the sender side.
Definition: net.h:545
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:1479
#define ACQUIRED_AFTER(...)
Definition: threadsafety.h:40
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition: net.h:73
static bool HasFlag(NetPermissionFlags flags, NetPermissionFlags f)
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition: net.h:1426
Stochastic address manager.
Definition: addrman.h:88
bool fConnected
Definition: net.h:107
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition: net.h:1279
int GetRefCount() const
Definition: net.h:902
NetPermissionFlags m_permission_flags
Definition: net.h:206
Mutex m_unused_i2p_sessions_mutex
Mutex protecting m_i2p_sam_sessions.
Definition: net.h:1597
uint16_t nPort
Definition: net.h:175
TransportProtocolType m_transport_type
Transport protocol type.
Definition: net.h:220
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:4018
std::array< uint8_t, 4 > MessageStartChars
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:92
Mutex m_sock_mutex
Definition: net.h:698
std::thread threadI2PAcceptIncoming
Definition: net.h:1563
std::tuple< Span< const uint8_t >, bool, const std::string &> BytesToSend
Return type for GetBytesToSend, consisting of:
Definition: net.h:311
bool CompleteInternal() const noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Definition: net.h:398
DataStream m_recv
received message data
Definition: net.h:233
CService GetLocalAddress(const CNode &peer)
Definition: net.cpp:226
int nVersion
Definition: net.h:194
CSerializedNetMsg Copy() const
Definition: net.h:122
int m_max_inbound
Definition: net.h:1519
std::optional< uint256 > session_id
Definition: net.h:261
ListenSocket(std::shared_ptr< Sock > sock_, NetPermissionFlags permissions_)
Definition: net.h:1280
void Release()
Definition: net.h:939
static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it)
Definition: txmempool.cpp:847
constexpr bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
std::condition_variable condMsgProc
Definition: net.h:1539
const std::unique_ptr< Transport > m_transport
Transport serializer/deserializer.
Definition: net.h:677
std::chrono::seconds m_connected
Definition: net.h:192
bool IsManualOrFullOutboundConn() const
Definition: net.h:783
Mutex m_added_nodes_mutex
Definition: net.h:1444
GlobalMutex g_maplocalhost_mutex
Definition: net.cpp:124
We open manual connections to addresses that users explicitly requested via the addnode RPC or the -a...
int m_starting_height
Definition: net.h:201
std::thread threadOpenAddedConnections
Definition: net.h:1560
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
#define LOCK(cs)
Definition: sync.h:257
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:146
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition: net.h:1067
const CService addrBind
Definition: net.h:710
std::function< void(CNode *)> NodeFn
Definition: net.h:1150
std::string m_added_node
Definition: net.h:100
TransportProtocolType transport_type
Definition: net.h:260
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:530
Fast randomness source.
Definition: random.h:376
Transport protocol agnostic message container.
Definition: net.h:230
bool whitelist_forcerelay
flag for adding &#39;forcerelay&#39; permission to whitelisted inbound and manual peers with default permissi...
Definition: net.h:1586
std::vector< std::string > vSeedNodes
Definition: net.h:1066
std::vector< std::string > m_specified_outgoing
Definition: net.h:1076
bool m_bip152_highbandwidth_from
Definition: net.h:200
uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex)
Definition: net.h:1417
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:1494
std::thread threadMessageHandler
Definition: net.h:1562
void RemoveLocalServices(ServiceFlags services)
Definition: net.h:1246
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
Definition: net.h:85
Network m_network
Definition: net.h:216
bool fInbound
Definition: net.h:196
bool IsManualConn() const
Definition: net.h:779
std::chrono::microseconds m_last_ping_time
Definition: net.h:207
A CService with information about it as peer.
Definition: protocol.h:366
std::chrono::seconds m_last_tx_time
Definition: net.h:190
uint64_t nRecvBytes
Definition: net.h:204
static constexpr bool DEFAULT_FIXEDSEEDS
Definition: net.h:91
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(g_maplocalhost_mutex)
bool fInbound
Definition: net.h:108
Network
A network type.
Definition: netaddress.h:32
static CService ip(uint32_t i)
bool m_bip152_highbandwidth_to
Definition: net.h:198
bool ExpectServicesFromConn() const
Definition: net.h:815
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:1568
int64_t NodeId
Definition: net.h:97
Definition: net.h:1051
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:77
static constexpr bool DEFAULT_V2_TRANSPORT
Definition: net.h:95
static constexpr bool DEFAULT_DNSSEED
Definition: net.h:90
const CChainParams & m_params
Definition: net.h:1674
Mutex m_recv_mutex
Lock for receive state.
Definition: net.h:372
const bool m_initiating
Whether we are the initiator side.
Definition: net.h:578
const NetPermissionFlags m_permission_flags
Definition: net.h:679
std::chrono::seconds m_last_send
Definition: net.h:188
NodeId GetId() const
Definition: net.h:894
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e. connected via our Tor onion service.
Definition: net.h:715
uint64_t nSendBytes
Definition: net.h:202
void PongReceived(std::chrono::microseconds ping_time)
A ping-pong round trip has completed successfully.
Definition: net.h:967
A helper class for interruptible sleeps.
mapMsgTypeSize mapRecvBytesPerMsgType
Definition: net.h:205
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:301
#define Assume(val)
Assume is the identity function.
Definition: check.h:97
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Definition: net.h:701
RecursiveMutex m_nodes_mutex
Definition: net.h:1447
const size_t m_recv_flood_size
Definition: net.h:977
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:3183
static constexpr std::chrono::hours ASMAP_HEALTH_CHECK_INTERVAL
Interval for ASMap Health Check.
Definition: net.h:87
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
Definition: net.h:1556
NetPermissionFlags m_permissions
Definition: net.h:1286
Definition: messages.h:20
const CAddress addr
Definition: net.h:708
bool IsBlockOnlyConn() const
Definition: net.h:799
std::atomic< ServiceFlags > m_local_services
Services this node offers.
Definition: net.h:1492
Mutex m_addr_fetches_mutex
Definition: net.h:1439
int flags
Definition: bitcoin-tx.cpp:536
Network address.
Definition: netaddress.h:111
256-bit opaque blob.
Definition: uint256.h:201
void RemoveLocal(const CService &addr)
Definition: net.cpp:310
std::vector< CService > onion_binds
Definition: net.h:1071
int nScore
Definition: net.h:174
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
The Transport converts one connection&#39;s sent messages to wire bytes, and received bytes back...
Definition: net.h:254
BanMan * m_banman
Pointer to this node&#39;s banman.
Definition: net.h:1525
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:93
Mutex cs_vRecv
Definition: net.h:699
CService resolvedAddress
Definition: net.h:106
std::thread threadOpenConnections
Definition: net.h:1561
std::chrono::seconds m_peer_connect_timeout
Definition: net.h:1422
CSemaphoreGrant grantOutbound
Definition: net.h:732
const NodeId id
Definition: net.h:973
std::string m_type
Definition: net.h:237
std::string addrLocal
Definition: net.h:210
std::thread threadDNSAddressSeed
Definition: net.h:1558
#define ACQUIRED_BEFORE(...)
Definition: threadsafety.h:41
std::vector< std::string > m_added_nodes
Definition: net.h:1077
std::vector< ListenSocket > vhListenSocket
Definition: net.h:1433
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition: net.h:1428
Mutex cs_vSend
Definition: net.h:697
CService addrBind
Definition: net.h:214
std::chrono::seconds m_last_block_time
Definition: net.h:191
static constexpr bool DEFAULT_FORCEDNSSEED
Definition: net.h:89
SipHash-2-4.
Definition: siphash.h:14
#define AssertLockNotHeld(cs)
Definition: sync.h:147
std::string m_session_id
BIP324 session id string in hex, if any.
Definition: net.h:222
size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex)
Definition: net.h:982
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:65
RecvState
State type that defines the current contents of the receive buffer and/or how the next received bytes...
Definition: net.h:480
static constexpr auto FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes.
Definition: net.h:59
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition: net.h:83
const std::string NET_MESSAGE_TYPE_OTHER
Definition: net.cpp:114
static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL
Run the extra block-relay-only connection loop once every 5 minutes.
Definition: net.h:61
uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex)
Definition: net.h:1414
ConnectionType
Different types of connections to a peer.
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:81
const uint64_t nLocalHostNonce
Definition: net.h:974
Mutex m_msg_process_queue_mutex
Definition: net.h:980
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:1671
Mutex m_reconnections_mutex
Mutex protecting m_reconnections.
Definition: net.h:1611
bool IsAddrFetchConn() const
Definition: net.h:807
std::string m_addr_name
Definition: net.h:193
RAII helper to atomically create a copy of m_nodes and add a reference to each of the nodes...
Definition: net.h:1641
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we&#39;ll relay everything (blocks, tx, addrs, etc)
Definition: net.h:67
An encapsulated private key.
Definition: key.h:34
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:97
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:126
Different type to mark Mutex at global scope.
Definition: sync.h:140
Definition: net.h:149
NodesSnapshot(const CConnman &connman, bool shuffle)
Definition: net.h:1644
Information about a peer.
Definition: net.h:672
std::thread threadSocketHandler
Definition: net.h:1559
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:1614
bool fDiscover
Definition: net.cpp:122
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
Definition: net.h:1531
bool m_use_v2transport
Definition: net.h:101
const NetGroupManager & m_netgroupman
Definition: net.h:1437
int GetCommonVersion() const
Definition: net.h:924
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
const std::string m_addr_name
Definition: net.h:711
std::unique_ptr< CSemaphore > semAddnode
Definition: net.h:1495
CThreadInterrupt interruptNet
This is signaled when network activity should cease.
Definition: net.h:1549
const MessageStartChars m_magic_bytes
Definition: net.h:370
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:419
ConnectionDirection
Definition: netbase.h:33
bool HasPermission(NetPermissionFlags permission) const
Definition: net.h:724
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
Definition: net.cpp:277
bool IsInboundConn() const
Definition: net.h:811
const uint64_t nSeed1
Definition: net.h:1534
void Stop()
Definition: net.h:1129
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:1069
bool whitelist_relay
flag for adding &#39;relay&#39; permission to whitelisted inbound and manual peers with default permissions...
Definition: net.h:1592
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:588
const std::vector< CNode * > & Nodes() const
Definition: net.h:1665
bool GetUseAddrmanOutgoing() const
Definition: net.h:1137
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0...
Definition: net.h:1074
bool m_use_addrman_outgoing
Definition: net.h:1521
Cache responses to addr requests to minimize privacy leak.
Definition: net.h:1460
bool IsFullOutboundConn() const
Definition: net.h:775
NodeId nodeid
Definition: net.h:187
We use block-relay-only connections to help prevent against partition attacks.
CClientUIInterface * m_client_interface
Definition: net.h:1522
CAddress addr
Definition: net.h:212
Message header.
Definition: protocol.h:28
static const std::string DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:79
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition: net.h:1068
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:722