Bitcoin Core  24.99.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 <chainparams.h>
10 #include <common/bloom.h>
11 #include <compat/compat.h>
12 #include <node/connection_types.h>
13 #include <consensus/amount.h>
14 #include <crypto/siphash.h>
15 #include <hash.h>
16 #include <i2p.h>
17 #include <net_permissions.h>
18 #include <netaddress.h>
19 #include <netbase.h>
20 #include <netgroup.h>
21 #include <policy/feerate.h>
22 #include <protocol.h>
23 #include <random.h>
24 #include <span.h>
25 #include <streams.h>
26 #include <sync.h>
27 #include <uint256.h>
28 #include <util/check.h>
29 #include <util/sock.h>
30 #include <util/threadinterrupt.h>
31 
32 #include <atomic>
33 #include <condition_variable>
34 #include <cstdint>
35 #include <deque>
36 #include <functional>
37 #include <list>
38 #include <map>
39 #include <memory>
40 #include <optional>
41 #include <thread>
42 #include <unordered_set>
43 #include <vector>
44 
45 class AddrMan;
46 class BanMan;
47 class CNode;
48 class CScheduler;
49 struct bilingual_str;
50 
52 static const bool DEFAULT_WHITELISTRELAY = true;
54 static const bool DEFAULT_WHITELISTFORCERELAY = false;
55 
57 static constexpr std::chrono::minutes TIMEOUT_INTERVAL{20};
59 static constexpr auto FEELER_INTERVAL = 2min;
61 static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL = 5min;
63 static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
65 static const unsigned int MAX_SUBVERSION_LENGTH = 256;
69 static const int MAX_ADDNODE_CONNECTIONS = 8;
71 static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS = 2;
73 static const int MAX_FEELER_CONNECTIONS = 1;
75 static const bool DEFAULT_LISTEN = true;
77 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
79 static const std::string DEFAULT_MAX_UPLOAD_TARGET{"0M"};
81 static const bool DEFAULT_BLOCKSONLY = false;
83 static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
85 static const int NUM_FDS_MESSAGE_CAPTURE = 1;
86 
87 static constexpr bool DEFAULT_FORCEDNSSEED{false};
88 static constexpr bool DEFAULT_DNSSEED{true};
89 static constexpr bool DEFAULT_FIXEDSEEDS{true};
90 static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
91 static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
92 
93 typedef int64_t NodeId;
94 
96 {
97  std::string strAddedNode;
99  bool fConnected;
100  bool fInbound;
101 };
102 
103 class CNodeStats;
104 class CClientUIInterface;
105 
107  CSerializedNetMsg() = default;
110  // No implicit copying, only moves.
111  CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
113 
115  {
116  CSerializedNetMsg copy;
117  copy.data = data;
118  copy.m_type = m_type;
119  return copy;
120  }
121 
122  std::vector<unsigned char> data;
123  std::string m_type;
124 };
125 
132 void Discover();
133 
134 uint16_t GetListenPort();
135 
136 enum
137 {
138  LOCAL_NONE, // unknown
139  LOCAL_IF, // address a local interface listens on
140  LOCAL_BIND, // address explicit bound to
141  LOCAL_MAPPED, // address reported by UPnP or NAT-PMP
142  LOCAL_MANUAL, // address explicitly specified (-externalip=)
143 
144  LOCAL_MAX
145 };
146 
147 bool IsPeerAddrLocalGood(CNode *pnode);
149 std::optional<CService> GetLocalAddrForPeer(CNode& node);
150 
155 void SetReachable(enum Network net, bool reachable);
157 bool IsReachable(enum Network net);
159 bool IsReachable(const CNetAddr& addr);
160 
161 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
162 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
163 void RemoveLocal(const CService& addr);
164 bool SeenLocal(const CService& addr);
165 bool IsLocal(const CService& addr);
166 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr);
167 CService GetLocalAddress(const CNetAddr& addrPeer);
168 CService MaybeFlipIPv6toCJDNS(const CService& service);
169 
170 
171 extern bool fDiscover;
172 extern bool fListen;
173 
175 extern std::string strSubVersion;
176 
178  int nScore;
179  uint16_t nPort;
180 };
181 
183 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(g_maplocalhost_mutex);
184 
185 extern const std::string NET_MESSAGE_TYPE_OTHER;
186 using mapMsgTypeSize = std::map</* message type */ std::string, /* total bytes */ uint64_t>;
187 
189 {
190 public:
192  std::chrono::seconds m_last_send;
193  std::chrono::seconds m_last_recv;
194  std::chrono::seconds m_last_tx_time;
195  std::chrono::seconds m_last_block_time;
196  std::chrono::seconds m_connected;
197  int64_t nTimeOffset;
198  std::string m_addr_name;
199  int nVersion;
200  std::string cleanSubVer;
201  bool fInbound;
205  uint64_t nSendBytes;
207  uint64_t nRecvBytes;
210  std::chrono::microseconds m_last_ping_time;
211  std::chrono::microseconds m_min_ping_time;
212  // Our address, as reported by the peer
213  std::string addrLocal;
214  // Address of this peer
216  // Bind address of our side of the connection
218  // Network the peer connected through
220  uint32_t m_mapped_as;
222 };
223 
224 
229 class CNetMessage {
230 public:
232  std::chrono::microseconds m_time{0};
233  uint32_t m_message_size{0};
234  uint32_t m_raw_message_size{0};
235  std::string m_type;
236 
237  CNetMessage(CDataStream&& recv_in) : m_recv(std::move(recv_in)) {}
238 
239  void SetVersion(int nVersionIn)
240  {
241  m_recv.SetVersion(nVersionIn);
242  }
243 };
244 
250 public:
251  // returns true if the current deserialization is complete
252  virtual bool Complete() const = 0;
253  // set the serialization context version
254  virtual void SetVersion(int version) = 0;
256  virtual int Read(Span<const uint8_t>& msg_bytes) = 0;
257  // decomposes a message from the context
258  virtual CNetMessage GetMessage(std::chrono::microseconds time, bool& reject_message) = 0;
260 };
261 
263 {
264 private:
266  const NodeId m_node_id; // Only for logging
267  mutable CHash256 hasher;
269  bool in_data; // parsing header (false) or data (true)
270  CDataStream hdrbuf; // partially received header
271  CMessageHeader hdr; // complete header
272  CDataStream vRecv; // received message data
273  unsigned int nHdrPos;
274  unsigned int nDataPos;
275 
276  const uint256& GetMessageHash() const;
277  int readHeader(Span<const uint8_t> msg_bytes);
278  int readData(Span<const uint8_t> msg_bytes);
279 
280  void Reset() {
281  vRecv.clear();
282  hdrbuf.clear();
283  hdrbuf.resize(24);
284  in_data = false;
285  nHdrPos = 0;
286  nDataPos = 0;
287  data_hash.SetNull();
288  hasher.Reset();
289  }
290 
291 public:
292  V1TransportDeserializer(const CChainParams& chain_params, const NodeId node_id, int nTypeIn, int nVersionIn)
293  : m_chain_params(chain_params),
294  m_node_id(node_id),
295  hdrbuf(nTypeIn, nVersionIn),
296  vRecv(nTypeIn, nVersionIn)
297  {
298  Reset();
299  }
300 
301  bool Complete() const override
302  {
303  if (!in_data)
304  return false;
305  return (hdr.nMessageSize == nDataPos);
306  }
307  void SetVersion(int nVersionIn) override
308  {
309  hdrbuf.SetVersion(nVersionIn);
310  vRecv.SetVersion(nVersionIn);
311  }
312  int Read(Span<const uint8_t>& msg_bytes) override
313  {
314  int ret = in_data ? readData(msg_bytes) : readHeader(msg_bytes);
315  if (ret < 0) {
316  Reset();
317  } else {
318  msg_bytes = msg_bytes.subspan(ret);
319  }
320  return ret;
321  }
322  CNetMessage GetMessage(std::chrono::microseconds time, bool& reject_message) override;
323 };
324 
328 public:
329  // prepare message for transport (header construction, error-correction computation, payload encryption, etc.)
330  virtual void prepareForTransport(CSerializedNetMsg& msg, std::vector<unsigned char>& header) const = 0;
331  virtual ~TransportSerializer() {}
332 };
333 
335 public:
336  void prepareForTransport(CSerializedNetMsg& msg, std::vector<unsigned char>& header) const override;
337 };
338 
340 {
342  std::unique_ptr<i2p::sam::Session> i2p_sam_session = nullptr;
343  bool prefer_evict = false;
344 };
345 
347 class CNode
348 {
349  friend class CConnman;
350  friend struct ConnmanTestMsg;
351 
352 public:
353  const std::unique_ptr<TransportDeserializer> m_deserializer; // Used only by SocketHandler thread
354  const std::unique_ptr<const TransportSerializer> m_serializer;
355 
357 
366  std::shared_ptr<Sock> m_sock GUARDED_BY(m_sock_mutex);
367 
369  size_t nSendSize GUARDED_BY(cs_vSend){0};
371  size_t nSendOffset GUARDED_BY(cs_vSend){0};
372  uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
373  std::deque<std::vector<unsigned char>> vSendMsg GUARDED_BY(cs_vSend);
377 
379  std::list<CNetMessage> vProcessMsg GUARDED_BY(cs_vProcessMsg);
380  size_t nProcessQueueSize GUARDED_BY(cs_vProcessMsg){0};
381 
382  uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
383 
384  std::atomic<std::chrono::seconds> m_last_send{0s};
385  std::atomic<std::chrono::seconds> m_last_recv{0s};
387  const std::chrono::seconds m_connected;
388  std::atomic<int64_t> nTimeOffset{0};
389  // Address of this peer
390  const CAddress addr;
391  // Bind address of our side of the connection
393  const std::string m_addr_name;
395  const bool m_inbound_onion;
396  std::atomic<int> nVersion{0};
402  std::string cleanSubVer GUARDED_BY(m_subver_mutex){};
403  const bool m_prefer_evict{false}; // This peer is preferred for eviction.
404  bool HasPermission(NetPermissionFlags permission) const {
405  return NetPermissions::HasFlag(m_permission_flags, permission);
406  }
408  std::atomic_bool fSuccessfullyConnected{false};
409  // Setting fDisconnect to true will cause the node to be disconnected the
410  // next time DisconnectNodes() runs
411  std::atomic_bool fDisconnect{false};
413  std::atomic<int> nRefCount{0};
414 
415  const uint64_t nKeyedNetGroup;
416  std::atomic_bool fPauseRecv{false};
417  std::atomic_bool fPauseSend{false};
418 
420  switch (m_conn_type) {
423  return true;
428  return false;
429  } // no default case, so the compiler can warn about missing cases
430 
431  assert(false);
432  }
433 
434  bool IsFullOutboundConn() const {
436  }
437 
438  bool IsManualConn() const {
440  }
441 
442  bool IsBlockOnlyConn() const {
444  }
445 
446  bool IsFeelerConn() const {
448  }
449 
450  bool IsAddrFetchConn() const {
452  }
453 
454  bool IsInboundConn() const {
456  }
457 
458  bool ExpectServicesFromConn() const {
459  switch (m_conn_type) {
463  return false;
467  return true;
468  } // no default case, so the compiler can warn about missing cases
469 
470  assert(false);
471  }
472 
484 
485  // We selected peer as (compact blocks) high-bandwidth peer (BIP152)
486  std::atomic<bool> m_bip152_highbandwidth_to{false};
487  // Peer selected us as (compact blocks) high-bandwidth peer (BIP152)
488  std::atomic<bool> m_bip152_highbandwidth_from{false};
489 
491  std::atomic_bool m_has_all_wanted_services{false};
492 
495  std::atomic_bool m_relays_txs{false};
496 
499  std::atomic_bool m_bloom_filter_loaded{false};
500 
506  std::atomic<std::chrono::seconds> m_last_block_time{0s};
507 
512  std::atomic<std::chrono::seconds> m_last_tx_time{0s};
513 
515  std::atomic<std::chrono::microseconds> m_last_ping_time{0us};
516 
519  std::atomic<std::chrono::microseconds> m_min_ping_time{std::chrono::microseconds::max()};
520 
521  CNode(NodeId id,
522  std::shared_ptr<Sock> sock,
523  const CAddress& addrIn,
524  uint64_t nKeyedNetGroupIn,
525  uint64_t nLocalHostNonceIn,
526  const CAddress& addrBindIn,
527  const std::string& addrNameIn,
528  ConnectionType conn_type_in,
529  bool inbound_onion,
530  CNodeOptions&& node_opts = {});
531  CNode(const CNode&) = delete;
532  CNode& operator=(const CNode&) = delete;
533 
534  NodeId GetId() const {
535  return id;
536  }
537 
538  uint64_t GetLocalNonce() const {
539  return nLocalHostNonce;
540  }
541 
542  int GetRefCount() const
543  {
544  assert(nRefCount >= 0);
545  return nRefCount;
546  }
547 
557  bool ReceiveMsgBytes(Span<const uint8_t> msg_bytes, bool& complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv);
558 
559  void SetCommonVersion(int greatest_common_version)
560  {
562  m_greatest_common_version = greatest_common_version;
563  }
564  int GetCommonVersion() const
565  {
567  }
568 
572 
574  {
575  nRefCount++;
576  return this;
577  }
578 
579  void Release()
580  {
581  nRefCount--;
582  }
583 
585 
587 
589 
591  void PongReceived(std::chrono::microseconds ping_time) {
592  m_last_ping_time = ping_time;
593  m_min_ping_time = std::min(m_min_ping_time.load(), ping_time);
594  }
595 
596 private:
597  const NodeId id;
598  const uint64_t nLocalHostNonce;
601 
602  std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
603 
604  // Our address, as reported by the peer
607 
608  mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend);
609  mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv);
610 
621  std::unique_ptr<i2p::sam::Session> m_i2p_sam_session GUARDED_BY(m_sock_mutex);
622 };
623 
628 {
629 public:
632 
634  virtual void InitializeNode(CNode& node, ServiceFlags our_services) = 0;
635 
637  virtual void FinalizeNode(const CNode& node) = 0;
638 
646  virtual bool ProcessMessages(CNode* pnode, std::atomic<bool>& interrupt) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) = 0;
647 
655 
656 
657 protected:
662  ~NetEventsInterface() = default;
663 };
664 
665 class CConnman
666 {
667 public:
668 
669  struct Options
670  {
675  int nMaxAddnode = 0;
676  int nMaxFeeler = 0;
679  BanMan* m_banman = nullptr;
680  unsigned int nSendBufferMaxSize = 0;
681  unsigned int nReceiveFloodSize = 0;
682  uint64_t nMaxOutboundLimit = 0;
684  std::vector<std::string> vSeedNodes;
685  std::vector<NetWhitelistPermissions> vWhitelistedRange;
686  std::vector<NetWhitebindPermissions> vWhiteBinds;
687  std::vector<CService> vBinds;
688  std::vector<CService> onion_binds;
693  std::vector<std::string> m_specified_outgoing;
694  std::vector<std::string> m_added_nodes;
696  };
697 
699  {
701 
702  nLocalServices = connOptions.nLocalServices;
703  nMaxConnections = connOptions.nMaxConnections;
704  m_max_outbound_full_relay = std::min(connOptions.m_max_outbound_full_relay, connOptions.nMaxConnections);
705  m_max_outbound_block_relay = connOptions.m_max_outbound_block_relay;
706  m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
707  nMaxAddnode = connOptions.nMaxAddnode;
708  nMaxFeeler = connOptions.nMaxFeeler;
710  m_client_interface = connOptions.uiInterface;
711  m_banman = connOptions.m_banman;
712  m_msgproc = connOptions.m_msgproc;
713  nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
714  nReceiveFloodSize = connOptions.nReceiveFloodSize;
715  m_peer_connect_timeout = std::chrono::seconds{connOptions.m_peer_connect_timeout};
716  {
718  nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
719  }
720  vWhitelistedRange = connOptions.vWhitelistedRange;
721  {
723  m_added_nodes = connOptions.m_added_nodes;
724  }
725  m_onion_binds = connOptions.onion_binds;
726  }
727 
728  CConnman(uint64_t seed0, uint64_t seed1, AddrMan& addrman, const NetGroupManager& netgroupman,
729  bool network_active = true);
730 
731  ~CConnman();
732 
734 
735  void StopThreads();
736  void StopNodes();
737  void Stop()
738  {
739  StopThreads();
740  StopNodes();
741  };
742 
744  bool GetNetworkActive() const { return fNetworkActive; };
746  void SetNetworkActive(bool active);
747  void OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant* grantOutbound, const char* strDest, ConnectionType conn_type);
748  bool CheckIncomingNonce(uint64_t nonce);
749 
750  bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
751 
753 
754  using NodeFn = std::function<void(CNode*)>;
755  void ForEachNode(const NodeFn& func)
756  {
758  for (auto&& node : m_nodes) {
760  func(node);
761  }
762  };
763 
764  void ForEachNode(const NodeFn& func) const
765  {
767  for (auto&& node : m_nodes) {
769  func(node);
770  }
771  };
772 
773  // Addrman functions
781  std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct, std::optional<Network> network) const;
788  std::vector<CAddress> GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct);
789 
790  // This allows temporarily exceeding m_max_outbound_full_relay, with the goal of finding
791  // a peer that is better than all our current peers.
792  void SetTryNewOutboundPeer(bool flag);
793  bool GetTryNewOutboundPeer() const;
794 
796 
797  // Return the number of outbound peers we have in excess of our target (eg,
798  // if we previously called SetTryNewOutboundPeer(true), and have since set
799  // to false, we may have extra peers that we wish to disconnect). This may
800  // return a value less than (num_outbound_connections - num_outbound_slots)
801  // in cases where some outbound connections are not yet fully connected, or
802  // not yet fully disconnected.
803  int GetExtraFullOutboundCount() const;
804  // Count the number of block-relay-only peers we have over our limit.
805  int GetExtraBlockRelayCount() const;
806 
807  bool AddNode(const std::string& node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
809  std::vector<AddedNodeInfo> GetAddedNodeInfo() const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
810 
823  bool AddConnection(const std::string& address, ConnectionType conn_type);
824 
825  size_t GetNodeCount(ConnectionDirection) const;
826  void GetNodeStats(std::vector<CNodeStats>& vstats) const;
827  bool DisconnectNode(const std::string& node);
828  bool DisconnectNode(const CSubNet& subnet);
829  bool DisconnectNode(const CNetAddr& addr);
830  bool DisconnectNode(NodeId id);
831 
839 
841  std::chrono::seconds GetMaxOutboundTimeframe() const;
842 
846  bool OutboundTargetReached(bool historicalBlockServingLimit) const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
847 
851 
853 
854  uint64_t GetTotalBytesRecv() const;
856 
858  CSipHasher GetDeterministicRandomizer(uint64_t id) const;
859 
860  unsigned int GetReceiveFloodSize() const;
861 
863 
865  bool ShouldRunInactivityChecks(const CNode& node, std::chrono::seconds now) const;
866 
867 private:
868  struct ListenSocket {
869  public:
870  std::shared_ptr<Sock> sock;
872  ListenSocket(std::shared_ptr<Sock> sock_, NetPermissionFlags permissions_)
873  : sock{sock_}, m_permissions{permissions_}
874  {
875  }
876 
877  private:
879  };
880 
884 
885  bool BindListenPort(const CService& bindAddr, bilingual_str& strError, NetPermissionFlags permissions);
886  bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions);
887  bool InitBinds(const Options& options);
888 
890  void AddAddrFetch(const std::string& strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex);
895  void AcceptConnection(const ListenSocket& hListenSocket);
896 
905  void CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock,
906  NetPermissionFlags permission_flags,
907  const CAddress& addr_bind,
908  const CAddress& addr);
909 
910  void DisconnectNodes();
913  bool InactivityCheck(const CNode& node) const;
914 
920  Sock::EventsPerSock GenerateWaitSockets(Span<CNode* const> nodes);
921 
926 
932  void SocketHandlerConnected(const std::vector<CNode*>& nodes,
933  const Sock::EventsPerSock& events_per_sock)
935 
940  void SocketHandlerListening(const Sock::EventsPerSock& events_per_sock);
941 
944 
945  uint64_t CalculateKeyedNetGroup(const CAddress& ad) const;
946 
947  CNode* FindNode(const CNetAddr& ip);
948  CNode* FindNode(const CSubNet& subNet);
949  CNode* FindNode(const std::string& addrName);
950  CNode* FindNode(const CService& addr);
951 
956  bool AlreadyConnectedToAddress(const CAddress& addr);
957 
959  CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type);
961 
962  void DeleteNode(CNode* pnode);
963 
965 
966  size_t SocketSendData(CNode& node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend);
967  void DumpAddresses();
968 
969  // Network stats
970  void RecordBytesRecv(uint64_t bytes);
972 
977  std::unordered_set<Network> GetReachableEmptyNetworks() const;
978 
982  std::vector<CAddress> GetCurrentBlockRelayOnlyConns() const;
983 
984  // Whether the node should be passed out in ForEach* callbacks
985  static bool NodeFullyConnected(const CNode* pnode);
986 
987  // Network usage totals
989  std::atomic<uint64_t> nTotalBytesRecv{0};
990  uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex) {0};
991 
992  // outbound limit & stats
993  uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex) {0};
994  std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex) {0};
996 
997  // P2P timeout in seconds
998  std::chrono::seconds m_peer_connect_timeout;
999 
1000  // Whitelisted ranges. Any node connecting from these is automatically
1001  // whitelisted (as well as those connecting to whitelisted binds).
1002  std::vector<NetWhitelistPermissions> vWhitelistedRange;
1003 
1004  unsigned int nSendBufferMaxSize{0};
1005  unsigned int nReceiveFloodSize{0};
1006 
1007  std::vector<ListenSocket> vhListenSocket;
1008  std::atomic<bool> fNetworkActive{true};
1012  std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
1014  std::vector<std::string> m_added_nodes GUARDED_BY(m_added_nodes_mutex);
1016  std::vector<CNode*> m_nodes GUARDED_BY(m_nodes_mutex);
1017  std::list<CNode*> m_nodes_disconnected;
1019  std::atomic<NodeId> nLastNodeId{0};
1020  unsigned int nPrevNodeCount{0};
1021 
1029  std::vector<CAddress> m_addrs_response_cache;
1030  std::chrono::microseconds m_cache_entry_expiration{0};
1031  };
1032 
1047  std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
1048 
1060 
1061  std::unique_ptr<CSemaphore> semOutbound;
1062  std::unique_ptr<CSemaphore> semAddnode;
1064 
1065  // How many full-relay (tx, block, addr) outbound peers we want
1067 
1068  // How many block-relay only outbound peers we want
1069  // We do not relay tx or addr messages with these peers
1071 
1080 
1085  std::vector<CAddress> m_anchors;
1086 
1088  const uint64_t nSeed0, nSeed1;
1089 
1091  bool fMsgProcWake GUARDED_BY(mutexMsgProc);
1092 
1093  std::condition_variable condMsgProc;
1095  std::atomic<bool> flagInterruptMsgProc{false};
1096 
1104 
1110  std::unique_ptr<i2p::sam::Session> m_i2p_sam_session;
1111 
1113  std::thread threadSocketHandler;
1118 
1123 
1128  std::atomic_bool m_start_extra_block_relay_peers{false};
1129 
1134  std::vector<CService> m_onion_binds;
1135 
1141  {
1142  public:
1143  explicit NodesSnapshot(const CConnman& connman, bool shuffle)
1144  {
1145  {
1146  LOCK(connman.m_nodes_mutex);
1147  m_nodes_copy = connman.m_nodes;
1148  for (auto& node : m_nodes_copy) {
1149  node->AddRef();
1150  }
1151  }
1152  if (shuffle) {
1154  }
1155  }
1156 
1158  {
1159  for (auto& node : m_nodes_copy) {
1160  node->Release();
1161  }
1162  }
1163 
1164  const std::vector<CNode*>& Nodes() const
1165  {
1166  return m_nodes_copy;
1167  }
1168 
1169  private:
1170  std::vector<CNode*> m_nodes_copy;
1171  };
1172 
1173  friend struct CConnmanTest;
1174  friend struct ConnmanTestMsg;
1175 };
1176 
1178 void CaptureMessageToFile(const CAddress& addr,
1179  const std::string& msg_type,
1181  bool is_incoming);
1182 
1184 extern std::function<void(const CAddress& addr,
1185  const std::string& msg_type,
1187  bool is_incoming)>
1189 
1190 #endif // BITCOIN_NET_H
int ret
int flags
Definition: bitcoin-tx.cpp:525
#define Assume(val)
Assume is the identity function.
Definition: check.h:85
Stochastic address manager.
Definition: addrman.h:87
Definition: banman.h:59
A CService with information about it as peer.
Definition: protocol.h:361
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:70
Signals for UI communication.
Definition: interface_ui.h:25
RAII helper to atomically create a copy of m_nodes and add a reference to each of the nodes.
Definition: net.h:1141
NodesSnapshot(const CConnman &connman, bool shuffle)
Definition: net.h:1143
const std::vector< CNode * > & Nodes() const
Definition: net.h:1164
std::vector< CNode * > m_nodes_copy
Definition: net.h:1170
Definition: net.h:666
std::unordered_set< Network > GetReachableEmptyNetworks() const
Return reachable networks for which we have no addresses in addrman and therefore may require loading...
Definition: net.cpp:1577
std::condition_variable condMsgProc
Definition: net.h:1093
std::thread threadMessageHandler
Definition: net.h:1116
void ForEachNode(const NodeFn &func)
Definition: net.h:755
nSendBufferMaxSize
Definition: net.h:713
CClientUIInterface * m_client_interface
Definition: net.h:1076
size_t SocketSendData(CNode &node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend)
Definition: net.cpp:814
void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:2006
void ForEachNode(const NodeFn &func) const
Definition: net.h:764
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:2825
bool AddConnection(const std::string &address, ConnectionType conn_type)
Attempts to open a connection.
Definition: net.cpp:1048
m_max_outbound_full_relay
Definition: net.h:704
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type)
Definition: net.cpp:437
void DeleteNode(CNode *pnode)
Definition: net.cpp:2470
bool RemoveAddedNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2549
bool AttemptToEvictConnection()
Try to find a connection to evict when the node is full.
Definition: net.cpp:874
bool GetNetworkActive() const
Definition: net.h:744
bool AlreadyConnectedToAddress(const CAddress &addr)
Determine whether we're already connected to a given address, in order to avoid initiating duplicate ...
Definition: net.cpp:406
int m_max_outbound
Definition: net.h:1074
ServiceFlags nLocalServices
Services this node offers.
Definition: net.h:1059
bool GetTryNewOutboundPeer() const
Definition: net.cpp:1526
void Stop()
Definition: net.h:737
int m_max_outbound_block_relay
Definition: net.h:1070
nMaxAddnode
Definition: net.h:707
m_added_nodes
Definition: net.h:723
std::thread threadI2PAcceptIncoming
Definition: net.h:1117
void SetTryNewOutboundPeer(bool flag)
Definition: net.cpp:1531
std::atomic< bool > flagInterruptMsgProc
Definition: net.h:1095
unsigned int GetReceiveFloodSize() const
Definition: net.cpp:2737
void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:1940
void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:2396
void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:1389
m_onion_binds
Definition: net.h:725
Sock::EventsPerSock GenerateWaitSockets(Span< CNode *const > nodes)
Generate a collection of sockets to check for IO readiness.
Definition: net.cpp:1187
NodeId GetNewNodeId()
Definition: net.cpp:2234
std::vector< CNode * > m_nodes GUARDED_BY(m_nodes_mutex)
uint64_t nMaxOutboundLimit GUARDED_BY(m_total_bytes_sent_mutex)
CThreadInterrupt interruptNet
This is signaled when network activity should cease.
Definition: net.h:1103
std::unique_ptr< CSemaphore > semAddnode
Definition: net.h:1062
std::atomic< NodeId > nLastNodeId
Definition: net.h:1019
bool fMsgProcWake GUARDED_BY(mutexMsgProc)
flag for waking the message processor.
std::vector< std::string > m_added_nodes GUARDED_BY(m_added_nodes_mutex)
int GetExtraBlockRelayCount() const
Definition: net.cpp:1563
void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:1380
BanMan * m_banman
Pointer to this node's banman.
Definition: net.h:1079
bool OutboundTargetReached(bool historicalBlockServingLimit) const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
check if the outbound target is reached if param historicalBlockServingLimit is set true,...
Definition: net.cpp:2689
uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex)
Definition: net.h:993
uint64_t GetMaxOutboundTarget() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:2655
std::thread threadDNSAddressSeed
Definition: net.h:1112
m_max_outbound
Definition: net.h:709
void SocketHandlerConnected(const std::vector< CNode * > &nodes, const Sock::EventsPerSock &events_per_sock) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
Do the read/write for connected sockets that are ready for IO.
Definition: net.cpp:1260
void ThreadI2PAcceptIncoming()
Definition: net.cpp:2046
const uint64_t nSeed1
Definition: net.h:1088
void StartExtraBlockRelayPeers()
Definition: net.cpp:1537
const NetGroupManager & m_netgroupman
Definition: net.h:1011
m_banman
Definition: net.h:711
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
Definition: net.h:1085
std::chrono::seconds GetMaxOutboundTimeframe() const
Definition: net.cpp:2662
unsigned int nPrevNodeCount
Definition: net.h:1020
void NotifyNumConnectionsChanged()
Definition: net.cpp:1134
ServiceFlags GetLocalServices() const
Used to convey which local services we are offering peers during node connection.
Definition: net.cpp:2732
bool DisconnectNode(const std::string &node)
Definition: net.cpp:2589
std::chrono::seconds m_peer_connect_timeout
Definition: net.h:998
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:1122
bool InitBinds(const Options &options)
Definition: net.cpp:2259
void AddAddrFetch(const std::string &strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex)
Definition: net.cpp:122
std::vector< ListenSocket > vhListenSocket
Definition: net.h:1007
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const
Return vector of current BLOCK_RELAY peers.
Definition: net.cpp:1873
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition: net.cpp:2838
Mutex m_total_bytes_sent_mutex
Definition: net.h:988
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:1061
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:1002
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
Definition: net.cpp:2240
std::thread threadOpenConnections
Definition: net.h:1115
size_t GetNodeCount(ConnectionDirection) const
Definition: net.cpp:2561
Mutex m_addr_fetches_mutex
Definition: net.h:1013
bool InactivityCheck(const CNode &node) const
Return true if the peer is inactive and should be disconnected.
Definition: net.cpp:1154
m_peer_connect_timeout
Definition: net.h:715
CNode * FindNode(const CNetAddr &ip)
Definition: net.cpp:362
void GetNodeStats(std::vector< CNodeStats > &vstats) const
Definition: net.cpp:2577
std::vector< AddedNodeInfo > GetAddedNodeInfo() const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:1886
bool Start(CScheduler &scheduler, const Options &options) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
Definition: net.cpp:2281
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition: net.h:1088
void ThreadOpenConnections(std::vector< std::string > connect) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:1590
void SocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
Check connected and listening sockets for IO readiness and process them accordingly.
Definition: net.cpp:1232
int GetExtraFullOutboundCount() const
Definition: net.cpp:1549
std::chrono::seconds GetMaxOutboundTimeLeftInCycle_() const EXCLUSIVE_LOCKS_REQUIRED(m_total_bytes_sent_mutex)
returns the time left in the current max outbound cycle in case of no limit, it will always return 0
Definition: net.cpp:2674
uint64_t GetTotalBytesRecv() const
Definition: net.cpp:2720
RecursiveMutex m_nodes_mutex
Definition: net.h:1018
m_max_outbound_block_relay
Definition: net.h:705
static bool NodeFullyConnected(const CNode *pnode)
Definition: net.cpp:2778
void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex)
Definition: net.cpp:1509
int nMaxConnections
Definition: net.h:1063
std::vector< CAddress > GetAddresses(size_t max_addresses, size_t max_pct, std::optional< Network > network) const
Return all or many randomly selected addresses, optionally by network.
Definition: net.cpp:2483
std::deque< std::string > m_addr_fetches GUARDED_BY(m_addr_fetches_mutex)
m_client_interface
Definition: net.h:710
nReceiveFloodSize
Definition: net.h:714
vWhitelistedRange
Definition: net.h:720
void SetNetworkActive(bool active)
Definition: net.cpp:2205
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *strDest, ConnectionType conn_type)
Definition: net.cpp:1969
std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:2667
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, const CNetAddr &addr) const
Definition: net.cpp:579
AddrMan & addrman
Definition: net.h:1010
uint64_t CalculateKeyedNetGroup(const CAddress &ad) const
Definition: net.cpp:2843
m_msgproc
Definition: net.h:712
Mutex mutexMsgProc
Definition: net.h:1094
bool fAddressesInitialized
Definition: net.h:1009
~CConnman()
Definition: net.cpp:2477
void StopThreads()
Definition: net.cpp:2420
bool AddNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2538
std::thread threadOpenAddedConnections
Definition: net.h:1114
Mutex m_added_nodes_mutex
Definition: net.h:1015
friend struct CConnmanTest
Definition: net.h:1173
void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
Definition: net.cpp:1367
void RecordBytesSent(uint64_t bytes) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:2637
bool CheckIncomingNonce(uint64_t nonce)
Definition: net.cpp:411
int m_max_outbound_full_relay
Definition: net.h:1066
void Init(const Options &connOptions) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
uint64_t GetTotalBytesSent() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:2725
int nMaxAddnode
Definition: net.h:1072
void RecordBytesRecv(uint64_t bytes)
Definition: net.cpp:2632
std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex)
Definition: net.h:994
nMaxFeeler
Definition: net.h:708
bool ShouldRunInactivityChecks(const CNode &node, std::chrono::seconds now) const
Return true if we should disconnect the peer for failing an inactivity check.
Definition: net.cpp:1149
uint64_t GetOutboundTargetBytesLeft() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
response the bytes left in the current max outbound cycle in case of no limit, it will always respons...
Definition: net.cpp:2710
nLocalServices
Definition: net.h:702
void CreateNodeFromAcceptedSocket(std::unique_ptr< Sock > &&sock, NetPermissionFlags permission_flags, const CAddress &addr_bind, const CAddress &addr)
Create a CNode object from a socket that has just been accepted and add the node to the m_nodes membe...
Definition: net.cpp:945
uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex)
Definition: net.h:990
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:2783
void StopNodes()
Definition: net.cpp:2437
bool GetUseAddrmanOutgoing() const
Definition: net.h:745
std::list< CNode * > m_nodes_disconnected
Definition: net.h:1017
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
Definition: net.h:1110
bool m_use_addrman_outgoing
Definition: net.h:1075
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:1047
CConnman(uint64_t seed0, uint64_t seed1, AddrMan &addrman, const NetGroupManager &netgroupman, bool network_active=true)
Definition: net.cpp:2220
std::function< void(CNode *)> NodeFn
Definition: net.h:754
NetEventsInterface * m_msgproc
Definition: net.h:1077
std::atomic< uint64_t > nTotalBytesRecv
Definition: net.h:989
std::atomic< bool > fNetworkActive
Definition: net.h:1008
std::atomic_bool m_start_extra_block_relay_peers
flag for initiating extra block-relay-only peer connections.
Definition: net.h:1128
m_use_addrman_outgoing
Definition: net.h:706
nMaxConnections
Definition: net.h:703
void DisconnectNodes()
Definition: net.cpp:1084
void SocketHandlerListening(const Sock::EventsPerSock &events_per_sock)
Accept incoming connections, one from each read-ready listening socket.
Definition: net.cpp:1354
void DumpAddresses()
Definition: net.cpp:1499
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:1134
int nMaxFeeler
Definition: net.h:1073
std::thread threadSocketHandler
Definition: net.h:1113
nMaxOutboundLimit
Definition: net.h:718
void AcceptConnection(const ListenSocket &hListenSocket)
Definition: net.cpp:917
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
Definition: net.cpp:2085
void SetVersion(int n)
Definition: streams.h:370
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
Definition: hash.h:25
CHash256 & Reset()
Definition: hash.h:43
Message header.
Definition: protocol.h:27
uint32_t nMessageSize
Definition: protocol.h:52
Network address.
Definition: netaddress.h:120
Transport protocol agnostic message container.
Definition: net.h:229
CNetMessage(CDataStream &&recv_in)
Definition: net.h:237
uint32_t m_message_size
size of the payload
Definition: net.h:233
std::chrono::microseconds m_time
time of message receipt
Definition: net.h:232
CDataStream m_recv
received message data
Definition: net.h:231
void SetVersion(int nVersionIn)
Definition: net.h:239
uint32_t m_raw_message_size
used wire size of the message (including header/checksum)
Definition: net.h:234
std::string m_type
Definition: net.h:235
Information about a peer.
Definition: net.h:348
RecursiveMutex cs_vProcessMsg
Definition: net.h:378
const CAddress addrBind
Definition: net.h:392
bool IsFeelerConn() const
Definition: net.h:446
const std::chrono::seconds m_connected
Unix epoch time at peer connection.
Definition: net.h:387
bool ExpectServicesFromConn() const
Definition: net.h:458
std::atomic< int > nVersion
Definition: net.h:396
std::atomic_bool m_has_all_wanted_services
Whether this peer provides all services that we want.
Definition: net.h:491
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Definition: net.h:382
size_t nProcessQueueSize GUARDED_BY(cs_vProcessMsg)
Definition: net.h:380
bool IsInboundConn() const
Definition: net.h:454
std::deque< std::vector< unsigned char > > vSendMsg GUARDED_BY(cs_vSend)
bool HasPermission(NetPermissionFlags permission) const
Definition: net.h:404
std::atomic_bool fPauseRecv
Definition: net.h:416
bool IsOutboundOrBlockRelayConn() const
Definition: net.h:419
NodeId GetId() const
Definition: net.h:534
bool IsManualConn() const
Definition: net.h:438
std::atomic< int64_t > nTimeOffset
Definition: net.h:388
const std::string m_addr_name
Definition: net.h:393
void CopyStats(CNodeStats &stats) EXCLUSIVE_LOCKS_REQUIRED(!m_subver_mutex
Definition: net.cpp:609
std::string ConnectionTypeAsString() const
Definition: net.h:588
void SetCommonVersion(int greatest_common_version)
Definition: net.h:559
std::atomic< bool > m_bip152_highbandwidth_to
Definition: net.h:486
std::list< CNetMessage > vRecvMsg
Definition: net.h:602
std::atomic_bool m_relays_txs
Whether we should relay transactions to this peer.
Definition: net.h:495
std::atomic< bool > m_bip152_highbandwidth_from
Definition: net.h:488
void PongReceived(std::chrono::microseconds ping_time)
A ping-pong round trip has completed successfully.
Definition: net.h:591
std::atomic_bool fSuccessfullyConnected
fSuccessfullyConnected is set to true on receiving VERACK from the peer.
Definition: net.h:408
const bool m_prefer_evict
Definition: net.h:403
bool IsAddrFetchConn() const
Definition: net.h:450
uint64_t GetLocalNonce() const
Definition: net.h:538
const CAddress addr
Definition: net.h:390
void SetAddrLocal(const CService &addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
May not be called more than once.
Definition: net.cpp:592
CSemaphoreGrant grantOutbound
Definition: net.h:412
mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend)
const uint64_t nKeyedNetGroup
Definition: net.h:415
std::atomic< int > nRefCount
Definition: net.h:413
std::atomic< int > m_greatest_common_version
Definition: net.h:600
bool IsBlockOnlyConn() const
Definition: net.h:442
int GetCommonVersion() const
Definition: net.h:564
mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv)
bool IsFullOutboundConn() const
Definition: net.h:434
std::shared_ptr< Sock > m_sock GUARDED_BY(m_sock_mutex)
Socket used for communication with the node.
Mutex m_subver_mutex
Definition: net.h:397
const std::unique_ptr< const TransportSerializer > m_serializer
Definition: net.h:354
Mutex cs_vSend
Definition: net.h:374
std::atomic_bool fPauseSend
Definition: net.h:417
int GetRefCount() const
Definition: net.h:542
std::list< CNetMessage > vProcessMsg GUARDED_BY(cs_vProcessMsg)
size_t nSendOffset GUARDED_BY(cs_vSend)
Offset inside the first vSendMsg already sent.
Definition: net.h:371
std::atomic_bool m_bloom_filter_loaded
Whether this peer has loaded a bloom filter.
Definition: net.h:499
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session GUARDED_BY(m_sock_mutex)
If an I2P session is created per connection (for outbound transient I2P connections) then it is store...
CService addrLocal GUARDED_BY(m_addr_local_mutex)
const ConnectionType m_conn_type
Definition: net.h:599
Network ConnectedThroughNetwork() const
Get network the peer connected through.
Definition: net.cpp:602
bool ReceiveMsgBytes(Span< const uint8_t > msg_bytes, bool &complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv)
Receive bytes from the buffer and deserialize them into messages.
Definition: net.cpp:653
const uint64_t nLocalHostNonce
Definition: net.h:598
std::atomic< std::chrono::microseconds > m_last_ping_time
Last measured round-trip time.
Definition: net.h:515
size_t nSendSize GUARDED_BY(cs_vSend)
Total size of all vSendMsg entries.
Definition: net.h:369
const NetPermissionFlags m_permission_flags
Definition: net.h:356
Mutex m_addr_local_mutex
Definition: net.h:606
CNode(const CNode &)=delete
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e. connected via our Tor onion service.
Definition: net.h:395
std::atomic< std::chrono::microseconds > m_min_ping_time
Lowest measured round-trip time.
Definition: net.h:519
const NodeId id
Definition: net.h:597
Mutex cs_vRecv
Definition: net.h:376
std::atomic< std::chrono::seconds > m_last_block_time
UNIX epoch time of the last block received from this peer that we had not yet seen (e....
Definition: net.h:506
const std::unique_ptr< TransportDeserializer > m_deserializer
Definition: net.h:353
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Definition: net.h:372
Mutex m_sock_mutex
Definition: net.h:375
std::atomic_bool fDisconnect
Definition: net.h:411
std::atomic< std::chrono::seconds > m_last_recv
Definition: net.h:385
std::atomic< std::chrono::seconds > m_last_tx_time
UNIX epoch time of the last transaction received from this peer that we had not yet seen (e....
Definition: net.h:512
CService GetAddrLocal() const EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
Definition: net.cpp:585
CNode(NodeId id, std::shared_ptr< Sock > sock, const CAddress &addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const CAddress &addrBindIn, const std::string &addrNameIn, ConnectionType conn_type_in, bool inbound_onion, CNodeOptions &&node_opts={})
Definition: net.cpp:2739
void CloseSocketDisconnect() EXCLUSIVE_LOCKS_REQUIRED(!m_sock_mutex)
Definition: net.cpp:568
std::atomic< std::chrono::seconds > m_last_send
Definition: net.h:384
void Release()
Definition: net.h:579
CNode & operator=(const CNode &)=delete
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:402
CNode * AddRef()
Definition: net.h:573
std::string addrLocal
Definition: net.h:213
CAddress addrBind
Definition: net.h:217
uint64_t nRecvBytes
Definition: net.h:207
std::chrono::microseconds m_last_ping_time
Definition: net.h:210
uint32_t m_mapped_as
Definition: net.h:220
mapMsgTypeSize mapRecvBytesPerMsgType
Definition: net.h:208
bool fInbound
Definition: net.h:201
uint64_t nSendBytes
Definition: net.h:205
std::chrono::seconds m_last_recv
Definition: net.h:193
ConnectionType m_conn_type
Definition: net.h:221
std::chrono::seconds m_last_send
Definition: net.h:192
std::chrono::seconds m_last_tx_time
Definition: net.h:194
CAddress addr
Definition: net.h:215
mapMsgTypeSize mapSendBytesPerMsgType
Definition: net.h:206
std::chrono::microseconds m_min_ping_time
Definition: net.h:211
int64_t nTimeOffset
Definition: net.h:197
std::chrono::seconds m_connected
Definition: net.h:196
bool m_bip152_highbandwidth_from
Definition: net.h:203
bool m_bip152_highbandwidth_to
Definition: net.h:202
std::string m_addr_name
Definition: net.h:198
int nVersion
Definition: net.h:199
std::chrono::seconds m_last_block_time
Definition: net.h:195
Network m_network
Definition: net.h:219
NodeId nodeid
Definition: net.h:191
std::string cleanSubVer
Definition: net.h:200
int m_starting_height
Definition: net.h:204
NetPermissionFlags m_permission_flags
Definition: net.h:209
Simple class for background tasks that should be run periodically or once "after a while".
Definition: scheduler.h:39
RAII-style semaphore lock.
Definition: sync.h:342
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:523
SipHash-2-4.
Definition: siphash.h:14
void resize(size_type n, value_type c=value_type{})
Definition: streams.h:222
void clear()
Definition: streams.h:226
Fast randomness source.
Definition: random.h:143
Different type to mark Mutex at global scope.
Definition: sync.h:141
Interface for message handling.
Definition: net.h:628
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition: net.h:631
virtual bool SendMessages(CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Send queued protocol messages to a given node.
virtual void FinalizeNode(const CNode &node)=0
Handle removal of a peer (clear state)
virtual bool ProcessMessages(CNode *pnode, std::atomic< bool > &interrupt) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Process protocol messages received from a given node.
~NetEventsInterface()=default
Protected destructor so that instances can only be deleted by derived classes.
virtual void InitializeNode(CNode &node, ServiceFlags our_services)=0
Initialize a peer (setup state, queue any initial messages)
Netgroup manager.
Definition: netgroup.h:16
static void AddFlag(NetPermissionFlags &flags, NetPermissionFlags f)
static bool HasFlag(NetPermissionFlags flags, NetPermissionFlags f)
RAII helper class that manages a socket.
Definition: sock.h:28
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:97
CONSTEXPR_IF_NOT_DEBUG Span< C > subspan(std::size_t offset) const noexcept
Definition: span.h:194
The TransportDeserializer takes care of holding and deserializing the network receive buffer.
Definition: net.h:249
virtual ~TransportDeserializer()
Definition: net.h:259
virtual bool Complete() const =0
virtual CNetMessage GetMessage(std::chrono::microseconds time, bool &reject_message)=0
virtual int Read(Span< const uint8_t > &msg_bytes)=0
read and deserialize data, advances msg_bytes data pointer
virtual void SetVersion(int version)=0
The TransportSerializer prepares messages for the network transport.
Definition: net.h:327
virtual void prepareForTransport(CSerializedNetMsg &msg, std::vector< unsigned char > &header) const =0
virtual ~TransportSerializer()
Definition: net.h:331
const CChainParams & m_chain_params
Definition: net.h:265
CDataStream vRecv
Definition: net.h:272
CMessageHeader hdr
Definition: net.h:271
CNetMessage GetMessage(std::chrono::microseconds time, bool &reject_message) override
Definition: net.cpp:763
const uint256 & GetMessageHash() const
Definition: net.cpp:755
const NodeId m_node_id
Definition: net.h:266
int Read(Span< const uint8_t > &msg_bytes) override
read and deserialize data, advances msg_bytes data pointer
Definition: net.h:312
V1TransportDeserializer(const CChainParams &chain_params, const NodeId node_id, int nTypeIn, int nVersionIn)
Definition: net.h:292
void SetVersion(int nVersionIn) override
Definition: net.h:307
int readData(Span< const uint8_t > msg_bytes)
Definition: net.cpp:738
int readHeader(Span< const uint8_t > msg_bytes)
Definition: net.cpp:698
unsigned int nHdrPos
Definition: net.h:273
bool Complete() const override
Definition: net.h:301
CHash256 hasher
Definition: net.h:267
CDataStream hdrbuf
Definition: net.h:270
uint256 data_hash
Definition: net.h:268
unsigned int nDataPos
Definition: net.h:274
void prepareForTransport(CSerializedNetMsg &msg, std::vector< unsigned char > &header) const override
Definition: net.cpp:800
void SetNull()
Definition: uint256.h:42
256-bit opaque blob.
Definition: uint256.h:119
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
ConnectionType
Different types of connections to a peer.
@ BLOCK_RELAY
We use block-relay-only connections to help prevent against partition attacks.
@ MANUAL
We open manual connections to addresses that users explicitly requested via the addnode RPC or the -a...
@ OUTBOUND_FULL_RELAY
These are the default connections that we use to connect with the network.
@ FEELER
Feeler connections are short-lived connections made to check that a node is alive.
@ INBOUND
Inbound connections are those initiated by a peer.
@ ADDR_FETCH
AddrFetch connections are short lived connections used to solicit addresses from peers.
static CService ip(uint32_t i)
unsigned int nonce
Definition: miner_tests.cpp:69
Definition: init.h:25
bool IsPeerAddrLocalGood(CNode *pnode)
Definition: net.cpp:226
uint16_t GetListenPort()
Definition: net.cpp:128
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:77
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:356
CService GetLocalAddress(const CNetAddr &addrPeer)
Definition: net.cpp:209
void RemoveLocal(const CService &addr)
Definition: net.cpp:318
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:65
static constexpr std::chrono::minutes TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:57
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:69
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
Definition: net.cpp:285
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
Definition: net.cpp:233
bool fDiscover
Definition: net.cpp:115
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:91
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
Definition: net.h:85
static constexpr bool DEFAULT_FIXEDSEEDS
Definition: net.h:89
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:81
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
Definition: net.h:54
static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH
Maximum length of incoming protocol messages (no message over 4 MB is currently acceptable).
Definition: net.h:63
bool fListen
Definition: net.cpp:116
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
Definition: net.h:52
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(g_maplocalhost_mutex)
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
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:90
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:120
static const std::string DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:79
const std::string NET_MESSAGE_TYPE_OTHER
Definition: net.cpp:107
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:325
std::map< std::string, uint64_t > mapMsgTypeSize
Definition: net.h:186
static constexpr bool DEFAULT_FORCEDNSSEED
Definition: net.h:87
CService MaybeFlipIPv6toCJDNS(const CService &service)
If an IPv6 address belongs to the address range used by the CJDNS network and the CJDNS network is re...
Definition: net.cpp:275
static constexpr bool DEFAULT_DNSSEED
Definition: net.h:88
int64_t NodeId
Definition: net.h:93
void CaptureMessageToFile(const CAddress &addr, const std::string &msg_type, Span< const unsigned char > data, bool is_incoming)
Dump binary message to file, with timestamp.
Definition: net.cpp:2850
GlobalMutex g_maplocalhost_mutex
Definition: net.cpp:117
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition: net.h:73
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:75
bool GetLocal(CService &addr, const CNetAddr *paddrPeer=nullptr)
Definition: net.cpp:159
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
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
Definition: net.h:67
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:2885
@ LOCAL_NONE
Definition: net.h:138
@ LOCAL_MAPPED
Definition: net.h:141
@ LOCAL_MANUAL
Definition: net.h:142
@ LOCAL_MAX
Definition: net.h:144
@ LOCAL_BIND
Definition: net.h:140
@ LOCAL_IF
Definition: net.h:139
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:71
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:2154
bool IsReachable(enum Network net)
Definition: net.cpp:333
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:345
NetPermissionFlags
Network
A network type.
Definition: netaddress.h:44
ConnectionDirection
Definition: netbase.h:32
ServiceFlags
nServices flags
Definition: protocol.h:273
@ NODE_NONE
Definition: protocol.h:276
void Shuffle(I first, I last, R &&rng)
More efficient than using std::shuffle on a FastRandomContext.
Definition: random.h:271
bool fInbound
Definition: net.h:100
CService resolvedAddress
Definition: net.h:98
bool fConnected
Definition: net.h:99
std::string strAddedNode
Definition: net.h:97
Cache responses to addr requests to minimize privacy leak.
Definition: net.h:1028
std::chrono::microseconds m_cache_entry_expiration
Definition: net.h:1030
std::vector< CAddress > m_addrs_response_cache
Definition: net.h:1029
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition: net.h:871
ListenSocket(std::shared_ptr< Sock > sock_, NetPermissionFlags permissions_)
Definition: net.h:872
NetPermissionFlags m_permissions
Definition: net.h:878
std::shared_ptr< Sock > sock
Definition: net.h:870
int m_max_outbound_block_relay
Definition: net.h:674
unsigned int nReceiveFloodSize
Definition: net.h:681
int m_max_outbound_full_relay
Definition: net.h:673
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:686
uint64_t nMaxOutboundLimit
Definition: net.h:682
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:685
CClientUIInterface * uiInterface
Definition: net.h:677
std::vector< CService > onion_binds
Definition: net.h:688
int nMaxFeeler
Definition: net.h:676
std::vector< std::string > m_specified_outgoing
Definition: net.h:693
NetEventsInterface * m_msgproc
Definition: net.h:678
int nMaxConnections
Definition: net.h:672
ServiceFlags nLocalServices
Definition: net.h:671
std::vector< std::string > m_added_nodes
Definition: net.h:694
int64_t m_peer_connect_timeout
Definition: net.h:683
std::vector< CService > vBinds
Definition: net.h:687
unsigned int nSendBufferMaxSize
Definition: net.h:680
bool m_i2p_accept_incoming
Definition: net.h:695
std::vector< std::string > vSeedNodes
Definition: net.h:684
BanMan * m_banman
Definition: net.h:679
bool m_use_addrman_outgoing
Definition: net.h:692
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
Definition: net.h:691
int nMaxAddnode
Definition: net.h:675
NetPermissionFlags permission_flags
Definition: net.h:341
std::unique_ptr< i2p::sam::Session > i2p_sam_session
Definition: net.h:342
bool prefer_evict
Definition: net.h:343
CSerializedNetMsg(const CSerializedNetMsg &msg)=delete
CSerializedNetMsg Copy() const
Definition: net.h:114
std::string m_type
Definition: net.h:123
CSerializedNetMsg & operator=(const CSerializedNetMsg &)=delete
CSerializedNetMsg()=default
CSerializedNetMsg(CSerializedNetMsg &&)=default
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
std::vector< unsigned char > data
Definition: net.h:122
uint16_t nPort
Definition: net.h:179
int nScore
Definition: net.h:178
Bilingual messages:
Definition: translation.h:18
#define AssertLockNotHeld(cs)
Definition: sync.h:148
#define LOCK(cs)
Definition: sync.h:258
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
assert(!tx.IsCoinBase())
static const int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
Definition: version.h:15