Bitcoin Core  22.0.0
P2P Digital Currency
net.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 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 <addrdb.h>
10 #include <addrman.h>
11 #include <amount.h>
12 #include <bloom.h>
13 #include <chainparams.h>
14 #include <compat.h>
15 #include <crypto/siphash.h>
16 #include <hash.h>
17 #include <i2p.h>
18 #include <net_permissions.h>
19 #include <netaddress.h>
20 #include <netbase.h>
21 #include <policy/feerate.h>
22 #include <protocol.h>
23 #include <random.h>
24 #include <span.h>
25 #include <streams.h>
26 #include <sync.h>
27 #include <threadinterrupt.h>
28 #include <uint256.h>
29 #include <util/check.h>
30 
31 #include <atomic>
32 #include <condition_variable>
33 #include <cstdint>
34 #include <deque>
35 #include <map>
36 #include <memory>
37 #include <optional>
38 #include <thread>
39 #include <vector>
40 
41 class CScheduler;
42 class CNode;
43 class BanMan;
44 struct bilingual_str;
45 
47 static const bool DEFAULT_WHITELISTRELAY = true;
49 static const bool DEFAULT_WHITELISTFORCERELAY = false;
50 
52 static const int TIMEOUT_INTERVAL = 20 * 60;
54 static constexpr auto FEELER_INTERVAL = 2min;
56 static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL = 5min;
58 static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
60 static const unsigned int MAX_SUBVERSION_LENGTH = 256;
64 static const int MAX_ADDNODE_CONNECTIONS = 8;
66 static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS = 2;
68 static const int MAX_FEELER_CONNECTIONS = 1;
70 static const bool DEFAULT_LISTEN = true;
72 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
74 static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET = 0;
76 static const bool DEFAULT_BLOCKSONLY = false;
78 static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
80 static const int NUM_FDS_MESSAGE_CAPTURE = 1;
81 
82 static const bool DEFAULT_FORCEDNSSEED = false;
83 static const bool DEFAULT_DNSSEED = true;
84 static const bool DEFAULT_FIXEDSEEDS = true;
85 static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
86 static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
87 
88 typedef int64_t NodeId;
89 
91 {
92  std::string strAddedNode;
94  bool fConnected;
95  bool fInbound;
96 };
97 
98 class CNodeStats;
99 class CClientUIInterface;
100 
102 {
103  CSerializedNetMsg() = default;
106  // No copying, only moves.
107  CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
109 
110  std::vector<unsigned char> data;
111  std::string m_type;
112 };
113 
121 enum class ConnectionType {
127  INBOUND,
128 
136 
137 
144  MANUAL,
145 
161  FEELER,
162 
172  BLOCK_RELAY,
173 
180  ADDR_FETCH,
181 };
182 
184 std::string ConnectionTypeAsString(ConnectionType conn_type);
185 void Discover();
186 uint16_t GetListenPort();
187 
188 enum
189 {
190  LOCAL_NONE, // unknown
191  LOCAL_IF, // address a local interface listens on
192  LOCAL_BIND, // address explicit bound to
193  LOCAL_MAPPED, // address reported by UPnP or NAT-PMP
194  LOCAL_MANUAL, // address explicitly specified (-externalip=)
195 
197 };
198 
199 bool IsPeerAddrLocalGood(CNode *pnode);
201 std::optional<CAddress> GetLocalAddrForPeer(CNode *pnode);
202 
207 void SetReachable(enum Network net, bool reachable);
209 bool IsReachable(enum Network net);
211 bool IsReachable(const CNetAddr& addr);
212 
213 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
214 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
215 void RemoveLocal(const CService& addr);
216 bool SeenLocal(const CService& addr);
217 bool IsLocal(const CService& addr);
218 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr);
219 CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices);
220 
221 
222 extern bool fDiscover;
223 extern bool fListen;
224 
226 extern std::string strSubVersion;
227 
229  int nScore;
230  uint16_t nPort;
231 };
232 
234 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(cs_mapLocalHost);
235 
236 extern const std::string NET_MESSAGE_COMMAND_OTHER;
237 typedef std::map<std::string, uint64_t> mapMsgCmdSize; //command, total bytes
238 
240 {
241 public:
245  int64_t nLastSend;
246  int64_t nLastRecv;
247  int64_t nLastTXTime;
248  int64_t nLastBlockTime;
249  int64_t nTimeConnected;
250  int64_t nTimeOffset;
251  std::string addrName;
252  int nVersion;
253  std::string cleanSubVer;
254  bool fInbound;
258  uint64_t nSendBytes;
260  uint64_t nRecvBytes;
263  std::chrono::microseconds m_last_ping_time;
264  std::chrono::microseconds m_min_ping_time;
266  // Our address, as reported by the peer
267  std::string addrLocal;
268  // Address of this peer
270  // Bind address of our side of the connection
272  // Network the peer connected through
274  uint32_t m_mapped_as;
276 };
277 
278 
283 class CNetMessage {
284 public:
286  std::chrono::microseconds m_time{0};
287  uint32_t m_message_size{0};
288  uint32_t m_raw_message_size{0};
289  std::string m_command;
290 
291  CNetMessage(CDataStream&& recv_in) : m_recv(std::move(recv_in)) {}
292 
293  void SetVersion(int nVersionIn)
294  {
295  m_recv.SetVersion(nVersionIn);
296  }
297 };
298 
304 public:
305  // returns true if the current deserialization is complete
306  virtual bool Complete() const = 0;
307  // set the serialization context version
308  virtual void SetVersion(int version) = 0;
310  virtual int Read(Span<const uint8_t>& msg_bytes) = 0;
311  // decomposes a message from the context
312  virtual std::optional<CNetMessage> GetMessage(std::chrono::microseconds time, uint32_t& out_err) = 0;
314 };
315 
317 {
318 private:
320  const NodeId m_node_id; // Only for logging
321  mutable CHash256 hasher;
323  bool in_data; // parsing header (false) or data (true)
324  CDataStream hdrbuf; // partially received header
325  CMessageHeader hdr; // complete header
326  CDataStream vRecv; // received message data
327  unsigned int nHdrPos;
328  unsigned int nDataPos;
329 
330  const uint256& GetMessageHash() const;
331  int readHeader(Span<const uint8_t> msg_bytes);
332  int readData(Span<const uint8_t> msg_bytes);
333 
334  void Reset() {
335  vRecv.clear();
336  hdrbuf.clear();
337  hdrbuf.resize(24);
338  in_data = false;
339  nHdrPos = 0;
340  nDataPos = 0;
341  data_hash.SetNull();
342  hasher.Reset();
343  }
344 
345 public:
346  V1TransportDeserializer(const CChainParams& chain_params, const NodeId node_id, int nTypeIn, int nVersionIn)
347  : m_chain_params(chain_params),
348  m_node_id(node_id),
349  hdrbuf(nTypeIn, nVersionIn),
350  vRecv(nTypeIn, nVersionIn)
351  {
352  Reset();
353  }
354 
355  bool Complete() const override
356  {
357  if (!in_data)
358  return false;
359  return (hdr.nMessageSize == nDataPos);
360  }
361  void SetVersion(int nVersionIn) override
362  {
363  hdrbuf.SetVersion(nVersionIn);
364  vRecv.SetVersion(nVersionIn);
365  }
366  int Read(Span<const uint8_t>& msg_bytes) override
367  {
368  int ret = in_data ? readData(msg_bytes) : readHeader(msg_bytes);
369  if (ret < 0) {
370  Reset();
371  } else {
372  msg_bytes = msg_bytes.subspan(ret);
373  }
374  return ret;
375  }
376  std::optional<CNetMessage> GetMessage(std::chrono::microseconds time, uint32_t& out_err_raw_size) override;
377 };
378 
382 public:
383  // prepare message for transport (header construction, error-correction computation, payload encryption, etc.)
384  virtual void prepareForTransport(CSerializedNetMsg& msg, std::vector<unsigned char>& header) = 0;
385  virtual ~TransportSerializer() {}
386 };
387 
389 public:
390  void prepareForTransport(CSerializedNetMsg& msg, std::vector<unsigned char>& header) override;
391 };
392 
394 class CNode
395 {
396  friend class CConnman;
397  friend struct ConnmanTestMsg;
398 
399 public:
400  std::unique_ptr<TransportDeserializer> m_deserializer;
401  std::unique_ptr<TransportSerializer> m_serializer;
402 
404  std::atomic<ServiceFlags> nServices{NODE_NONE};
405  SOCKET hSocket GUARDED_BY(cs_hSocket);
407  size_t nSendSize GUARDED_BY(cs_vSend){0};
409  size_t nSendOffset GUARDED_BY(cs_vSend){0};
410  uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
411  std::deque<std::vector<unsigned char>> vSendMsg GUARDED_BY(cs_vSend);
415 
417  std::list<CNetMessage> vProcessMsg GUARDED_BY(cs_vProcessMsg);
418  size_t nProcessQueueSize{0};
419 
421 
422  uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
423 
424  std::atomic<int64_t> nLastSend{0};
425  std::atomic<int64_t> nLastRecv{0};
427  const int64_t nTimeConnected;
428  std::atomic<int64_t> nTimeOffset{0};
429  // Address of this peer
430  const CAddress addr;
431  // Bind address of our side of the connection
434  const bool m_inbound_onion;
435  std::atomic<int> nVersion{0};
441  std::string cleanSubVer GUARDED_BY(cs_SubVer){};
442  bool m_prefer_evict{false}; // This peer is preferred for eviction.
443  bool HasPermission(NetPermissionFlags permission) const {
444  return NetPermissions::HasFlag(m_permissionFlags, permission);
445  }
446  bool fClient{false}; // set by version message
447  bool m_limited_node{false}; //after BIP159, set by version message
449  std::atomic_bool fSuccessfullyConnected{false};
450  // Setting fDisconnect to true will cause the node to be disconnected the
451  // next time DisconnectNodes() runs
452  std::atomic_bool fDisconnect{false};
454  std::atomic<int> nRefCount{0};
455 
456  const uint64_t nKeyedNetGroup;
457  std::atomic_bool fPauseRecv{false};
458  std::atomic_bool fPauseSend{false};
459 
461  switch (m_conn_type) {
464  return true;
469  return false;
470  } // no default case, so the compiler can warn about missing cases
471 
472  assert(false);
473  }
474 
475  bool IsFullOutboundConn() const {
477  }
478 
479  bool IsManualConn() const {
481  }
482 
483  bool IsBlockOnlyConn() const {
485  }
486 
487  bool IsFeelerConn() const {
489  }
490 
491  bool IsAddrFetchConn() const {
493  }
494 
495  bool IsInboundConn() const {
497  }
498 
499  bool ExpectServicesFromConn() const {
500  switch (m_conn_type) {
504  return false;
508  return true;
509  } // no default case, so the compiler can warn about missing cases
510 
511  assert(false);
512  }
513 
525 
526  // We selected peer as (compact blocks) high-bandwidth peer (BIP152)
527  std::atomic<bool> m_bip152_highbandwidth_to{false};
528  // Peer selected us as (compact blocks) high-bandwidth peer (BIP152)
529  std::atomic<bool> m_bip152_highbandwidth_from{false};
530 
531  struct TxRelay {
533  // We use fRelayTxes for two purposes -
534  // a) it allows us to not relay tx invs before receiving the peer's version message
535  // b) the peer may tell us in its version message that we should not relay tx invs
536  // unless it loads a bloom filter.
537  bool fRelayTxes GUARDED_BY(cs_filter){false};
538  std::unique_ptr<CBloomFilter> pfilter PT_GUARDED_BY(cs_filter) GUARDED_BY(cs_filter){nullptr};
539 
541  CRollingBloomFilter filterInventoryKnown GUARDED_BY(cs_tx_inventory){50000, 0.000001};
542  // Set of transaction ids we still have to announce.
543  // They are sorted by the mempool before relay, so the order is not important.
544  std::set<uint256> setInventoryTxToSend;
545  // Used for BIP35 mempool sending
546  bool fSendMempool GUARDED_BY(cs_tx_inventory){false};
547  // Last time a "MEMPOOL" request was serviced.
548  std::atomic<std::chrono::seconds> m_last_mempool_req{0s};
549  std::chrono::microseconds nNextInvSend{0};
550 
552  std::atomic<CAmount> minFeeFilter{0};
554  std::chrono::microseconds m_next_send_feefilter{0};
555  };
556 
557  // m_tx_relay == nullptr if we're not relaying transactions with this peer
558  std::unique_ptr<TxRelay> m_tx_relay;
559 
565  std::atomic<int64_t> nLastBlockTime{0};
566 
571  std::atomic<int64_t> nLastTXTime{0};
572 
574  std::atomic<std::chrono::microseconds> m_last_ping_time{0us};
575 
578  std::atomic<std::chrono::microseconds> m_min_ping_time{std::chrono::microseconds::max()};
579 
580  CNode(NodeId id, ServiceFlags nLocalServicesIn, SOCKET hSocketIn, const CAddress& addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const CAddress& addrBindIn, const std::string& addrNameIn, ConnectionType conn_type_in, bool inbound_onion);
581  ~CNode();
582  CNode(const CNode&) = delete;
583  CNode& operator=(const CNode&) = delete;
584 
585  NodeId GetId() const {
586  return id;
587  }
588 
589  uint64_t GetLocalNonce() const {
590  return nLocalHostNonce;
591  }
592 
593  int GetRefCount() const
594  {
595  assert(nRefCount >= 0);
596  return nRefCount;
597  }
598 
608  bool ReceiveMsgBytes(Span<const uint8_t> msg_bytes, bool& complete);
609 
610  void SetCommonVersion(int greatest_common_version)
611  {
613  m_greatest_common_version = greatest_common_version;
614  }
615  int GetCommonVersion() const
616  {
618  }
619 
620  CService GetAddrLocal() const;
622  void SetAddrLocal(const CService& addrLocalIn);
623 
625  {
626  nRefCount++;
627  return this;
628  }
629 
630  void Release()
631  {
632  nRefCount--;
633  }
634 
635  void AddKnownTx(const uint256& hash)
636  {
637  if (m_tx_relay != nullptr) {
638  LOCK(m_tx_relay->cs_tx_inventory);
639  m_tx_relay->filterInventoryKnown.insert(hash);
640  }
641  }
642 
643  void PushTxInventory(const uint256& hash)
644  {
645  if (m_tx_relay == nullptr) return;
646  LOCK(m_tx_relay->cs_tx_inventory);
647  if (!m_tx_relay->filterInventoryKnown.contains(hash)) {
648  m_tx_relay->setInventoryTxToSend.insert(hash);
649  }
650  }
651 
652  void CloseSocketDisconnect();
653 
654  void copyStats(CNodeStats &stats, const std::vector<bool> &m_asmap);
655 
657  {
658  return nLocalServices;
659  }
660 
661  std::string GetAddrName() const;
663  void MaybeSetAddrName(const std::string& addrNameIn);
664 
666 
668  void PongReceived(std::chrono::microseconds ping_time) {
669  m_last_ping_time = ping_time;
670  m_min_ping_time = std::min(m_min_ping_time.load(), ping_time);
671  }
672 
673 private:
674  const NodeId id;
675  const uint64_t nLocalHostNonce;
678 
695 
696  std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
697 
699  std::string addrName GUARDED_BY(cs_addrName);
700 
701  // Our address, as reported by the peer
702  CService addrLocal GUARDED_BY(cs_addrLocal);
704 
705  mapMsgCmdSize mapSendBytesPerMsgCmd GUARDED_BY(cs_vSend);
706  mapMsgCmdSize mapRecvBytesPerMsgCmd GUARDED_BY(cs_vRecv);
707 };
708 
713 {
714 public:
716  virtual void InitializeNode(CNode* pnode) = 0;
717 
719  virtual void FinalizeNode(const CNode& node) = 0;
720 
728  virtual bool ProcessMessages(CNode* pnode, std::atomic<bool>& interrupt) = 0;
729 
736  virtual bool SendMessages(CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(pnode->cs_sendProcessing) = 0;
737 
738 
739 protected:
744  ~NetEventsInterface() = default;
745 };
746 
747 class CConnman
748 {
749 public:
750 
751  struct Options
752  {
757  int nMaxAddnode = 0;
758  int nMaxFeeler = 0;
761  BanMan* m_banman = nullptr;
762  unsigned int nSendBufferMaxSize = 0;
763  unsigned int nReceiveFloodSize = 0;
764  uint64_t nMaxOutboundLimit = 0;
766  std::vector<std::string> vSeedNodes;
767  std::vector<NetWhitelistPermissions> vWhitelistedRange;
768  std::vector<NetWhitebindPermissions> vWhiteBinds;
769  std::vector<CService> vBinds;
770  std::vector<CService> onion_binds;
775  std::vector<std::string> m_specified_outgoing;
776  std::vector<std::string> m_added_nodes;
777  std::vector<bool> m_asmap;
779  };
780 
781  void Init(const Options& connOptions) {
782  nLocalServices = connOptions.nLocalServices;
783  nMaxConnections = connOptions.nMaxConnections;
784  m_max_outbound_full_relay = std::min(connOptions.m_max_outbound_full_relay, connOptions.nMaxConnections);
787  nMaxAddnode = connOptions.nMaxAddnode;
788  nMaxFeeler = connOptions.nMaxFeeler;
790  clientInterface = connOptions.uiInterface;
791  m_banman = connOptions.m_banman;
792  m_msgproc = connOptions.m_msgproc;
794  nReceiveFloodSize = connOptions.nReceiveFloodSize;
796  {
798  nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
799  }
800  vWhitelistedRange = connOptions.vWhitelistedRange;
801  {
803  vAddedNodes = connOptions.m_added_nodes;
804  }
805  m_onion_binds = connOptions.onion_binds;
806  }
807 
808  CConnman(uint64_t seed0, uint64_t seed1, CAddrMan& addrman, bool network_active = true);
809  ~CConnman();
810  bool Start(CScheduler& scheduler, const Options& options);
811 
812  void StopThreads();
813  void StopNodes();
814  void Stop()
815  {
816  StopThreads();
817  StopNodes();
818  };
819 
820  void Interrupt();
821  bool GetNetworkActive() const { return fNetworkActive; };
823  void SetNetworkActive(bool active);
824  void OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant* grantOutbound, const char* strDest, ConnectionType conn_type);
825  bool CheckIncomingNonce(uint64_t nonce);
826 
827  bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
828 
829  void PushMessage(CNode* pnode, CSerializedNetMsg&& msg);
830 
831  using NodeFn = std::function<void(CNode*)>;
832  void ForEachNode(const NodeFn& func)
833  {
834  LOCK(cs_vNodes);
835  for (auto&& node : vNodes) {
837  func(node);
838  }
839  };
840 
841  void ForEachNode(const NodeFn& func) const
842  {
843  LOCK(cs_vNodes);
844  for (auto&& node : vNodes) {
846  func(node);
847  }
848  };
849 
850  // Addrman functions
858  std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct, std::optional<Network> network) const;
865  std::vector<CAddress> GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct);
866 
867  // This allows temporarily exceeding m_max_outbound_full_relay, with the goal of finding
868  // a peer that is better than all our current peers.
869  void SetTryNewOutboundPeer(bool flag);
870  bool GetTryNewOutboundPeer() const;
871 
873  LogPrint(BCLog::NET, "net: enabling extra block-relay-only peers\n");
875  }
876 
877  // Return the number of outbound peers we have in excess of our target (eg,
878  // if we previously called SetTryNewOutboundPeer(true), and have since set
879  // to false, we may have extra peers that we wish to disconnect). This may
880  // return a value less than (num_outbound_connections - num_outbound_slots)
881  // in cases where some outbound connections are not yet fully connected, or
882  // not yet fully disconnected.
883  int GetExtraFullOutboundCount() const;
884  // Count the number of block-relay-only peers we have over our limit.
885  int GetExtraBlockRelayCount() const;
886 
887  bool AddNode(const std::string& node);
888  bool RemoveAddedNode(const std::string& node);
889  std::vector<AddedNodeInfo> GetAddedNodeInfo() const;
890 
903  bool AddConnection(const std::string& address, ConnectionType conn_type);
904 
905  size_t GetNodeCount(ConnectionDirection) const;
906  void GetNodeStats(std::vector<CNodeStats>& vstats) const;
907  bool DisconnectNode(const std::string& node);
908  bool DisconnectNode(const CSubNet& subnet);
909  bool DisconnectNode(const CNetAddr& addr);
910  bool DisconnectNode(NodeId id);
911 
919 
920  uint64_t GetMaxOutboundTarget() const;
921  std::chrono::seconds GetMaxOutboundTimeframe() const;
922 
926  bool OutboundTargetReached(bool historicalBlockServingLimit) const;
927 
930  uint64_t GetOutboundTargetBytesLeft() const;
931 
934  std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const;
935 
936  uint64_t GetTotalBytesRecv() const;
937  uint64_t GetTotalBytesSent() const;
938 
940  CSipHasher GetDeterministicRandomizer(uint64_t id) const;
941 
942  unsigned int GetReceiveFloodSize() const;
943 
944  void WakeMessageHandler();
945 
950  std::chrono::microseconds PoissonNextSendInbound(std::chrono::microseconds now, std::chrono::seconds average_interval);
951 
952  void SetAsmap(std::vector<bool> asmap) { addrman.m_asmap = std::move(asmap); }
953 
955  bool ShouldRunInactivityChecks(const CNode& node, std::optional<int64_t> now=std::nullopt) const;
956 
957 private:
958  struct ListenSocket {
959  public:
962  ListenSocket(SOCKET socket_, NetPermissionFlags permissions_) : socket(socket_), m_permissions(permissions_) {}
963  private:
965  };
966 
967  bool BindListenPort(const CService& bindAddr, bilingual_str& strError, NetPermissionFlags permissions);
968  bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions);
969  bool InitBinds(const Options& options);
970 
972  void AddAddrFetch(const std::string& strDest);
973  void ProcessAddrFetch();
974  void ThreadOpenConnections(std::vector<std::string> connect);
975  void ThreadMessageHandler();
977  void AcceptConnection(const ListenSocket& hListenSocket);
978 
988  NetPermissionFlags permissionFlags,
989  const CAddress& addr_bind,
990  const CAddress& addr);
991 
992  void DisconnectNodes();
995  bool InactivityCheck(const CNode& node) const;
996  bool GenerateSelectSet(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set);
997  void SocketEvents(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set);
998  void SocketHandler();
999  void ThreadSocketHandler();
1000  void ThreadDNSAddressSeed();
1001 
1002  uint64_t CalculateKeyedNetGroup(const CAddress& ad) const;
1003 
1004  CNode* FindNode(const CNetAddr& ip);
1005  CNode* FindNode(const CSubNet& subNet);
1006  CNode* FindNode(const std::string& addrName);
1007  CNode* FindNode(const CService& addr);
1008 
1013  bool AlreadyConnectedToAddress(const CAddress& addr);
1014 
1015  bool AttemptToEvictConnection();
1016  CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type);
1018 
1019  void DeleteNode(CNode* pnode);
1020 
1021  NodeId GetNewNodeId();
1022 
1023  size_t SocketSendData(CNode& node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend);
1024  void DumpAddresses();
1025 
1026  // Network stats
1027  void RecordBytesRecv(uint64_t bytes);
1028  void RecordBytesSent(uint64_t bytes);
1029 
1033  std::vector<CAddress> GetCurrentBlockRelayOnlyConns() const;
1034 
1035  // Whether the node should be passed out in ForEach* callbacks
1036  static bool NodeFullyConnected(const CNode* pnode);
1037 
1038  // Network usage totals
1041  uint64_t nTotalBytesRecv GUARDED_BY(cs_totalBytesRecv) {0};
1042  uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent) {0};
1043 
1044  // outbound limit & stats
1045  uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent) {0};
1046  std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent) {0};
1047  uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent);
1048 
1049  // P2P timeout in seconds
1051 
1052  // Whitelisted ranges. Any node connecting from these is automatically
1053  // whitelisted (as well as those connecting to whitelisted binds).
1054  std::vector<NetWhitelistPermissions> vWhitelistedRange;
1055 
1056  unsigned int nSendBufferMaxSize{0};
1057  unsigned int nReceiveFloodSize{0};
1058 
1059  std::vector<ListenSocket> vhListenSocket;
1060  std::atomic<bool> fNetworkActive{true};
1063  std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
1065  std::vector<std::string> vAddedNodes GUARDED_BY(cs_vAddedNodes);
1067  std::vector<CNode*> vNodes GUARDED_BY(cs_vNodes);
1068  std::list<CNode*> vNodesDisconnected;
1070  std::atomic<NodeId> nLastNodeId{0};
1071  unsigned int nPrevNodeCount{0};
1072 
1080  std::vector<CAddress> m_addrs_response_cache;
1081  std::chrono::microseconds m_cache_entry_expiration{0};
1082  };
1083 
1098  std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
1099 
1113 
1114  std::unique_ptr<CSemaphore> semOutbound;
1115  std::unique_ptr<CSemaphore> semAddnode;
1117 
1118  // How many full-relay (tx, block, addr) outbound peers we want
1120 
1121  // How many block-relay only outbound peers we want
1122  // We do not relay tx or addr messages with these peers
1124 
1133 
1138  std::vector<CAddress> m_anchors;
1139 
1141  const uint64_t nSeed0, nSeed1;
1142 
1144  bool fMsgProcWake GUARDED_BY(mutexMsgProc);
1145 
1146  std::condition_variable condMsgProc;
1148  std::atomic<bool> flagInterruptMsgProc{false};
1149 
1157 
1162  std::unique_ptr<i2p::sam::Session> m_i2p_sam_session;
1163 
1165  std::thread threadSocketHandler;
1170 
1175 
1180  std::atomic_bool m_start_extra_block_relay_peers{false};
1181 
1182  std::atomic<std::chrono::microseconds> m_next_send_inv_to_incoming{0us};
1183 
1188  std::vector<CService> m_onion_binds;
1189 
1190  friend struct CConnmanTest;
1191  friend struct ConnmanTestMsg;
1192 };
1193 
1195 std::chrono::microseconds PoissonNextSend(std::chrono::microseconds now, std::chrono::seconds average_interval);
1196 
1198 void CaptureMessage(const CAddress& addr, const std::string& msg_type, const Span<const unsigned char>& data, bool is_incoming);
1199 
1201 {
1204  std::chrono::microseconds m_min_ping_time;
1206  int64_t nLastTXTime;
1210  uint64_t nKeyedNetGroup;
1214 };
1215 
1223 [[nodiscard]] std::optional<NodeId> SelectNodeToEvict(std::vector<NodeEvictionCandidate>&& vEvictionCandidates);
1224 
1246 void ProtectEvictionCandidatesByRatio(std::vector<NodeEvictionCandidate>& vEvictionCandidates);
1247 
1248 #endif // BITCOIN_NET_H
std::chrono::microseconds m_min_ping_time
Definition: net.h:264
std::vector< CService > vBinds
Definition: net.h:769
int m_max_outbound_full_relay
Definition: net.h:755
std::atomic< bool > flagInterruptMsgProc
Definition: net.h:1148
uint256 data_hash
Definition: net.h:322
void copyStats(CNodeStats &stats, const std::vector< bool > &m_asmap)
Definition: net.cpp:569
std::vector< CAddress > m_addrs_response_cache
Definition: net.h:1080
std::chrono::microseconds m_min_ping_time
Definition: net.h:1204
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:66
std::optional< NodeId > SelectNodeToEvict(std::vector< NodeEvictionCandidate > &&vEvictionCandidates)
Select an inbound peer to evict after filtering out (protecting) peers having distinct, difficult-to-forge characteristics.
Definition: net.cpp:980
uint64_t CalculateKeyedNetGroup(const CAddress &ad) const
Definition: net.cpp:3084
std::string m_type
Definition: net.h:111
uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1042
CONSTEXPR_IF_NOT_DEBUG Span< C > subspan(std::size_t offset) const noexcept
Definition: span.h:189
int nMaxFeeler
Definition: net.h:1126
void SocketHandler()
Definition: net.cpp:1512
std::vector< bool > m_asmap
Definition: net.h:777
bool IsReachable(enum Network net)
Definition: net.cpp:276
std::atomic_bool fPauseSend
Definition: net.h:458
void ThreadOpenAddedConnections()
Definition: net.cpp:2171
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:58
bool m_i2p_accept_incoming
Definition: net.h:778
std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const
returns the time left in the current max outbound cycle in case of no limit, it will always return 0 ...
Definition: net.cpp:2913
int m_max_outbound
Definition: net.h:1127
mapMsgCmdSize mapRecvBytesPerMsgCmd
Definition: net.h:261
std::atomic< bool > fNetworkActive
Definition: net.h:1060
uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1045
Definition: banman.h:58
static void AddFlag(NetPermissionFlags &flags, NetPermissionFlags f)
ServiceFlags
nServices flags
Definition: protocol.h:271
void SetNull()
Definition: uint256.h:39
friend struct ConnmanTestMsg
Definition: net.h:397
std::unique_ptr< TransportSerializer > m_serializer
Definition: net.h:401
RecursiveMutex cs_vNodes
Definition: net.h:1069
#define LogPrint(category,...)
Definition: logging.h:188
std::string cleanSubVer GUARDED_BY(cs_SubVer)
cleanSubVer is a sanitized string of the user agent byte array we read from the wire.
Definition: net.h:441
int64_t nTimeOffset
Definition: net.h:250
int readData(Span< const uint8_t > msg_bytes)
Definition: net.cpp:710
assert(!tx.IsCoinBase())
bool fListen
Definition: net.cpp:109
int m_max_outbound_block_relay
Definition: net.h:756
We open manual connections to addresses that users explicitly requested via the addnode RPC or the -a...
uint32_t m_mapped_as
Definition: net.h:274
void WakeMessageHandler()
Definition: net.cpp:1640
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
Definition: net.cpp:2469
bool fRelayTxes GUARDED_BY(cs_filter)
Definition: net.h:537
uint64_t GetOutboundTargetBytesLeft() const
response the bytes left in the current max outbound cycle in case of no limit, it will always respons...
Definition: net.cpp:2947
void Interrupt()
Definition: net.cpp:2638
int64_t nLastTXTime
Definition: net.h:1206
Bilingual messages:
Definition: translation.h:16
void SocketEvents(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set)
Definition: net.cpp:1437
const std::string NET_MESSAGE_COMMAND_OTHER
Definition: net.cpp:100
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(cs_mapLocalHost)
void SetVersion(int nVersionIn) override
Definition: net.h:361
void PushTxInventory(const uint256 &hash)
Definition: net.h:643
BanMan * m_banman
Definition: net.h:761
Mutex mutexMsgProc
Definition: net.h:1147
static const bool DEFAULT_FORCEDNSSEED
Definition: net.h:82
const uint64_t nKeyedNetGroup
Definition: net.h:456
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:288
CNode & operator=(const CNode &)=delete
CDataStream hdrbuf
Definition: net.h:324
bool IsOutboundOrBlockRelayConn() const
Definition: net.h:460
std::vector< unsigned char > data
Definition: net.h:110
unsigned int nDataPos
Definition: net.h:328
const ConnectionType m_conn_type
Definition: net.h:676
void ProtectEvictionCandidatesByRatio(std::vector< NodeEvictionCandidate > &vEvictionCandidates)
Protect desirable or disadvantaged inbound peers from eviction by ratio.
Definition: net.cpp:907
uint64_t GetTotalBytesRecv() const
Definition: net.cpp:2956
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:1054
bool IsFeelerConn() const
Definition: net.h:487
unsigned int nReceiveFloodSize
Definition: net.h:763
uint16_t GetListenPort()
Definition: net.cpp:121
RecursiveMutex cs_filter
Definition: net.h:532
int m_max_outbound_full_relay
Definition: net.h:1119
mapMsgCmdSize mapSendBytesPerMsgCmd
Definition: net.h:259
CClientUIInterface * uiInterface
Definition: net.h:759
void resize(size_type n, value_type c=0)
Definition: streams.h:257
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:1188
void SetAsmap(std::vector< bool > asmap)
Definition: net.h:952
void ProcessAddrFetch()
Definition: net.cpp:1770
void CaptureMessage(const CAddress &addr, const std::string &msg_type, const Span< const unsigned char > &data, bool is_incoming)
Dump binary message to file, with timestamp.
Definition: net.cpp:3091
ServiceFlags nServices
Definition: net.h:243
bool AlreadyConnectedToAddress(const CAddress &addr)
Determine whether we&#39;re already connected to a given address, in order to avoid initiating duplicate ...
Definition: net.cpp:351
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, const CNetAddr &addr) const
Definition: net.cpp:510
CDataStream m_recv
received message data
Definition: net.h:285
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:70
CNetMessage(CDataStream &&recv_in)
Definition: net.h:291
int nMaxAddnode
Definition: net.h:1125
RAII-style semaphore lock.
Definition: sync.h:315
std::chrono::microseconds nNextInvSend
Definition: net.h:549
friend struct CConnmanTest
Definition: net.h:1190
void SetCommonVersion(int greatest_common_version)
Definition: net.h:610
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:64
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
Definition: net.cpp:3017
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
Definition: net.cpp:2328
RecursiveMutex cs_vProcessMsg
Definition: net.h:416
uint32_t m_message_size
size of the payload
Definition: net.h:287
bool m_prefer_evict
Definition: net.h:442
std::string cleanSubVer
Definition: net.h:253
Interface for message handling.
Definition: net.h:712
void SetVersion(int nVersionIn)
Definition: net.h:293
RecursiveMutex cs_addrName
Definition: net.h:698
RollingBloomFilter is a probabilistic "keep track of most recently inserted" set. ...
Definition: bloom.h:110
NetEventsInterface * m_msgproc
Definition: net.h:1130
CAmount minFeeFilter
Definition: net.h:265
int nMaxConnections
Definition: net.h:754
CSerializedNetMsg()=default
int64_t nTimeConnected
Definition: net.h:249
void CreateNodeFromAcceptedSocket(SOCKET hSocket, NetPermissionFlags permissionFlags, 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 vNodes member...
Definition: net.cpp:1118
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:69
CAddrMan & addrman
Definition: net.h:1062
void ForEachNode(const NodeFn &func) const
Definition: net.h:841
int m_max_outbound_block_relay
Definition: net.h:1123
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:204
void SetTryNewOutboundPeer(bool flag)
Definition: net.cpp:1792
uint32_t nMessageSize
Definition: protocol.h:56
A hasher class for Bitcoin&#39;s 256-bit hash (double SHA-256).
Definition: hash.h:24
uint64_t GetLocalNonce() const
Definition: net.h:589
std::unique_ptr< TransportDeserializer > m_deserializer
Definition: net.h:400
void ThreadSocketHandler()
Definition: net.cpp:1630
CAmount lastSentFeeFilter
Definition: net.h:553
virtual void prepareForTransport(CSerializedNetMsg &msg, std::vector< unsigned char > &header)=0
NetPermissionFlags
ConnectionType m_conn_type
Definition: net.h:275
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Definition: net.h:410
static const int TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:52
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:2734
void GetNodeStats(std::vector< CNodeStats > &vstats) const
Definition: net.cpp:2825
Definition: net.h:196
Signals for UI communication.
Definition: ui_interface.h:24
void StopThreads()
Definition: net.cpp:2662
std::list< CNetMessage > vRecvMsg
Definition: net.h:696
bool GetTryNewOutboundPeer() const
Definition: net.cpp:1787
void NotifyNumConnectionsChanged()
Definition: net.cpp:1297
const NodeId m_node_id
Definition: net.h:320
void RecordBytesSent(uint64_t bytes)
Definition: net.cpp:2885
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:1098
std::atomic< ServiceFlags > nServices
Definition: net.h:404
void SetAddrLocal(const CService &addrLocalIn)
May not be called more than once.
Definition: net.cpp:553
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition: net.h:68
static bool HasFlag(NetPermissionFlags flags, NetPermissionFlags f)
bool fConnected
Definition: net.h:94
virtual ~TransportDeserializer()
Definition: net.h:313
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition: net.h:961
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:3049
int GetRefCount() const
Definition: net.h:593
RecursiveMutex cs_sendProcessing
Definition: net.h:420
ServiceFlags nLocalServices
Services this instance offers.
Definition: net.h:1112
bool DisconnectNode(const std::string &node)
Definition: net.cpp:2836
Stochastical (IP) address manager.
Definition: addrman.h:173
CHash256 hasher
Definition: net.h:321
int GetExtraBlockRelayCount() const
Definition: net.cpp:1818
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
std::atomic< int64_t > nLastSend
Definition: net.h:424
std::atomic< CAmount > minFeeFilter
Minimum fee rate with which to filter inv&#39;s to this node.
Definition: net.h:552
uint16_t nPort
Definition: net.h:230
void RecordBytesRecv(uint64_t bytes)
Definition: net.cpp:2879
void DumpAddresses()
Definition: net.cpp:1759
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:85
std::chrono::microseconds PoissonNextSendInbound(std::chrono::microseconds now, std::chrono::seconds average_interval)
Attempts to obfuscate tx time through exponentially distributed emitting.
Definition: net.cpp:3062
std::thread threadI2PAcceptIncoming
Definition: net.h:1169
int64_t nLastTXTime
Definition: net.h:247
ServiceFlags GetLocalServices() const
Definition: net.h:656
int nVersion
Definition: net.h:252
bool fClient
Definition: net.h:446
void CloseSocketDisconnect()
Definition: net.cpp:499
RecursiveMutex cs_tx_inventory
Definition: net.h:538
void Release()
Definition: net.h:630
std::chrono::microseconds m_cache_entry_expiration
Definition: net.h:1081
void AddAddrFetch(const std::string &strDest)
Definition: net.cpp:115
bool GetLocal(CService &addr, const CNetAddr *paddrPeer=nullptr)
Definition: net.cpp:127
static bool NodeFullyConnected(const CNode *pnode)
Definition: net.cpp:3012
unsigned int nPrevNodeCount
Definition: net.h:1071
bool InactivityCheck(const CNode &node) const
Return true if the peer is inactive and should be disconnected.
Definition: net.cpp:1317
bool AddNode(const std::string &node)
Definition: net.cpp:2786
size_t nProcessQueueSize
Definition: net.h:418
std::condition_variable condMsgProc
Definition: net.h:1146
std::atomic_bool m_start_extra_block_relay_peers
flag for initiating extra block-relay-only peer connections.
Definition: net.h:1180
RecursiveMutex cs_vAddedNodes
Definition: net.h:1066
CService GetAddrLocal() const
Definition: net.cpp:548
virtual int Read(Span< const uint8_t > &msg_bytes)=0
read and deserialize data, advances msg_bytes data pointer
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *strDest, ConnectionType conn_type)
Definition: net.cpp:2199
size_t SocketSendData(CNode &node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend)
Definition: net.cpp:785
ListenSocket(SOCKET socket_, NetPermissionFlags permissions_)
Definition: net.h:962
int m_starting_height
Definition: net.h:257
std::atomic< int64_t > nLastRecv
Definition: net.h:425
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
Definition: net.cpp:516
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition: net.h:1141
int Read(Span< const uint8_t > &msg_bytes) override
read and deserialize data, advances msg_bytes data pointer
Definition: net.h:366
std::thread threadOpenAddedConnections
Definition: net.h:1166
Network m_network
Definition: net.h:1213
#define LOCK(cs)
Definition: sync.h:232
Mutex cs_hSocket
Definition: net.h:413
void StartExtraBlockRelayPeers()
Definition: net.h:872
CNode * FindNode(const CNetAddr &ip)
Definition: net.cpp:307
ServiceFlags GetLocalServices() const
Used to convey which local services we are offering peers during node connection. ...
Definition: net.cpp:2968
RecursiveMutex m_addr_fetches_mutex
Definition: net.h:1064
bool IsPeerAddrLocalGood(CNode *pnode)
Definition: net.cpp:197
std::function< void(CNode *)> NodeFn
Definition: net.h:831
NetEventsInterface * m_msgproc
Definition: net.h:760
static const int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
Definition: version.h:15
std::string strAddedNode
Definition: net.h:92
CConnman(uint64_t seed0, uint64_t seed1, CAddrMan &addrman, bool network_active=true)
Definition: net.cpp:2453
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:560
Transport protocol agnostic message container.
Definition: net.h:283
const CAddress addrBind
Definition: net.h:432
std::vector< std::string > vSeedNodes
Definition: net.h:766
std::vector< std::string > m_specified_outgoing
Definition: net.h:775
bool m_bip152_highbandwidth_from
Definition: net.h:256
int64_t m_peer_connect_timeout
Definition: net.h:1050
void DisconnectNodes()
Definition: net.cpp:1247
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:1114
void ThreadOpenConnections(std::vector< std::string > connect)
Definition: net.cpp:1832
std::thread threadMessageHandler
Definition: net.h:1168
friend struct ConnmanTestMsg
Definition: net.h:1191
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
Definition: net.h:80
Network m_network
Definition: net.h:273
bool fInbound
Definition: net.h:254
const uint256 & GetMessageHash() const
Definition: net.cpp:727
~NetEventsInterface()=default
Protected destructor so that instances can only be deleted by derived classes.
bool IsManualConn() const
Definition: net.h:479
virtual void FinalizeNode(const CNode &node)=0
Handle removal of a peer (clear state)
int GetExtraFullOutboundCount() const
Definition: net.cpp:1804
std::chrono::microseconds m_last_ping_time
Definition: net.h:263
A CService with information about it as peer.
Definition: protocol.h:358
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const
Return vector of current BLOCK_RELAY peers.
Definition: net.cpp:2104
bool Start(CScheduler &scheduler, const Options &options)
Definition: net.cpp:2510
uint64_t nRecvBytes
Definition: net.h:260
void MaybeSetAddrName(const std::string &addrNameIn)
Sets the addrName only if it was not previously set.
Definition: net.cpp:541
RecursiveMutex cs_mapLocalHost
Definition: net.cpp:110
bool fInbound
Definition: net.h:95
std::string addrName
Definition: net.h:251
int nMaxFeeler
Definition: net.h:758
Network
A network type.
Definition: netaddress.h:45
bool ReceiveMsgBytes(Span< const uint8_t > msg_bytes, bool &complete)
Receive bytes from the buffer and deserialize them into messages.
Definition: net.cpp:626
bool m_bip152_highbandwidth_to
Definition: net.h:255
bool ExpectServicesFromConn() const
Definition: net.h:499
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:1174
int64_t NodeId
Definition: net.h:88
bool InitBinds(const Options &options)
Definition: net.cpp:2488
Definition: net.h:747
void SetNetworkActive(bool active)
Definition: net.cpp:2440
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:72
bool GetNetworkActive() const
Definition: net.h:821
std::atomic< bool > m_bip152_highbandwidth_to
Definition: net.h:527
CClientUIInterface * clientInterface
Definition: net.h:1129
NodeId GetId() const
Definition: net.h:585
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition: net.cpp:3079
std::optional< CNetMessage > GetMessage(std::chrono::microseconds time, uint32_t &out_err_raw_size) override
Definition: net.cpp:735
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e. connected via our Tor onion service.
Definition: net.h:434
uint64_t nSendBytes
Definition: net.h:258
std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1046
void PongReceived(std::chrono::microseconds ping_time)
A ping-pong round trip has completed successfully.
Definition: net.h:668
std::atomic_bool fDisconnect
Definition: net.h:452
int nMaxConnections
Definition: net.h:1116
The TransportSerializer prepares messages for the network transport.
Definition: net.h:381
std::set< uint256 > setInventoryTxToSend
Definition: net.h:541
void prepareForTransport(CSerializedNetMsg &msg, std::vector< unsigned char > &header) override
Definition: net.cpp:772
std::atomic< std::chrono::seconds > m_last_mempool_req
Definition: net.h:548
#define Assume(val)
Assume is the identity function.
Definition: check.h:72
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Definition: net.h:422
void Discover()
Definition: net.cpp:2389
unsigned int GetReceiveFloodSize() const
Definition: net.cpp:2973
Inbound connections are those initiated by a peer.
~CNode()
Definition: net.cpp:3007
void DeleteNode(CNode *pnode)
Definition: net.cpp:2721
RecursiveMutex cs_SubVer
Definition: net.h:436
unsigned int SOCKET
Definition: compat.h:41
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
Definition: net.h:1162
NetPermissionFlags m_permissions
Definition: net.h:964
bool CheckIncomingNonce(uint64_t nonce)
Definition: net.cpp:356
const CAddress addr
Definition: net.h:430
std::atomic< int > nRefCount
Definition: net.h:454
CNode(NodeId id, ServiceFlags nLocalServicesIn, SOCKET hSocketIn, const CAddress &addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const CAddress &addrBindIn, const std::string &addrNameIn, ConnectionType conn_type_in, bool inbound_onion)
Definition: net.cpp:2975
bool Complete() const override
Definition: net.h:355
static const bool DEFAULT_DNSSEED
Definition: net.h:83
bool IsBlockOnlyConn() const
Definition: net.h:483
std::chrono::microseconds m_next_send_feefilter
Definition: net.h:554
CDataStream vRecv
Definition: net.h:326
const int64_t nTimeConnected
Unix epoch time at peer connection, in seconds.
Definition: net.h:427
CMessageHeader hdr
Definition: net.h:325
virtual ~TransportSerializer()
Definition: net.h:385
int flags
Definition: bitcoin-tx.cpp:512
std::atomic< NodeId > nLastNodeId
Definition: net.h:1070
static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:74
bool RemoveAddedNode(const std::string &node)
Definition: net.cpp:2797
Network address.
Definition: netaddress.h:121
std::list< CNode * > vNodesDisconnected
Definition: net.h:1068
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type)
Definition: net.cpp:382
256-bit opaque blob.
Definition: uint256.h:124
void RemoveLocal(const CService &addr)
Definition: net.cpp:261
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:767
std::vector< CService > onion_binds
Definition: net.h:770
size_t GetNodeCount(ConnectionDirection) const
Definition: net.cpp:2809
uint32_t m_raw_message_size
used wire size of the message (including header/checksum)
Definition: net.h:288
int nScore
Definition: net.h:229
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
bool ShouldRunInactivityChecks(const CNode &node, std::optional< int64_t > now=std::nullopt) const
Return true if we should disconnect the peer for failing an inactivity check.
Definition: net.cpp:1311
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
Definition: net.h:49
int nMaxAddnode
Definition: net.h:757
BanMan * m_banman
Pointer to this node&#39;s banman.
Definition: net.h:1132
void AddKnownTx(const uint256 &hash)
Definition: net.h:635
std::atomic< int64_t > nLastTXTime
UNIX epoch time of the last transaction received from this peer that we had not yet seen (e...
Definition: net.h:571
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:86
CAddress addrBind
Definition: net.h:271
bool fSendMempool GUARDED_BY(cs_tx_inventory)
Definition: net.h:546
Mutex cs_vRecv
Definition: net.h:414
~CConnman()
Definition: net.cpp:2728
CService resolvedAddress
Definition: net.h:93
std::thread threadOpenConnections
Definition: net.h:1167
bool AttemptToEvictConnection()
Try to find a connection to evict when the node is full.
Definition: net.cpp:1048
ConnectionType
Different types of connections to a peer.
Definition: net.h:121
int readHeader(Span< const uint8_t > msg_bytes)
Definition: net.cpp:670
CSemaphoreGrant grantOutbound
Definition: net.h:453
The TransportDeserializer takes care of holding and deserializing the network receive buffer...
Definition: net.h:303
const CChainParams & m_chain_params
Definition: net.h:319
std::map< std::string, uint64_t > mapMsgCmdSize
Definition: net.h:237
const NodeId id
Definition: net.h:674
NodeId GetNewNodeId()
Definition: net.cpp:2463
Feeler connections are short-lived connections made to check that a node is alive.
std::vector< AddedNodeInfo > GetAddedNodeInfo() const
Definition: net.cpp:2117
std::string addrLocal
Definition: net.h:267
NetPermissionFlags m_permissionFlags
Definition: net.h:403
bool fAddressesInitialized
Definition: net.h:1061
std::thread threadDNSAddressSeed
Definition: net.h:1164
ServiceFlags nLocalServices
Definition: net.h:753
int64_t nTimeConnected
Definition: net.h:1203
uint64_t nMaxOutboundLimit
Definition: net.h:764
std::vector< std::string > m_added_nodes
Definition: net.h:776
std::vector< ListenSocket > vhListenSocket
Definition: net.h:1059
std::chrono::seconds GetMaxOutboundTimeframe() const
Definition: net.cpp:2908
std::atomic< int > m_greatest_common_version
Definition: net.h:677
Mutex cs_vSend
Definition: net.h:412
std::atomic< int64_t > nTimeOffset
Definition: net.h:428
size_t nSendOffset GUARDED_BY(cs_vSend)
Offset inside the first vSendMsg already sent.
Definition: net.h:409
std::atomic_bool fSuccessfullyConnected
fSuccessfullyConnected is set to true on receiving VERACK from the peer.
Definition: net.h:449
SipHash-2-4.
Definition: siphash.h:13
void ThreadMessageHandler()
Definition: net.cpp:2234
These are the default connections that we use to connect with the network.
bool OutboundTargetReached(bool historicalBlockServingLimit) const
check if the outbound target is reached if param historicalBlockServingLimit is set true...
Definition: net.cpp:2927
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:60
static constexpr auto FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes.
Definition: net.h:54
uint64_t nTotalBytesRecv GUARDED_BY(cs_totalBytesRecv)
Definition: net.h:1041
void StopNodes()
Definition: net.cpp:2679
std::atomic< int > nVersion
Definition: net.h:435
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition: net.h:78
unsigned int nSendBufferMaxSize
Definition: net.h:1056
static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL
Run the extra block-relay-only connection loop once every 5 minutes.
Definition: net.h:56
std::string ConnectionTypeAsString() const
Definition: net.h:665
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:76
const uint64_t nLocalHostNonce
Definition: net.h:675
unsigned int nSendBufferMaxSize
Definition: net.h:762
std::vector< bool > m_asmap
Definition: addrman.h:190
bool m_limited_node
Definition: net.h:447
std::atomic< bool > m_bip152_highbandwidth_from
Definition: net.h:529
std::string m_command
Definition: net.h:289
void ThreadI2PAcceptIncoming()
Definition: net.cpp:2289
void clear()
Definition: streams.h:261
const ServiceFlags nLocalServices
Services offered to this peer.
Definition: net.h:694
bool IsAddrFetchConn() const
Definition: net.h:491
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
Definition: net.h:47
bool AddConnection(const std::string &address, ConnectionType conn_type)
Attempts to open a connection.
Definition: net.cpp:1213
SOCKET hSocket GUARDED_BY(cs_hSocket)
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:62
bool GenerateSelectSet(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set)
Definition: net.cpp:1348
void AcceptConnection(const ListenSocket &hListenSocket)
Definition: net.cpp:1092
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:92
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:113
Definition: net.h:191
std::chrono::microseconds PoissonNextSend(std::chrono::microseconds now, std::chrono::seconds average_interval)
Return a timestamp in the future (in microseconds) for exponentially distributed events.
Definition: net.cpp:3073
uint64_t GetMaxOutboundTarget() const
Definition: net.cpp:2902
Information about a peer.
Definition: net.h:394
void ForEachNode(const NodeFn &func)
Definition: net.h:832
std::thread threadSocketHandler
Definition: net.h:1165
Simple class for background tasks that should be run periodically or once "after a while"...
Definition: scheduler.h:33
We use block-relay-only connections to help prevent against partition attacks.
RecursiveMutex cs_totalBytesRecv
Definition: net.h:1039
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:268
virtual bool Complete() const =0
std::atomic< std::chrono::microseconds > m_last_ping_time
Last measured round-trip time.
Definition: net.h:574
NetPermissionFlags m_permissionFlags
Definition: net.h:262
uint64_t nKeyedNetGroup
Definition: net.h:1210
Network ConnectedThroughNetwork() const
Get network the peer connected through.
Definition: net.cpp:562
virtual void InitializeNode(CNode *pnode)=0
Initialize a peer (setup state, queue any initial messages)
std::string GetAddrName() const
Definition: net.cpp:536
V1TransportDeserializer(const CChainParams &chain_params, const NodeId node_id, int nTypeIn, int nVersionIn)
Definition: net.h:346
std::chrono::microseconds m_time
time of message receipt
Definition: net.h:286
RecursiveMutex cs_addrLocal
Definition: net.h:703
bool fDiscover
Definition: net.cpp:108
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
Definition: net.h:1138
void SetVersion(int n)
Definition: streams.h:362
AddrFetch connections are short lived connections used to solicit addresses from peers.
std::atomic< std::chrono::microseconds > m_min_ping_time
Lowest measured round-trip time.
Definition: net.h:578
int GetCommonVersion() const
Definition: net.h:615
uint64_t GetTotalBytesSent() const
Definition: net.cpp:2962
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
std::atomic_bool fPauseRecv
Definition: net.h:457
CNode * AddRef()
Definition: net.h:624
virtual std::optional< CNetMessage > GetMessage(std::chrono::microseconds time, uint32_t &out_err)=0
std::unique_ptr< CSemaphore > semAddnode
Definition: net.h:1115
std::atomic< std::chrono::microseconds > m_next_send_inv_to_incoming
Definition: net.h:1182
void Init(const Options &connOptions)
Definition: net.h:781
CThreadInterrupt interruptNet
This is signaled when network activity should cease.
Definition: net.h:1156
unsigned int nHdrPos
Definition: net.h:327
ConnectionDirection
Definition: netbase.h:32
bool HasPermission(NetPermissionFlags permission) const
Definition: net.h:443
virtual void SetVersion(int version)=0
std::optional< CAddress > GetLocalAddrForPeer(CNode *pnode)
Returns a local address that we should advertise to this peer.
Definition: net.cpp:204
CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
Definition: net.cpp:177
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
Definition: net.cpp:230
bool IsInboundConn() const
Definition: net.h:495
const uint64_t nSeed1
Definition: net.h:1141
void Stop()
Definition: net.h:814
bool m_use_addrman_outgoing
Definition: net.h:774
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:768
std::atomic< int64_t > nLastBlockTime
UNIX epoch time of the last block received from this peer that we had not yet seen (e...
Definition: net.h:565
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:301
size_t nSendSize GUARDED_BY(cs_vSend)
Total size of all vSendMsg entries.
Definition: net.h:407
CHash256 & Reset()
Definition: hash.h:42
bool GetUseAddrmanOutgoing() const
Definition: net.h:822
bool fRelayTxes
Definition: net.h:244
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0...
Definition: net.h:773
int64_t nLastSend
Definition: net.h:245
int64_t nLastBlockTime
Definition: net.h:1205
bool m_use_addrman_outgoing
Definition: net.h:1128
Cache responses to addr requests to minimize privacy leak.
Definition: net.h:1079
virtual bool ProcessMessages(CNode *pnode, std::atomic< bool > &interrupt)=0
Process protocol messages received from a given node.
bool IsFullOutboundConn() const
Definition: net.h:475
NodeId nodeid
Definition: net.h:242
int64_t nLastRecv
Definition: net.h:246
RecursiveMutex cs_totalBytesSent
Definition: net.h:1040
unsigned int nReceiveFloodSize
Definition: net.h:1057
bool fRelevantServices
Definition: net.h:1207
std::unique_ptr< TxRelay > m_tx_relay
Definition: net.h:558
virtual bool SendMessages(CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(pnode -> cs_sendProcessing)=0
Send queued protocol messages to a given node.
CAddress addr
Definition: net.h:269
Message header.
Definition: protocol.h:30
void ThreadDNSAddressSeed()
Definition: net.cpp:1649
int64_t nLastBlockTime
Definition: net.h:248
int64_t m_peer_connect_timeout
Definition: net.h:765
std::unique_ptr< CBloomFilter > pfilter PT_GUARDED_BY(cs_filter) GUARDED_BY(cs_filter)
Definition: net.h:538
static const bool DEFAULT_FIXEDSEEDS
Definition: net.h:84