Bitcoin Core  21.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-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 constexpr size_t MAX_ADDR_TO_SEND = 1000;
60 static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
62 static const unsigned int MAX_SUBVERSION_LENGTH = 256;
66 static const int MAX_ADDNODE_CONNECTIONS = 8;
68 static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS = 2;
70 static const int MAX_FEELER_CONNECTIONS = 1;
72 static const bool DEFAULT_LISTEN = true;
74 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
76 static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET = 0;
78 static const bool DEFAULT_BLOCKSONLY = false;
80 static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
82 static const int NUM_FDS_MESSAGE_CAPTURE = 1;
83 
84 static const bool DEFAULT_FORCEDNSSEED = false;
85 static const bool DEFAULT_DNSSEED = true;
86 static const bool DEFAULT_FIXEDSEEDS = true;
87 static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
88 static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
89 
90 typedef int64_t NodeId;
91 
93 {
94  std::string strAddedNode;
96  bool fConnected;
97  bool fInbound;
98 };
99 
100 class CNodeStats;
101 class CClientUIInterface;
102 
104 {
105  CSerializedNetMsg() = default;
108  // No copying, only moves.
109  CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
111 
112  std::vector<unsigned char> data;
113  std::string m_type;
114 };
115 
123 enum class ConnectionType {
129  INBOUND,
130 
138 
139 
146  MANUAL,
147 
163  FEELER,
164 
174  BLOCK_RELAY,
175 
182  ADDR_FETCH,
183 };
184 
186 std::string ConnectionTypeAsString(ConnectionType conn_type);
187 void Discover();
188 uint16_t GetListenPort();
189 
190 enum
191 {
192  LOCAL_NONE, // unknown
193  LOCAL_IF, // address a local interface listens on
194  LOCAL_BIND, // address explicit bound to
195  LOCAL_MAPPED, // address reported by UPnP or NAT-PMP
196  LOCAL_MANUAL, // address explicitly specified (-externalip=)
197 
199 };
200 
201 bool IsPeerAddrLocalGood(CNode *pnode);
203 std::optional<CAddress> GetLocalAddrForPeer(CNode *pnode);
204 
209 void SetReachable(enum Network net, bool reachable);
211 bool IsReachable(enum Network net);
213 bool IsReachable(const CNetAddr& addr);
214 
215 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
216 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
217 void RemoveLocal(const CService& addr);
218 bool SeenLocal(const CService& addr);
219 bool IsLocal(const CService& addr);
220 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr);
221 CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices);
222 
223 
224 extern bool fDiscover;
225 extern bool fListen;
226 
228 extern std::string strSubVersion;
229 
231  int nScore;
232  uint16_t nPort;
233 };
234 
236 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(cs_mapLocalHost);
237 
238 extern const std::string NET_MESSAGE_COMMAND_OTHER;
239 typedef std::map<std::string, uint64_t> mapMsgCmdSize; //command, total bytes
240 
242 {
243 public:
247  int64_t nLastSend;
248  int64_t nLastRecv;
249  int64_t nLastTXTime;
250  int64_t nLastBlockTime;
251  int64_t nTimeConnected;
252  int64_t nTimeOffset;
253  std::string addrName;
254  int nVersion;
255  std::string cleanSubVer;
256  bool fInbound;
260  uint64_t nSendBytes;
262  uint64_t nRecvBytes;
265  std::chrono::microseconds m_last_ping_time;
266  std::chrono::microseconds m_min_ping_time;
268  // Our address, as reported by the peer
269  std::string addrLocal;
270  // Address of this peer
272  // Bind address of our side of the connection
274  // Network the peer connected through
276  uint32_t m_mapped_as;
278 };
279 
280 
285 class CNetMessage {
286 public:
288  std::chrono::microseconds m_time{0};
289  uint32_t m_message_size{0};
290  uint32_t m_raw_message_size{0};
291  std::string m_command;
292 
293  CNetMessage(CDataStream&& recv_in) : m_recv(std::move(recv_in)) {}
294 
295  void SetVersion(int nVersionIn)
296  {
297  m_recv.SetVersion(nVersionIn);
298  }
299 };
300 
306 public:
307  // returns true if the current deserialization is complete
308  virtual bool Complete() const = 0;
309  // set the serialization context version
310  virtual void SetVersion(int version) = 0;
312  virtual int Read(Span<const uint8_t>& msg_bytes) = 0;
313  // decomposes a message from the context
314  virtual std::optional<CNetMessage> GetMessage(std::chrono::microseconds time, uint32_t& out_err) = 0;
316 };
317 
319 {
320 private:
322  const NodeId m_node_id; // Only for logging
323  mutable CHash256 hasher;
325  bool in_data; // parsing header (false) or data (true)
326  CDataStream hdrbuf; // partially received header
327  CMessageHeader hdr; // complete header
328  CDataStream vRecv; // received message data
329  unsigned int nHdrPos;
330  unsigned int nDataPos;
331 
332  const uint256& GetMessageHash() const;
333  int readHeader(Span<const uint8_t> msg_bytes);
334  int readData(Span<const uint8_t> msg_bytes);
335 
336  void Reset() {
337  vRecv.clear();
338  hdrbuf.clear();
339  hdrbuf.resize(24);
340  in_data = false;
341  nHdrPos = 0;
342  nDataPos = 0;
343  data_hash.SetNull();
344  hasher.Reset();
345  }
346 
347 public:
348  V1TransportDeserializer(const CChainParams& chain_params, const NodeId node_id, int nTypeIn, int nVersionIn)
349  : m_chain_params(chain_params),
350  m_node_id(node_id),
351  hdrbuf(nTypeIn, nVersionIn),
352  vRecv(nTypeIn, nVersionIn)
353  {
354  Reset();
355  }
356 
357  bool Complete() const override
358  {
359  if (!in_data)
360  return false;
361  return (hdr.nMessageSize == nDataPos);
362  }
363  void SetVersion(int nVersionIn) override
364  {
365  hdrbuf.SetVersion(nVersionIn);
366  vRecv.SetVersion(nVersionIn);
367  }
368  int Read(Span<const uint8_t>& msg_bytes) override
369  {
370  int ret = in_data ? readData(msg_bytes) : readHeader(msg_bytes);
371  if (ret < 0) {
372  Reset();
373  } else {
374  msg_bytes = msg_bytes.subspan(ret);
375  }
376  return ret;
377  }
378  std::optional<CNetMessage> GetMessage(std::chrono::microseconds time, uint32_t& out_err_raw_size) override;
379 };
380 
384 public:
385  // prepare message for transport (header construction, error-correction computation, payload encryption, etc.)
386  virtual void prepareForTransport(CSerializedNetMsg& msg, std::vector<unsigned char>& header) = 0;
387  virtual ~TransportSerializer() {}
388 };
389 
391 public:
392  void prepareForTransport(CSerializedNetMsg& msg, std::vector<unsigned char>& header) override;
393 };
394 
396 class CNode
397 {
398  friend class CConnman;
399  friend struct ConnmanTestMsg;
400 
401 public:
402  std::unique_ptr<TransportDeserializer> m_deserializer;
403  std::unique_ptr<TransportSerializer> m_serializer;
404 
406  std::atomic<ServiceFlags> nServices{NODE_NONE};
407  SOCKET hSocket GUARDED_BY(cs_hSocket);
409  size_t nSendSize GUARDED_BY(cs_vSend){0};
411  size_t nSendOffset GUARDED_BY(cs_vSend){0};
412  uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
413  std::deque<std::vector<unsigned char>> vSendMsg GUARDED_BY(cs_vSend);
417 
419  std::list<CNetMessage> vProcessMsg GUARDED_BY(cs_vProcessMsg);
420  size_t nProcessQueueSize{0};
421 
423 
424  uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
425 
426  std::atomic<int64_t> nLastSend{0};
427  std::atomic<int64_t> nLastRecv{0};
429  const int64_t nTimeConnected;
430  std::atomic<int64_t> nTimeOffset{0};
431  // Address of this peer
432  const CAddress addr;
433  // Bind address of our side of the connection
436  const bool m_inbound_onion;
437  std::atomic<int> nVersion{0};
443  std::string cleanSubVer GUARDED_BY(cs_SubVer){};
444  bool m_prefer_evict{false}; // This peer is preferred for eviction.
445  bool HasPermission(NetPermissionFlags permission) const {
446  return NetPermissions::HasFlag(m_permissionFlags, permission);
447  }
448  bool fClient{false}; // set by version message
449  bool m_limited_node{false}; //after BIP159, set by version message
454  std::atomic_bool m_wants_addrv2{false};
456  std::atomic_bool fSuccessfullyConnected{false};
457  // Setting fDisconnect to true will cause the node to be disconnected the
458  // next time DisconnectNodes() runs
459  std::atomic_bool fDisconnect{false};
460  bool fSentAddr{false};
462  std::atomic<int> nRefCount{0};
463 
464  const uint64_t nKeyedNetGroup;
465  std::atomic_bool fPauseRecv{false};
466  std::atomic_bool fPauseSend{false};
467 
469  switch (m_conn_type) {
472  return true;
477  return false;
478  } // no default case, so the compiler can warn about missing cases
479 
480  assert(false);
481  }
482 
483  bool IsFullOutboundConn() const {
485  }
486 
487  bool IsManualConn() const {
489  }
490 
491  bool IsBlockOnlyConn() const {
493  }
494 
495  bool IsFeelerConn() const {
497  }
498 
499  bool IsAddrFetchConn() const {
501  }
502 
503  bool IsInboundConn() const {
505  }
506 
507  /* Whether we send addr messages over this connection */
508  bool RelayAddrsWithConn() const
509  {
510  // Don't relay addr messages to peers that we connect to as block-relay-only
511  // peers (to prevent adversaries from inferring these links from addr
512  // traffic).
514  }
515 
516  bool ExpectServicesFromConn() const {
517  switch (m_conn_type) {
521  return false;
525  return true;
526  } // no default case, so the compiler can warn about missing cases
527 
528  assert(false);
529  }
530 
542 
543  // We selected peer as (compact blocks) high-bandwidth peer (BIP152)
544  std::atomic<bool> m_bip152_highbandwidth_to{false};
545  // Peer selected us as (compact blocks) high-bandwidth peer (BIP152)
546  std::atomic<bool> m_bip152_highbandwidth_from{false};
547 
548  // flood relay
549  std::vector<CAddress> vAddrToSend;
550  std::unique_ptr<CRollingBloomFilter> m_addr_known{nullptr};
551  bool fGetAddr{false};
553  std::chrono::microseconds m_next_addr_send GUARDED_BY(m_addr_send_times_mutex){0};
554  std::chrono::microseconds m_next_local_addr_send GUARDED_BY(m_addr_send_times_mutex){0};
555 
556  struct TxRelay {
558  // We use fRelayTxes for two purposes -
559  // a) it allows us to not relay tx invs before receiving the peer's version message
560  // b) the peer may tell us in its version message that we should not relay tx invs
561  // unless it loads a bloom filter.
562  bool fRelayTxes GUARDED_BY(cs_filter){false};
563  std::unique_ptr<CBloomFilter> pfilter PT_GUARDED_BY(cs_filter) GUARDED_BY(cs_filter){nullptr};
564 
566  CRollingBloomFilter filterInventoryKnown GUARDED_BY(cs_tx_inventory){50000, 0.000001};
567  // Set of transaction ids we still have to announce.
568  // They are sorted by the mempool before relay, so the order is not important.
569  std::set<uint256> setInventoryTxToSend;
570  // Used for BIP35 mempool sending
571  bool fSendMempool GUARDED_BY(cs_tx_inventory){false};
572  // Last time a "MEMPOOL" request was serviced.
573  std::atomic<std::chrono::seconds> m_last_mempool_req{0s};
574  std::chrono::microseconds nNextInvSend{0};
575 
577  std::atomic<CAmount> minFeeFilter{0};
579  std::chrono::microseconds m_next_send_feefilter{0};
580  };
581 
582  // m_tx_relay == nullptr if we're not relaying transactions with this peer
583  std::unique_ptr<TxRelay> m_tx_relay;
584 
590  std::atomic<int64_t> nLastBlockTime{0};
591 
596  std::atomic<int64_t> nLastTXTime{0};
597 
599  std::atomic<std::chrono::microseconds> m_last_ping_time{0us};
600 
603  std::atomic<std::chrono::microseconds> m_min_ping_time{std::chrono::microseconds::max()};
604 
605  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);
606  ~CNode();
607  CNode(const CNode&) = delete;
608  CNode& operator=(const CNode&) = delete;
609 
610  NodeId GetId() const {
611  return id;
612  }
613 
614  uint64_t GetLocalNonce() const {
615  return nLocalHostNonce;
616  }
617 
618  int GetRefCount() const
619  {
620  assert(nRefCount >= 0);
621  return nRefCount;
622  }
623 
633  bool ReceiveMsgBytes(Span<const uint8_t> msg_bytes, bool& complete);
634 
635  void SetCommonVersion(int greatest_common_version)
636  {
638  m_greatest_common_version = greatest_common_version;
639  }
640  int GetCommonVersion() const
641  {
643  }
644 
645  CService GetAddrLocal() const;
647  void SetAddrLocal(const CService& addrLocalIn);
648 
650  {
651  nRefCount++;
652  return this;
653  }
654 
655  void Release()
656  {
657  nRefCount--;
658  }
659 
660  void AddAddressKnown(const CAddress& _addr)
661  {
663  m_addr_known->insert(_addr.GetKey());
664  }
665 
671  bool IsAddrCompatible(const CAddress& addr) const
672  {
674  }
675 
676  void PushAddress(const CAddress& _addr, FastRandomContext &insecure_rand)
677  {
678  // Known checking here is only to save space from duplicates.
679  // SendMessages will filter it again for knowns that were added
680  // after addresses were pushed.
682  if (_addr.IsValid() && !m_addr_known->contains(_addr.GetKey()) && IsAddrCompatible(_addr)) {
683  if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
684  vAddrToSend[insecure_rand.randrange(vAddrToSend.size())] = _addr;
685  } else {
686  vAddrToSend.push_back(_addr);
687  }
688  }
689  }
690 
691  void AddKnownTx(const uint256& hash)
692  {
693  if (m_tx_relay != nullptr) {
694  LOCK(m_tx_relay->cs_tx_inventory);
695  m_tx_relay->filterInventoryKnown.insert(hash);
696  }
697  }
698 
699  void PushTxInventory(const uint256& hash)
700  {
701  if (m_tx_relay == nullptr) return;
702  LOCK(m_tx_relay->cs_tx_inventory);
703  if (!m_tx_relay->filterInventoryKnown.contains(hash)) {
704  m_tx_relay->setInventoryTxToSend.insert(hash);
705  }
706  }
707 
708  void CloseSocketDisconnect();
709 
710  void copyStats(CNodeStats &stats, const std::vector<bool> &m_asmap);
711 
713  {
714  return nLocalServices;
715  }
716 
717  std::string GetAddrName() const;
719  void MaybeSetAddrName(const std::string& addrNameIn);
720 
722 
724  void PongReceived(std::chrono::microseconds ping_time) {
725  m_last_ping_time = ping_time;
726  m_min_ping_time = std::min(m_min_ping_time.load(), ping_time);
727  }
728 
729 private:
730  const NodeId id;
731  const uint64_t nLocalHostNonce;
734 
751 
752  std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
753 
755  std::string addrName GUARDED_BY(cs_addrName);
756 
757  // Our address, as reported by the peer
758  CService addrLocal GUARDED_BY(cs_addrLocal);
760 
761  mapMsgCmdSize mapSendBytesPerMsgCmd GUARDED_BY(cs_vSend);
762  mapMsgCmdSize mapRecvBytesPerMsgCmd GUARDED_BY(cs_vRecv);
763 };
764 
769 {
770 public:
772  virtual void InitializeNode(CNode* pnode) = 0;
773 
775  virtual void FinalizeNode(const CNode& node) = 0;
776 
784  virtual bool ProcessMessages(CNode* pnode, std::atomic<bool>& interrupt) = 0;
785 
792  virtual bool SendMessages(CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(pnode->cs_sendProcessing) = 0;
793 
794 
795 protected:
800  ~NetEventsInterface() = default;
801 };
802 
803 class CConnman
804 {
805 public:
806 
807  struct Options
808  {
813  int nMaxAddnode = 0;
814  int nMaxFeeler = 0;
817  BanMan* m_banman = nullptr;
818  unsigned int nSendBufferMaxSize = 0;
819  unsigned int nReceiveFloodSize = 0;
820  uint64_t nMaxOutboundLimit = 0;
822  std::vector<std::string> vSeedNodes;
823  std::vector<NetWhitelistPermissions> vWhitelistedRange;
824  std::vector<NetWhitebindPermissions> vWhiteBinds;
825  std::vector<CService> vBinds;
826  std::vector<CService> onion_binds;
828  std::vector<std::string> m_specified_outgoing;
829  std::vector<std::string> m_added_nodes;
830  std::vector<bool> m_asmap;
832  };
833 
834  void Init(const Options& connOptions) {
835  nLocalServices = connOptions.nLocalServices;
836  nMaxConnections = connOptions.nMaxConnections;
837  m_max_outbound_full_relay = std::min(connOptions.m_max_outbound_full_relay, connOptions.nMaxConnections);
840  nMaxAddnode = connOptions.nMaxAddnode;
841  nMaxFeeler = connOptions.nMaxFeeler;
843  clientInterface = connOptions.uiInterface;
844  m_banman = connOptions.m_banman;
845  m_msgproc = connOptions.m_msgproc;
847  nReceiveFloodSize = connOptions.nReceiveFloodSize;
849  {
851  nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
852  }
853  vWhitelistedRange = connOptions.vWhitelistedRange;
854  {
856  vAddedNodes = connOptions.m_added_nodes;
857  }
858  m_onion_binds = connOptions.onion_binds;
859  }
860 
861  CConnman(uint64_t seed0, uint64_t seed1, CAddrMan& addrman, bool network_active = true);
862  ~CConnman();
863  bool Start(CScheduler& scheduler, const Options& options);
864 
865  void StopThreads();
866  void StopNodes();
867  void Stop()
868  {
869  StopThreads();
870  StopNodes();
871  };
872 
873  void Interrupt();
874  bool GetNetworkActive() const { return fNetworkActive; };
876  void SetNetworkActive(bool active);
877  void OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant* grantOutbound, const char* strDest, ConnectionType conn_type);
878  bool CheckIncomingNonce(uint64_t nonce);
879 
880  bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
881 
882  void PushMessage(CNode* pnode, CSerializedNetMsg&& msg);
883 
884  using NodeFn = std::function<void(CNode*)>;
885  void ForEachNode(const NodeFn& func)
886  {
887  LOCK(cs_vNodes);
888  for (auto&& node : vNodes) {
890  func(node);
891  }
892  };
893 
894  void ForEachNode(const NodeFn& func) const
895  {
896  LOCK(cs_vNodes);
897  for (auto&& node : vNodes) {
899  func(node);
900  }
901  };
902 
903  template<typename Callable, typename CallableAfter>
904  void ForEachNodeThen(Callable&& pre, CallableAfter&& post)
905  {
906  LOCK(cs_vNodes);
907  for (auto&& node : vNodes) {
909  pre(node);
910  }
911  post();
912  };
913 
914  template<typename Callable, typename CallableAfter>
915  void ForEachNodeThen(Callable&& pre, CallableAfter&& post) const
916  {
917  LOCK(cs_vNodes);
918  for (auto&& node : vNodes) {
920  pre(node);
921  }
922  post();
923  };
924 
925  // Addrman functions
926  std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct);
933  std::vector<CAddress> GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct);
934 
935  // This allows temporarily exceeding m_max_outbound_full_relay, with the goal of finding
936  // a peer that is better than all our current peers.
937  void SetTryNewOutboundPeer(bool flag);
938  bool GetTryNewOutboundPeer();
939 
941  LogPrint(BCLog::NET, "net: enabling extra block-relay-only peers\n");
943  }
944 
945  // Return the number of outbound peers we have in excess of our target (eg,
946  // if we previously called SetTryNewOutboundPeer(true), and have since set
947  // to false, we may have extra peers that we wish to disconnect). This may
948  // return a value less than (num_outbound_connections - num_outbound_slots)
949  // in cases where some outbound connections are not yet fully connected, or
950  // not yet fully disconnected.
952  // Count the number of block-relay-only peers we have over our limit.
954 
955  bool AddNode(const std::string& node);
956  bool RemoveAddedNode(const std::string& node);
957  std::vector<AddedNodeInfo> GetAddedNodeInfo();
958 
970  bool AddConnection(const std::string& address, ConnectionType conn_type);
971 
973  void GetNodeStats(std::vector<CNodeStats>& vstats);
974  bool DisconnectNode(const std::string& node);
975  bool DisconnectNode(const CSubNet& subnet);
976  bool DisconnectNode(const CNetAddr& addr);
977  bool DisconnectNode(NodeId id);
978 
986 
987  uint64_t GetMaxOutboundTarget();
988  std::chrono::seconds GetMaxOutboundTimeframe();
989 
993  bool OutboundTargetReached(bool historicalBlockServingLimit);
994 
997  uint64_t GetOutboundTargetBytesLeft();
998 
1001  std::chrono::seconds GetMaxOutboundTimeLeftInCycle();
1002 
1003  uint64_t GetTotalBytesRecv();
1004  uint64_t GetTotalBytesSent();
1005 
1007  CSipHasher GetDeterministicRandomizer(uint64_t id) const;
1008 
1009  unsigned int GetReceiveFloodSize() const;
1010 
1011  void WakeMessageHandler();
1012 
1017  std::chrono::microseconds PoissonNextSendInbound(std::chrono::microseconds now, std::chrono::seconds average_interval);
1018 
1019  void SetAsmap(std::vector<bool> asmap) { addrman.m_asmap = std::move(asmap); }
1020 
1022  bool ShouldRunInactivityChecks(const CNode& node, std::optional<int64_t> now=std::nullopt) const;
1023 
1024 private:
1025  struct ListenSocket {
1026  public:
1029  ListenSocket(SOCKET socket_, NetPermissionFlags permissions_) : socket(socket_), m_permissions(permissions_) {}
1030  private:
1032  };
1033 
1034  bool BindListenPort(const CService& bindAddr, bilingual_str& strError, NetPermissionFlags permissions);
1035  bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions);
1036  bool InitBinds(
1037  const std::vector<CService>& binds,
1038  const std::vector<NetWhitebindPermissions>& whiteBinds,
1039  const std::vector<CService>& onion_binds);
1040 
1042  void AddAddrFetch(const std::string& strDest);
1043  void ProcessAddrFetch();
1044  void ThreadOpenConnections(std::vector<std::string> connect);
1045  void ThreadMessageHandler();
1046  void ThreadI2PAcceptIncoming();
1047  void AcceptConnection(const ListenSocket& hListenSocket);
1048 
1057  void CreateNodeFromAcceptedSocket(SOCKET hSocket,
1058  NetPermissionFlags permissionFlags,
1059  const CAddress& addr_bind,
1060  const CAddress& addr);
1061 
1062  void DisconnectNodes();
1065  bool InactivityCheck(const CNode& node) const;
1066  bool GenerateSelectSet(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set);
1067  void SocketEvents(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set);
1068  void SocketHandler();
1069  void ThreadSocketHandler();
1070  void ThreadDNSAddressSeed();
1071 
1072  uint64_t CalculateKeyedNetGroup(const CAddress& ad) const;
1073 
1074  CNode* FindNode(const CNetAddr& ip);
1075  CNode* FindNode(const CSubNet& subNet);
1076  CNode* FindNode(const std::string& addrName);
1077  CNode* FindNode(const CService& addr);
1078 
1083  bool AlreadyConnectedToAddress(const CAddress& addr);
1084 
1085  bool AttemptToEvictConnection();
1086  CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type);
1088 
1089  void DeleteNode(CNode* pnode);
1090 
1091  NodeId GetNewNodeId();
1092 
1093  size_t SocketSendData(CNode& node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend);
1094  void DumpAddresses();
1095 
1096  // Network stats
1097  void RecordBytesRecv(uint64_t bytes);
1098  void RecordBytesSent(uint64_t bytes);
1099 
1103  std::vector<CAddress> GetCurrentBlockRelayOnlyConns() const;
1104 
1105  // Whether the node should be passed out in ForEach* callbacks
1106  static bool NodeFullyConnected(const CNode* pnode);
1107 
1108  // Network usage totals
1111  uint64_t nTotalBytesRecv GUARDED_BY(cs_totalBytesRecv) {0};
1112  uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent) {0};
1113 
1114  // outbound limit & stats
1115  uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent) {0};
1116  std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent) {0};
1117  uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent);
1118 
1119  // P2P timeout in seconds
1121 
1122  // Whitelisted ranges. Any node connecting from these is automatically
1123  // whitelisted (as well as those connecting to whitelisted binds).
1124  std::vector<NetWhitelistPermissions> vWhitelistedRange;
1125 
1126  unsigned int nSendBufferMaxSize{0};
1127  unsigned int nReceiveFloodSize{0};
1128 
1129  std::vector<ListenSocket> vhListenSocket;
1130  std::atomic<bool> fNetworkActive{true};
1133  std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
1135  std::vector<std::string> vAddedNodes GUARDED_BY(cs_vAddedNodes);
1137  std::vector<CNode*> vNodes GUARDED_BY(cs_vNodes);
1138  std::list<CNode*> vNodesDisconnected;
1140  std::atomic<NodeId> nLastNodeId{0};
1141  unsigned int nPrevNodeCount{0};
1142 
1150  std::vector<CAddress> m_addrs_response_cache;
1151  std::chrono::microseconds m_cache_entry_expiration{0};
1152  };
1153 
1168  std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
1169 
1183 
1184  std::unique_ptr<CSemaphore> semOutbound;
1185  std::unique_ptr<CSemaphore> semAddnode;
1187 
1188  // How many full-relay (tx, block, addr) outbound peers we want
1190 
1191  // How many block-relay only outbound peers we want
1192  // We do not relay tx or addr messages with these peers
1194 
1203 
1208  std::vector<CAddress> m_anchors;
1209 
1211  const uint64_t nSeed0, nSeed1;
1212 
1214  bool fMsgProcWake GUARDED_BY(mutexMsgProc);
1215 
1216  std::condition_variable condMsgProc;
1218  std::atomic<bool> flagInterruptMsgProc{false};
1219 
1227 
1232  std::unique_ptr<i2p::sam::Session> m_i2p_sam_session;
1233 
1235  std::thread threadSocketHandler;
1240 
1245 
1250  std::atomic_bool m_start_extra_block_relay_peers{false};
1251 
1252  std::atomic<std::chrono::microseconds> m_next_send_inv_to_incoming{0us};
1253 
1258  std::vector<CService> m_onion_binds;
1259 
1260  friend struct CConnmanTest;
1261  friend struct ConnmanTestMsg;
1262 };
1263 
1265 std::chrono::microseconds PoissonNextSend(std::chrono::microseconds now, std::chrono::seconds average_interval);
1266 
1268 void CaptureMessage(const CAddress& addr, const std::string& msg_type, const Span<const unsigned char>& data, bool is_incoming);
1269 
1271 {
1274  std::chrono::microseconds m_min_ping_time;
1276  int64_t nLastTXTime;
1280  uint64_t nKeyedNetGroup;
1284 };
1285 
1293 [[nodiscard]] std::optional<NodeId> SelectNodeToEvict(std::vector<NodeEvictionCandidate>&& vEvictionCandidates);
1294 
1316 void ProtectEvictionCandidatesByRatio(std::vector<NodeEvictionCandidate>& vEvictionCandidates);
1317 
1318 #endif // BITCOIN_NET_H
V1TransportSerializer
Definition: net.h:390
CNodeStats::addrName
std::string addrName
Definition: net.h:253
CConnman::SetTryNewOutboundPeer
void SetTryNewOutboundPeer(bool flag)
Definition: net.cpp:1740
NodeId
int64_t NodeId
Definition: net.h:90
CConnman::cs_totalBytesRecv
RecursiveMutex cs_totalBytesRecv
Definition: net.h:1109
CNode::ConnmanTestMsg
friend struct ConnmanTestMsg
Definition: net.h:399
CConnman::DisconnectNode
bool DisconnectNode(const std::string &node)
Definition: net.cpp:2776
CService
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:551
threadinterrupt.h
CNodeStats::m_last_ping_time
std::chrono::microseconds m_last_ping_time
Definition: net.h:265
CNode::IsOutboundOrBlockRelayConn
bool IsOutboundOrBlockRelayConn() const
Definition: net.h:468
CConnman::m_max_outbound
int m_max_outbound
Definition: net.h:1197
CConnman::m_anchors
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
Definition: net.h:1208
feerate.h
CConnman::ConnectNode
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type)
Definition: net.cpp:379
CScheduler
Simple class for background tasks that should be run periodically or once "after a while".
Definition: scheduler.h:33
CConnman::Options::vSeedNodes
std::vector< std::string > vSeedNodes
Definition: net.h:822
CConnman::vhListenSocket
std::vector< ListenSocket > vhListenSocket
Definition: net.h:1129
V1TransportDeserializer::Complete
bool Complete() const override
Definition: net.h:357
CNodeStats::fInbound
bool fInbound
Definition: net.h:256
TransportDeserializer::GetMessage
virtual std::optional< CNetMessage > GetMessage(std::chrono::microseconds time, uint32_t &out_err)=0
CNode::GUARDED_BY
size_t nSendSize GUARDED_BY(cs_vSend)
Total size of all vSendMsg entries.
Definition: net.h:409
CConnman::ThreadMessageHandler
void ThreadMessageHandler()
Definition: net.cpp:2181
CNode::IsFeelerConn
bool IsFeelerConn() const
Definition: net.h:495
CConnman::GetNodeCount
size_t GetNodeCount(ConnectionDirection)
Definition: net.cpp:2749
CNode::GetRefCount
int GetRefCount() const
Definition: net.h:618
TransportDeserializer
The TransportDeserializer takes care of holding and deserializing the network receive buffer.
Definition: net.h:305
NetEventsInterface
Interface for message handling.
Definition: net.h:768
CConnman::GUARDED_BY
uint64_t nTotalBytesRecv GUARDED_BY(cs_totalBytesRecv)
Definition: net.h:1111
CConnman::Options::nMaxAddnode
int nMaxAddnode
Definition: net.h:813
NodeEvictionCandidate::m_min_ping_time
std::chrono::microseconds m_min_ping_time
Definition: net.h:1274
check.h
CNodeStats::m_network
Network m_network
Definition: net.h:275
CConnman::nSendBufferMaxSize
unsigned int nSendBufferMaxSize
Definition: net.h:1126
CConnman::GetOutboundTargetBytesLeft
uint64_t GetOutboundTargetBytesLeft()
response the bytes left in the current max outbound cycle in case of no limit, it will always respons...
Definition: net.cpp:2887
CConnman::AttemptToEvictConnection
bool AttemptToEvictConnection()
Try to find a connection to evict when the node is full.
Definition: net.cpp:1000
CNode::fSentAddr
bool fSentAddr
Definition: net.h:460
CNode::nLastSend
std::atomic< int64_t > nLastSend
Definition: net.h:426
CNode::cs_vSend
Mutex cs_vSend
Definition: net.h:414
CNodeStats::addrLocal
std::string addrLocal
Definition: net.h:269
CConnman::Interrupt
void Interrupt()
Definition: net.cpp:2581
CClientUIInterface
Signals for UI communication.
Definition: ui_interface.h:24
CNode::GetId
NodeId GetId() const
Definition: net.h:610
CConnman::condMsgProc
std::condition_variable condMsgProc
Definition: net.h:1216
CConnman::nReceiveFloodSize
unsigned int nReceiveFloodSize
Definition: net.h:1127
CNode::GUARDED_BY
size_t nSendOffset GUARDED_BY(cs_vSend)
Offset inside the first vSendMsg already sent.
Definition: net.h:411
NodeEvictionCandidate::fBloomFilter
bool fBloomFilter
Definition: net.h:1279
CNodeStats::nodeid
NodeId nodeid
Definition: net.h:244
CMessageHeader::nMessageSize
uint32_t nMessageSize
Definition: protocol.h:54
CNode::PongReceived
void PongReceived(std::chrono::microseconds ping_time)
A ping-pong round trip has completed successfully.
Definition: net.h:724
flags
int flags
Definition: bitcoin-tx.cpp:512
CConnman::ThreadDNSAddressSeed
void ThreadDNSAddressSeed()
Definition: net.cpp:1597
CNodeStats::nVersion
int nVersion
Definition: net.h:254
streams.h
CHash256::Reset
CHash256 & Reset()
Definition: hash.h:42
CConnman::Options::vBinds
std::vector< CService > vBinds
Definition: net.h:825
CSerializedNetMsg::data
std::vector< unsigned char > data
Definition: net.h:112
CNode::copyStats
void copyStats(CNodeStats &stats, const std::vector< bool > &m_asmap)
Definition: net.cpp:565
CConnman::CreateNodeFromAcceptedSocket
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:1070
CNode::nRefCount
std::atomic< int > nRefCount
Definition: net.h:462
PF_NONE
@ PF_NONE
Definition: net_permissions.h:18
CNode::m_wants_addrv2
std::atomic_bool m_wants_addrv2
Whether the peer has signaled support for receiving ADDRv2 (BIP155) messages, implying a preference t...
Definition: net.h:454
CConnman::StartExtraBlockRelayPeers
void StartExtraBlockRelayPeers()
Definition: net.h:940
CConnman::RecordBytesRecv
void RecordBytesRecv(uint64_t bytes)
Definition: net.cpp:2819
CNode::Release
void Release()
Definition: net.h:655
CConnman::WakeMessageHandler
void WakeMessageHandler()
Definition: net.cpp:1588
CNode::m_bip152_highbandwidth_from
std::atomic< bool > m_bip152_highbandwidth_from
Definition: net.h:546
CConnman::Bind
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
Definition: net.cpp:2410
CConnman::Options::m_i2p_accept_incoming
bool m_i2p_accept_incoming
Definition: net.h:831
CNode::nProcessQueueSize
size_t nProcessQueueSize
Definition: net.h:420
sync.h
CConnman::SocketEvents
void SocketEvents(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set)
Definition: net.cpp:1385
CConnman::m_max_outbound_full_relay
int m_max_outbound_full_relay
Definition: net.h:1189
Discover
void Discover()
Definition: net.cpp:2330
CConnman::Options::nMaxOutboundLimit
uint64_t nMaxOutboundLimit
Definition: net.h:820
CNode::nLocalServices
const ServiceFlags nLocalServices
Services offered to this peer.
Definition: net.h:750
CNode::nLastRecv
std::atomic< int64_t > nLastRecv
Definition: net.h:427
CConnman::OutboundTargetReached
bool OutboundTargetReached(bool historicalBlockServingLimit)
check if the outbound target is reached if param historicalBlockServingLimit is set true,...
Definition: net.cpp:2867
CConnman::m_onion_binds
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:1258
CNodeStats::mapRecvBytesPerMsgCmd
mapMsgCmdSize mapRecvBytesPerMsgCmd
Definition: net.h:263
CNode::m_limited_node
bool m_limited_node
Definition: net.h:449
bilingual_str
Bilingual messages:
Definition: translation.h:16
CNetAddr
Network address.
Definition: netaddress.h:119
CConnman::GetAddresses
std::vector< CAddress > GetAddresses(size_t max_addresses, size_t max_pct)
Definition: net.cpp:2674
CConnman::ProcessAddrFetch
void ProcessAddrFetch()
Definition: net.cpp:1718
uint256.h
NodeEvictionCandidate::fRelayTxes
bool fRelayTxes
Definition: net.h:1278
DEFAULT_MAX_PEER_CONNECTIONS
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:74
AddLocal
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
Definition: net.cpp:227
ConnectionType::OUTBOUND_FULL_RELAY
@ OUTBOUND_FULL_RELAY
These are the default connections that we use to connect with the network.
CNode
Information about a peer.
Definition: net.h:396
CNode::GUARDED_BY
SOCKET hSocket GUARDED_BY(cs_hSocket)
CConnman::GetMaxOutboundTarget
uint64_t GetMaxOutboundTarget()
Definition: net.cpp:2842
CConnman::GetTotalBytesRecv
uint64_t GetTotalBytesRecv()
Definition: net.cpp:2896
DEFAULT_MAXRECEIVEBUFFER
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:87
ProtectEvictionCandidatesByRatio
void ProtectEvictionCandidatesByRatio(std::vector< NodeEvictionCandidate > &vEvictionCandidates)
Protect desirable or disadvantaged inbound peers from eviction by ratio.
Definition: net.cpp:895
CConnman::Options::nLocalServices
ServiceFlags nLocalServices
Definition: net.h:809
CConnman::GetMaxOutboundTimeLeftInCycle
std::chrono::seconds GetMaxOutboundTimeLeftInCycle()
returns the time left in the current max outbound cycle in case of no limit, it will always return 0
Definition: net.cpp:2853
CConnman::cs_vAddedNodes
RecursiveMutex cs_vAddedNodes
Definition: net.h:1136
CChainParams
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:64
base_blob::SetNull
void SetNull()
Definition: uint256.h:39
CConnman::AddConnection
bool AddConnection(const std::string &address, ConnectionType conn_type)
Attempts to open a connection.
Definition: net.cpp:1165
CNode::m_serializer
std::unique_ptr< TransportSerializer > m_serializer
Definition: net.h:403
CNetMessage::m_command
std::string m_command
Definition: net.h:291
CConnman::AcceptConnection
void AcceptConnection(const ListenSocket &hListenSocket)
Definition: net.cpp:1044
CConnman::GetAddedNodeInfo
std::vector< AddedNodeInfo > GetAddedNodeInfo()
Definition: net.cpp:2064
CNode::GetAddrName
std::string GetAddrName() const
Definition: net.cpp:532
CConnman::Options::m_added_nodes
std::vector< std::string > m_added_nodes
Definition: net.h:829
CConnman::GetLocalServices
ServiceFlags GetLocalServices() const
Used to convey which local services we are offering peers during node connection.
Definition: net.cpp:2908
CConnman::m_addr_fetches_mutex
RecursiveMutex m_addr_fetches_mutex
Definition: net.h:1134
AnnotatedMixin< std::recursive_mutex >
CConnman::cs_totalBytesSent
RecursiveMutex cs_totalBytesSent
Definition: net.h:1110
CSerializedNetMsg::m_type
std::string m_type
Definition: net.h:113
CConnman::CConnman
CConnman(uint64_t seed0, uint64_t seed1, CAddrMan &addrman, bool network_active=true)
Definition: net.cpp:2394
CNodeStats::mapSendBytesPerMsgCmd
mapMsgCmdSize mapSendBytesPerMsgCmd
Definition: net.h:261
CNode::PushTxInventory
void PushTxInventory(const uint256 &hash)
Definition: net.h:699
ServiceFlags
ServiceFlags
nServices flags
Definition: protocol.h:269
DEFAULT_FIXEDSEEDS
static const bool DEFAULT_FIXEDSEEDS
Definition: net.h:86
CConnman::CachedAddrResponse::m_addrs_response_cache
std::vector< CAddress > m_addrs_response_cache
Definition: net.h:1150
CNode::ExpectServicesFromConn
bool ExpectServicesFromConn() const
Definition: net.h:516
MAX_ADDR_TO_SEND
static constexpr size_t MAX_ADDR_TO_SEND
The maximum number of addresses from our addrman to return in response to a getaddr message.
Definition: net.h:58
PoissonNextSend
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:3017
V1TransportDeserializer::vRecv
CDataStream vRecv
Definition: net.h:328
CConnman::ListenSocket::socket
SOCKET socket
Definition: net.h:1027
CNode::m_permissionFlags
NetPermissionFlags m_permissionFlags
Definition: net.h:405
CNode::GUARDED_BY
std::chrono::microseconds m_next_addr_send GUARDED_BY(m_addr_send_times_mutex)
Definition: net.h:553
CNodeStats::nLastBlockTime
int64_t nLastBlockTime
Definition: net.h:250
CNode::nTimeOffset
std::atomic< int64_t > nTimeOffset
Definition: net.h:430
CNode::nServices
std::atomic< ServiceFlags > nServices
Definition: net.h:406
CNodeStats::nLastRecv
int64_t nLastRecv
Definition: net.h:248
chainparams.h
CConnman::PoissonNextSendInbound
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:3006
CNode::TxRelay::cs_filter
RecursiveMutex cs_filter
Definition: net.h:557
CConnman::Start
bool Start(CScheduler &scheduler, const Options &options)
Definition: net.cpp:2455
CConnman::CalculateKeyedNetGroup
uint64_t CalculateKeyedNetGroup(const CAddress &ad) const
Definition: net.cpp:3028
CNodeStats::addrBind
CAddress addrBind
Definition: net.h:273
V1TransportDeserializer::readData
int readData(Span< const uint8_t > msg_bytes)
Definition: net.cpp:706
Network
Network
A network type.
Definition: netaddress.h:43
CNodeStats::addr
CAddress addr
Definition: net.h:271
CConnman::StopThreads
void StopThreads()
Definition: net.cpp:2605
CConnman::NotifyNumConnectionsChanged
void NotifyNumConnectionsChanged()
Definition: net.cpp:1245
LOCAL_MAX
@ LOCAL_MAX
Definition: net.h:198
CNode::fDisconnect
std::atomic_bool fDisconnect
Definition: net.h:459
V1TransportDeserializer::data_hash
uint256 data_hash
Definition: net.h:324
CSipHasher
SipHash-2-4.
Definition: siphash.h:13
CConnman::nPrevNodeCount
unsigned int nPrevNodeCount
Definition: net.h:1141
AddedNodeInfo::fConnected
bool fConnected
Definition: net.h:96
ConnectionType::MANUAL
@ MANUAL
We open manual connections to addresses that users explicitly requested via the addnode RPC or the -a...
CNodeStats::m_min_ping_time
std::chrono::microseconds m_min_ping_time
Definition: net.h:266
CConnman::AddAddrFetch
void AddAddrFetch(const std::string &strDest)
Definition: net.cpp:112
CConnman::InactivityCheck
bool InactivityCheck(const CNode &node) const
Return true if the peer is inactive and should be disconnected.
Definition: net.cpp:1265
CNode::TxRelay::cs_tx_inventory
RecursiveMutex cs_tx_inventory
Definition: net.h:563
CConnman::GUARDED_BY
uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1115
CNode::addr
const CAddress addr
Definition: net.h:432
CConnman::OpenNetworkConnection
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *strDest, ConnectionType conn_type)
Definition: net.cpp:2146
NodeEvictionCandidate::nKeyedNetGroup
uint64_t nKeyedNetGroup
Definition: net.h:1280
NetPermissions::HasFlag
static bool HasFlag(const NetPermissionFlags &flags, NetPermissionFlags f)
Definition: net_permissions.h:46
CNode::SetCommonVersion
void SetCommonVersion(int greatest_common_version)
Definition: net.h:635
CNode::GetLocalServices
ServiceFlags GetLocalServices() const
Definition: net.h:712
CNodeStats::m_starting_height
int m_starting_height
Definition: net.h:259
bloom.h
Span
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:92
CNode::m_addr_send_times_mutex
Mutex m_addr_send_times_mutex
Definition: net.h:552
CNode::nTimeConnected
const int64_t nTimeConnected
Unix epoch time at peer connection, in seconds.
Definition: net.h:429
Assume
#define Assume(val)
Assume is the identity function.
Definition: check.h:72
CConnman::FindNode
CNode * FindNode(const CNetAddr &ip)
Definition: net.cpp:304
NetEventsInterface::InitializeNode
virtual void InitializeNode(CNode *pnode)=0
Initialize a peer (setup state, queue any initial messages)
ConnectionType::INBOUND
@ INBOUND
Inbound connections are those initiated by a peer.
addrdb.h
V1TransportDeserializer::hdr
CMessageHeader hdr
Definition: net.h:327
CConnman::m_addr_response_caches
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:1168
siphash.h
CSemaphoreGrant
RAII-style semaphore lock.
Definition: sync.h:315
protocol.h
MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
Definition: net.h:64
CNodeStats::nTimeConnected
int64_t nTimeConnected
Definition: net.h:251
random.h
CConnman::nMaxFeeler
int nMaxFeeler
Definition: net.h:1196
CNode::m_deserializer
std::unique_ptr< TransportDeserializer > m_deserializer
Definition: net.h:402
LOCAL_MAPPED
@ LOCAL_MAPPED
Definition: net.h:195
CConnman::mutexMsgProc
Mutex mutexMsgProc
Definition: net.h:1217
CConnman::ForEachNodeThen
void ForEachNodeThen(Callable &&pre, CallableAfter &&post)
Definition: net.h:904
CNodeStats::m_mapped_as
uint32_t m_mapped_as
Definition: net.h:276
SeenLocal
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:285
TransportSerializer::~TransportSerializer
virtual ~TransportSerializer()
Definition: net.h:387
CConnman::nLocalServices
ServiceFlags nLocalServices
Services this instance offers.
Definition: net.h:1182
CConnman::ThreadSocketHandler
void ThreadSocketHandler()
Definition: net.cpp:1578
CConnman::ThreadOpenAddedConnections
void ThreadOpenAddedConnections()
Definition: net.cpp:2118
CNode::AddKnownTx
void AddKnownTx(const uint256 &hash)
Definition: net.h:691
V1TransportDeserializer::in_data
bool in_data
Definition: net.h:325
DEFAULT_MAXSENDBUFFER
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:88
NodeEvictionCandidate
Definition: net.h:1270
LOCAL_MANUAL
@ LOCAL_MANUAL
Definition: net.h:196
CNode::ConnectedThroughNetwork
Network ConnectedThroughNetwork() const
Get network the peer connected through.
Definition: net.cpp:558
CNode::TxRelay::m_last_mempool_req
std::atomic< std::chrono::seconds > m_last_mempool_req
Definition: net.h:573
CNodeStats::m_permissionFlags
NetPermissionFlags m_permissionFlags
Definition: net.h:264
CNode::cs_vRecv
Mutex cs_vRecv
Definition: net.h:416
CConnman::DumpAddresses
void DumpAddresses()
Definition: net.cpp:1707
CNode::TxRelay
Definition: net.h:556
CNode::AddAddressKnown
void AddAddressKnown(const CAddress &_addr)
Definition: net.h:660
CConnman::vWhitelistedRange
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:1124
CConnman::m_start_extra_block_relay_peers
std::atomic_bool m_start_extra_block_relay_peers
flag for initiating extra block-relay-only peer connections.
Definition: net.h:1250
CConnman::Options::vWhitelistedRange
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:823
AddedNodeInfo::strAddedNode
std::string strAddedNode
Definition: net.h:94
CNode::GetCommonVersion
int GetCommonVersion() const
Definition: net.h:640
NodeEvictionCandidate::id
NodeId id
Definition: net.h:1272
CNode::AddRef
CNode * AddRef()
Definition: net.h:649
CConnman::SocketSendData
size_t SocketSendData(CNode &node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend)
Definition: net.cpp:781
CConnman::ForEachNodeThen
void ForEachNodeThen(Callable &&pre, CallableAfter &&post) const
Definition: net.h:915
CConnman::SetAsmap
void SetAsmap(std::vector< bool > asmap)
Definition: net.h:1019
CConnman::m_banman
BanMan * m_banman
Pointer to this node's banman.
Definition: net.h:1202
compat.h
CConnman::GetMaxOutboundTimeframe
std::chrono::seconds GetMaxOutboundTimeframe()
Definition: net.cpp:2848
CConnman::AlreadyConnectedToAddress
bool AlreadyConnectedToAddress(const CAddress &addr)
Determine whether we're already connected to a given address, in order to avoid initiating duplicate ...
Definition: net.cpp:348
NetEventsInterface::SendMessages
virtual bool SendMessages(CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(pnode -> cs_sendProcessing)=0
Send queued protocol messages to a given node.
CNode::TxRelay::m_next_send_feefilter
std::chrono::microseconds m_next_send_feefilter
Definition: net.h:579
CNode::fGetAddr
bool fGetAddr
Definition: net.h:551
CNodeStats::fRelayTxes
bool fRelayTxes
Definition: net.h:246
CConnman::threadOpenConnections
std::thread threadOpenConnections
Definition: net.h:1237
CNode::m_tx_relay
std::unique_ptr< TxRelay > m_tx_relay
Definition: net.h:583
MAX_PROTOCOL_MESSAGE_LENGTH
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:60
span.h
netaddress.h
CNode::m_conn_type
const ConnectionType m_conn_type
Definition: net.h:732
SelectNodeToEvict
std::optional< NodeId > SelectNodeToEvict(std::vector< NodeEvictionCandidate > &&vEvictionCandidates)
Select an inbound peer to evict after filtering out (protecting) peers having distinct,...
Definition: net.cpp:931
CConnman::ForNode
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:2993
CNode::TxRelay::lastSentFeeFilter
CAmount lastSentFeeFilter
Definition: net.h:578
SetReachable
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:265
CNetMessage::m_time
std::chrono::microseconds m_time
time of message receipt
Definition: net.h:288
AddedNodeInfo::fInbound
bool fInbound
Definition: net.h:97
CSerializedNetMsg
Definition: net.h:103
CNode::GUARDED_BY
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Definition: net.h:424
CNode::fSuccessfullyConnected
std::atomic_bool fSuccessfullyConnected
fSuccessfullyConnected is set to true on receiving VERACK from the peer.
Definition: net.h:456
NetPermissionFlags
NetPermissionFlags
Definition: net_permissions.h:17
CConnman::Options::onion_binds
std::vector< CService > onion_binds
Definition: net.h:826
CConnman::CachedAddrResponse
Cache responses to addr requests to minimize privacy leak.
Definition: net.h:1149
CConnman::GetNewNodeId
NodeId GetNewNodeId()
Definition: net.cpp:2404
GetListenPort
uint16_t GetListenPort()
Definition: net.cpp:118
CConnman::fAddressesInitialized
bool fAddressesInitialized
Definition: net.h:1131
CConnman::ListenSocket
Definition: net.h:1025
V1TransportDeserializer::V1TransportDeserializer
V1TransportDeserializer(const CChainParams &chain_params, const NodeId node_id, int nTypeIn, int nVersionIn)
Definition: net.h:348
AddedNodeInfo
Definition: net.h:92
CConnman::Options::m_peer_connect_timeout
int64_t m_peer_connect_timeout
Definition: net.h:821
CAmount
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
CConnman::addrman
CAddrMan & addrman
Definition: net.h:1132
CNode::TxRelay::setInventoryTxToSend
std::set< uint256 > setInventoryTxToSend
Definition: net.h:566
CNodeStats::minFeeFilter
CAmount minFeeFilter
Definition: net.h:267
CNode::m_bip152_highbandwidth_to
std::atomic< bool > m_bip152_highbandwidth_to
Definition: net.h:544
TransportDeserializer::~TransportDeserializer
virtual ~TransportDeserializer()
Definition: net.h:315
CConnman::Options::m_use_addrman_outgoing
bool m_use_addrman_outgoing
Definition: net.h:827
TransportDeserializer::Read
virtual int Read(Span< const uint8_t > &msg_bytes)=0
read and deserialize data, advances msg_bytes data pointer
CNetAddr::IsValid
bool IsValid() const
Definition: netaddress.cpp:469
CConnman::Options::m_max_outbound_block_relay
int m_max_outbound_block_relay
Definition: net.h:812
CSubNet
Definition: netaddress.h:480
CConnman::ListenSocket::AddSocketPermissionFlags
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition: net.h:1028
V1TransportDeserializer::hasher
CHash256 hasher
Definition: net.h:323
CNode::IsAddrFetchConn
bool IsAddrFetchConn() const
Definition: net.h:499
CConnman::m_peer_connect_timeout
int64_t m_peer_connect_timeout
Definition: net.h:1120
CNode::cs_vProcessMsg
RecursiveMutex cs_vProcessMsg
Definition: net.h:418
CNode::cs_hSocket
Mutex cs_hSocket
Definition: net.h:415
CNodeStats::cleanSubVer
std::string cleanSubVer
Definition: net.h:255
CConnman::vNodesDisconnected
std::list< CNode * > vNodesDisconnected
Definition: net.h:1138
CConnman::threadMessageHandler
std::thread threadMessageHandler
Definition: net.h:1238
CConnman::ConnmanTestMsg
friend struct ConnmanTestMsg
Definition: net.h:1261
TransportSerializer::prepareForTransport
virtual void prepareForTransport(CSerializedNetMsg &msg, std::vector< unsigned char > &header)=0
uint256
256-bit opaque blob.
Definition: uint256.h:124
CNode::cs_SubVer
RecursiveMutex cs_SubVer
Definition: net.h:438
MAX_FEELER_CONNECTIONS
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition: net.h:70
CNode::m_addr_known
std::unique_ptr< CRollingBloomFilter > m_addr_known
Definition: net.h:550
CNetMessage::m_recv
CDataStream m_recv
received message data
Definition: net.h:287
cs_mapLocalHost
RecursiveMutex cs_mapLocalHost
Definition: net.cpp:107
LogPrint
#define LogPrint(category,...)
Definition: logging.h:187
CConnman::Options::nReceiveFloodSize
unsigned int nReceiveFloodSize
Definition: net.h:819
CNode::IsBlockOnlyConn
bool IsBlockOnlyConn() const
Definition: net.h:491
CConnman::nSeed0
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition: net.h:1211
ConnectionType::FEELER
@ FEELER
Feeler connections are short-lived connections made to check that a node is alive.
CNodeStats::m_conn_type
ConnectionType m_conn_type
Definition: net.h:277
CConnman::~CConnman
~CConnman()
Definition: net.cpp:2668
CConnman::Options
Definition: net.h:807
CNode::GUARDED_BY
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Definition: net.h:412
CConnman::GetReceiveFloodSize
unsigned int GetReceiveFloodSize() const
Definition: net.cpp:2913
CNode::PushAddress
void PushAddress(const CAddress &_addr, FastRandomContext &insecure_rand)
Definition: net.h:676
CNode::grantOutbound
CSemaphoreGrant grantOutbound
Definition: net.h:461
CNode::GUARDED_BY
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:443
IsReachable
bool IsReachable(enum Network net)
Definition: net.cpp:273
CNode::TxRelay::minFeeFilter
std::atomic< CAmount > minFeeFilter
Minimum fee rate with which to filter inv's to this node.
Definition: net.h:577
NodeEvictionCandidate::m_is_local
bool m_is_local
Definition: net.h:1282
NetEventsInterface::ProcessMessages
virtual bool ProcessMessages(CNode *pnode, std::atomic< bool > &interrupt)=0
Process protocol messages received from a given node.
CConnman::Options::nMaxConnections
int nMaxConnections
Definition: net.h:810
DEFAULT_MAX_UPLOAD_TARGET
static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:76
CDataStream::SetVersion
void SetVersion(int n)
Definition: streams.h:362
NODE_NONE
@ NODE_NONE
Definition: protocol.h:272
CNodeStats::nLastSend
int64_t nLastSend
Definition: net.h:247
CSerializedNetMsg::CSerializedNetMsg
CSerializedNetMsg()=default
BanMan
Definition: banman.h:57
CNodeStats::nTimeOffset
int64_t nTimeOffset
Definition: net.h:252
CConnman::Options::nSendBufferMaxSize
unsigned int nSendBufferMaxSize
Definition: net.h:818
CConnman::ListenSocket::m_permissions
NetPermissionFlags m_permissions
Definition: net.h:1031
NodeEvictionCandidate::nTimeConnected
int64_t nTimeConnected
Definition: net.h:1273
CNode::GUARDED_BY
std::chrono::microseconds m_next_local_addr_send GUARDED_BY(m_addr_send_times_mutex)
Definition: net.h:554
CNode::nKeyedNetGroup
const uint64_t nKeyedNetGroup
Definition: net.h:464
DEFAULT_DNSSEED
static const bool DEFAULT_DNSSEED
Definition: net.h:85
CConnman::nLastNodeId
std::atomic< NodeId > nLastNodeId
Definition: net.h:1140
CNode::nLastTXTime
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:596
CConnman::RemoveAddedNode
bool RemoveAddedNode(const std::string &node)
Definition: net.cpp:2737
fListen
bool fListen
Definition: net.cpp:106
V1TransportDeserializer::hdrbuf
CDataStream hdrbuf
Definition: net.h:326
CNode::IsManualConn
bool IsManualConn() const
Definition: net.h:487
CConnman::Options::uiInterface
CClientUIInterface * uiInterface
Definition: net.h:815
AddedNodeInfo::resolvedAddress
CService resolvedAddress
Definition: net.h:95
fDiscover
bool fDiscover
Definition: net.cpp:105
CConnman::GUARDED_BY
uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1112
CConnman::GetCurrentBlockRelayOnlyConns
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const
Return vector of current BLOCK_RELAY peers.
Definition: net.cpp:2051
CConnman::nSeed1
const uint64_t nSeed1
Definition: net.h:1211
CConnman
Definition: net.h:803
CConnman::threadI2PAcceptIncoming
std::thread threadI2PAcceptIncoming
Definition: net.h:1239
CAddrMan
Stochastical (IP) address manager.
Definition: addrman.h:172
CAddrMan::m_asmap
std::vector< bool > m_asmap
Definition: addrman.h:315
V1TransportDeserializer::Reset
void Reset()
Definition: net.h:336
CNode::id
const NodeId id
Definition: net.h:730
CConnman::Options::nMaxFeeler
int nMaxFeeler
Definition: net.h:814
CConnman::StopNodes
void StopNodes()
Definition: net.cpp:2622
CConnman::m_try_another_outbound_peer
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:1244
CNode::cs_sendProcessing
RecursiveMutex cs_sendProcessing
Definition: net.h:422
NetEventsInterface::~NetEventsInterface
~NetEventsInterface()=default
Protected destructor so that instances can only be deleted by derived classes.
V1TransportDeserializer::GetMessageHash
const uint256 & GetMessageHash() const
Definition: net.cpp:723
LocalServiceInfo::nScore
int nScore
Definition: net.h:231
GetLocal
bool GetLocal(CService &addr, const CNetAddr *paddrPeer=nullptr)
Definition: net.cpp:124
CNodeStats::nSendBytes
uint64_t nSendBytes
Definition: net.h:260
CAddress
A CService with information about it as peer.
Definition: protocol.h:356
MAX_BLOCK_RELAY_ONLY_CONNECTIONS
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:68
CMessageHeader
Message header.
Definition: protocol.h:28
CNodeStats::m_bip152_highbandwidth_to
bool m_bip152_highbandwidth_to
Definition: net.h:257
CConnman::SetNetworkActive
void SetNetworkActive(bool active)
Definition: net.cpp:2381
CNode::nLocalHostNonce
const uint64_t nLocalHostNonce
Definition: net.h:731
CConnman::NodeFullyConnected
static bool NodeFullyConnected(const CNode *pnode)
Definition: net.cpp:2956
CNodeStats::nLastTXTime
int64_t nLastTXTime
Definition: net.h:249
DEFAULT_WHITELISTRELAY
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
Definition: net.h:47
LocalServiceInfo
Definition: net.h:230
ConnectionTypeAsString
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
Definition: net.cpp:512
CNode::cs_addrName
RecursiveMutex cs_addrName
Definition: net.h:754
NetPermissions::AddFlag
static void AddFlag(NetPermissionFlags &flags, NetPermissionFlags f)
Definition: net_permissions.h:50
CConnman::GetNodeStats
void GetNodeStats(std::vector< CNodeStats > &vstats)
Definition: net.cpp:2765
CNetMessage::m_message_size
uint32_t m_message_size
size of the payload
Definition: net.h:289
CConnman::Options::m_msgproc
NetEventsInterface * m_msgproc
Definition: net.h:816
CNode::m_inbound_onion
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e. connected via our Tor onion service.
Definition: net.h:436
CNetMessage::CNetMessage
CNetMessage(CDataStream &&recv_in)
Definition: net.h:293
MAX_ADDNODE_CONNECTIONS
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:66
CDataStream::clear
void clear()
Definition: streams.h:261
EXCLUSIVE_LOCKS_REQUIRED
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
CConnman::cs_vNodes
RecursiveMutex cs_vNodes
Definition: net.h:1139
LOCK
#define LOCK(cs)
Definition: sync.h:232
V1TransportDeserializer::SetVersion
void SetVersion(int nVersionIn) override
Definition: net.h:363
CNode::m_prefer_evict
bool m_prefer_evict
Definition: net.h:444
ConnectionType::ADDR_FETCH
@ ADDR_FETCH
AddrFetch connections are short lived connections used to solicit addresses from peers.
CNetMessage::SetVersion
void SetVersion(int nVersionIn)
Definition: net.h:295
i2p.h
NetEventsInterface::FinalizeNode
virtual void FinalizeNode(const CNode &node)=0
Handle removal of a peer (clear state)
V1TransportDeserializer::GetMessage
std::optional< CNetMessage > GetMessage(std::chrono::microseconds time, uint32_t &out_err_raw_size) override
Definition: net.cpp:731
CConnman::ForEachNode
void ForEachNode(const NodeFn &func)
Definition: net.h:885
CNode::CloseSocketDisconnect
void CloseSocketDisconnect()
Definition: net.cpp:495
CNode::ConnectionTypeAsString
std::string ConnectionTypeAsString() const
Definition: net.h:721
V1TransportDeserializer
Definition: net.h:318
TransportSerializer
The TransportSerializer prepares messages for the network transport.
Definition: net.h:383
CNode::TxRelay::PT_GUARDED_BY
std::unique_ptr< CBloomFilter > pfilter PT_GUARDED_BY(cs_filter) GUARDED_BY(cs_filter)
Definition: net.h:563
CNetMessage
Transport protocol agnostic message container.
Definition: net.h:285
LOCAL_IF
@ LOCAL_IF
Definition: net.h:193
NodeEvictionCandidate::prefer_evict
bool prefer_evict
Definition: net.h:1281
CNode::cs_addrLocal
RecursiveMutex cs_addrLocal
Definition: net.h:759
CConnman::SocketHandler
void SocketHandler()
Definition: net.cpp:1460
CNode::m_last_ping_time
std::atomic< std::chrono::microseconds > m_last_ping_time
Last measured round-trip time.
Definition: net.h:599
CNode::GetAddrLocal
CService GetAddrLocal() const
Definition: net.cpp:544
CConnman::DisconnectNodes
void DisconnectNodes()
Definition: net.cpp:1186
CDataStream::resize
void resize(size_type n, value_type c=0)
Definition: streams.h:257
mapMsgCmdSize
std::map< std::string, uint64_t > mapMsgCmdSize
Definition: net.h:239
FEELER_INTERVAL
static constexpr auto FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes.
Definition: net.h:54
NET_MESSAGE_COMMAND_OTHER
const std::string NET_MESSAGE_COMMAND_OTHER
Definition: net.cpp:97
CNode::GetLocalNonce
uint64_t GetLocalNonce() const
Definition: net.h:614
FastRandomContext::randrange
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
Definition: random.h:190
LocalServiceInfo::nPort
uint16_t nPort
Definition: net.h:232
CNode::nLastBlockTime
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:590
hash.h
CConnman::Options::m_specified_outgoing
std::vector< std::string > m_specified_outgoing
Definition: net.h:828
CConnman::Stop
void Stop()
Definition: net.h:867
DEFAULT_PEER_CONNECT_TIMEOUT
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition: net.h:80
CNode::HasPermission
bool HasPermission(NetPermissionFlags permission) const
Definition: net.h:445
node
Definition: interfaces.cpp:66
NUM_FDS_MESSAGE_CAPTURE
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
Definition: net.h:82
CConnman::AddNode
bool AddNode(const std::string &node)
Definition: net.cpp:2726
CNode::IsInboundConn
bool IsInboundConn() const
Definition: net.h:503
CNode::operator=
CNode & operator=(const CNode &)=delete
CNode::vRecvMsg
std::list< CNetMessage > vRecvMsg
Definition: net.h:752
CDataStream
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:204
CNode::RelayAddrsWithConn
bool RelayAddrsWithConn() const
Definition: net.h:508
CConnman::ListenSocket::ListenSocket
ListenSocket(SOCKET socket_, NetPermissionFlags permissions_)
Definition: net.h:1029
addrman.h
V1TransportDeserializer::Read
int Read(Span< const uint8_t > &msg_bytes) override
read and deserialize data, advances msg_bytes data pointer
Definition: net.h:368
V1TransportSerializer::prepareForTransport
void prepareForTransport(CSerializedNetMsg &msg, std::vector< unsigned char > &header) override
Definition: net.cpp:768
CConnman::threadOpenAddedConnections
std::thread threadOpenAddedConnections
Definition: net.h:1236
CConnman::GetNetworkActive
bool GetNetworkActive() const
Definition: net.h:874
CConnman::GetUseAddrmanOutgoing
bool GetUseAddrmanOutgoing() const
Definition: net.h:875
CConnman::CachedAddrResponse::m_cache_entry_expiration
std::chrono::microseconds m_cache_entry_expiration
Definition: net.h:1151
CNode::SetAddrLocal
void SetAddrLocal(const CService &addrLocalIn)
May not be called more than once.
Definition: net.cpp:549
CHash256
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
Definition: hash.h:24
V1TransportDeserializer::m_node_id
const NodeId m_node_id
Definition: net.h:322
CConnman::NodeFn
std::function< void(CNode *)> NodeFn
Definition: net.h:884
CNode::m_min_ping_time
std::atomic< std::chrono::microseconds > m_min_ping_time
Lowest measured round-trip time.
Definition: net.h:603
CConnman::Options::m_max_outbound_full_relay
int m_max_outbound_full_relay
Definition: net.h:811
ConnectionType::BLOCK_RELAY
@ BLOCK_RELAY
We use block-relay-only connections to help prevent against partition attacks.
netbase.h
CConnman::GUARDED_BY
std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1116
RemoveLocal
void RemoveLocal(const CService &addr)
Definition: net.cpp:258
LOCAL_NONE
@ LOCAL_NONE
Definition: net.h:192
CConnman::GetTryNewOutboundPeer
bool GetTryNewOutboundPeer()
Definition: net.cpp:1735
CNode::ReceiveMsgBytes
bool ReceiveMsgBytes(Span< const uint8_t > msg_bytes, bool &complete)
Receive bytes from the buffer and deserialize them into messages.
Definition: net.cpp:622
CNode::IsAddrCompatible
bool IsAddrCompatible(const CAddress &addr) const
Whether the peer supports the address.
Definition: net.h:671
CConnman::CConnmanTest
friend struct CConnmanTest
Definition: net.h:1260
CNodeStats::nRecvBytes
uint64_t nRecvBytes
Definition: net.h:262
CNetAddr::IsAddrV1Compatible
bool IsAddrV1Compatible() const
Check if the current object can be serialized in pre-ADDRv2/BIP155 format.
Definition: netaddress.cpp:523
CConnman::ThreadI2PAcceptIncoming
void ThreadI2PAcceptIncoming()
Definition: net.cpp:2230
ConnectionDirection
ConnectionDirection
Definition: netbase.h:32
DEFAULT_WHITELISTFORCERELAY
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
Definition: net.h:49
CNode::MaybeSetAddrName
void MaybeSetAddrName(const std::string &addrNameIn)
Sets the addrName only if it was not previously set.
Definition: net.cpp:537
CConnman::ThreadOpenConnections
void ThreadOpenConnections(std::vector< std::string > connect)
Definition: net.cpp:1780
CConnman::semOutbound
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:1184
CNode::nVersion
std::atomic< int > nVersion
Definition: net.h:437
BCLog::NET
@ NET
Definition: logging.h:38
CConnman::GetExtraBlockRelayCount
int GetExtraBlockRelayCount()
Definition: net.cpp:1766
CConnman::semAddnode
std::unique_ptr< CSemaphore > semAddnode
Definition: net.h:1185
CConnman::m_next_send_inv_to_incoming
std::atomic< std::chrono::microseconds > m_next_send_inv_to_incoming
Definition: net.h:1252
CConnman::flagInterruptMsgProc
std::atomic< bool > flagInterruptMsgProc
Definition: net.h:1218
DEFAULT_BLOCKSONLY
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:78
CConnman::m_msgproc
NetEventsInterface * m_msgproc
Definition: net.h:1200
CConnman::threadDNSAddressSeed
std::thread threadDNSAddressSeed
Definition: net.h:1234
CConnman::GetTotalBytesSent
uint64_t GetTotalBytesSent()
Definition: net.cpp:2902
CConnman::Init
void Init(const Options &connOptions)
Definition: net.h:834
CConnman::GenerateSelectSet
bool GenerateSelectSet(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set)
Definition: net.cpp:1296
LOCAL_BIND
@ LOCAL_BIND
Definition: net.h:194
V1TransportDeserializer::m_chain_params
const CChainParams & m_chain_params
Definition: net.h:321
CNode::fClient
bool fClient
Definition: net.h:448
CConnman::m_i2p_sam_session
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
Definition: net.h:1232
CNode::IsFullOutboundConn
bool IsFullOutboundConn() const
Definition: net.h:483
CConnman::threadSocketHandler
std::thread threadSocketHandler
Definition: net.h:1235
CConnman::CheckIncomingNonce
bool CheckIncomingNonce(uint64_t nonce)
Definition: net.cpp:353
CConnman::m_max_outbound_block_relay
int m_max_outbound_block_relay
Definition: net.h:1193
CConnman::Options::m_asmap
std::vector< bool > m_asmap
Definition: net.h:830
CNode::m_greatest_common_version
std::atomic< int > m_greatest_common_version
Definition: net.h:733
CNode::TxRelay::GUARDED_BY
bool fSendMempool GUARDED_BY(cs_tx_inventory)
Definition: net.h:571
amount.h
CThreadInterrupt
Definition: threadinterrupt.h:19
CNode::TxRelay::GUARDED_BY
bool fRelayTxes GUARDED_BY(cs_filter)
Definition: net.h:562
NodeEvictionCandidate::m_is_onion
bool m_is_onion
Definition: net.h:1283
ConnectionType
ConnectionType
Different types of connections to a peer.
Definition: net.h:123
TransportDeserializer::Complete
virtual bool Complete() const =0
assert
assert(std::addressof(::ChainstateActive().CoinsTip())==std::addressof(coins_cache))
IsLocal
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:298
CNode::fPauseSend
std::atomic_bool fPauseSend
Definition: net.h:466
CRollingBloomFilter
RollingBloomFilter is a probabilistic "keep track of most recently inserted" set.
Definition: bloom.h:110
CNodeStats::nServices
ServiceFlags nServices
Definition: net.h:245
CNodeStats
Definition: net.h:241
V1TransportDeserializer::readHeader
int readHeader(Span< const uint8_t > msg_bytes)
Definition: net.cpp:666
strSubVersion
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:110
GetLocalAddrForPeer
std::optional< CAddress > GetLocalAddrForPeer(CNode *pnode)
Returns a local address that we should advertise to this peer.
Definition: net.cpp:201
CaptureMessage
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:3035
MAX_SUBVERSION_LENGTH
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:62
CConnman::m_use_addrman_outgoing
bool m_use_addrman_outgoing
Definition: net.h:1198
CConnman::AddWhitelistPermissionFlags
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, const CNetAddr &addr) const
Definition: net.cpp:506
CConnman::clientInterface
CClientUIInterface * clientInterface
Definition: net.h:1199
CConnman::Options::vWhiteBinds
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:824
CConnman::fNetworkActive
std::atomic< bool > fNetworkActive
Definition: net.h:1130
CConnman::interruptNet
CThreadInterrupt interruptNet
This is signaled when network activity should cease.
Definition: net.h:1226
CNodeStats::m_bip152_highbandwidth_from
bool m_bip152_highbandwidth_from
Definition: net.h:258
CConnman::GetDeterministicRandomizer
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition: net.cpp:3023
CConnman::GetExtraFullOutboundCount
int GetExtraFullOutboundCount()
Definition: net.cpp:1752
CConnman::nMaxAddnode
int nMaxAddnode
Definition: net.h:1195
CConnman::InitBinds
bool InitBinds(const std::vector< CService > &binds, const std::vector< NetWhitebindPermissions > &whiteBinds, const std::vector< CService > &onion_binds)
Definition: net.cpp:2428
GUARDED_BY
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(cs_mapLocalHost)
CConnman::nMaxConnections
int nMaxConnections
Definition: net.h:1186
FastRandomContext
Fast randomness source.
Definition: random.h:119
CConnman::PushMessage
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
Definition: net.cpp:2961
CConnman::ShouldRunInactivityChecks
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:1259
CNode::~CNode
~CNode()
Definition: net.cpp:2951
CConnman::BindListenPort
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
Definition: net.cpp:2269
CNetMessage::m_raw_message_size
uint32_t m_raw_message_size
used wire size of the message (including header/checksum)
Definition: net.h:290
CNode::vAddrToSend
std::vector< CAddress > vAddrToSend
Definition: net.h:549
TIMEOUT_INTERVAL
static const int TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:52
V1TransportDeserializer::nDataPos
unsigned int nDataPos
Definition: net.h:330
CConnman::Options::m_banman
BanMan * m_banman
Definition: net.h:817
GetLocalAddress
CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
Definition: net.cpp:174
EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL
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
CSerializedNetMsg::operator=
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
CNode::CNode
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:2915
Span::subspan
CONSTEXPR_IF_NOT_DEBUG Span< C > subspan(std::size_t offset) const noexcept
Definition: span.h:189
V1TransportDeserializer::nHdrPos
unsigned int nHdrPos
Definition: net.h:329
INIT_PROTO_VERSION
static const int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
Definition: version.h:15
CNode::fPauseRecv
std::atomic_bool fPauseRecv
Definition: net.h:465
CConnman::RecordBytesSent
void RecordBytesSent(uint64_t bytes)
Definition: net.cpp:2825
TransportDeserializer::SetVersion
virtual void SetVersion(int version)=0
net_permissions.h
CNode::TxRelay::nNextInvSend
std::chrono::microseconds nNextInvSend
Definition: net.h:574
DEFAULT_FORCEDNSSEED
static const bool DEFAULT_FORCEDNSSEED
Definition: net.h:84
DEFAULT_LISTEN
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:72
SOCKET
unsigned int SOCKET
Definition: compat.h:41
CService::GetKey
std::vector< unsigned char > GetKey() const
Definition: netaddress.cpp:1006
IsPeerAddrLocalGood
bool IsPeerAddrLocalGood(CNode *pnode)
Definition: net.cpp:194
NodeEvictionCandidate::nLastBlockTime
int64_t nLastBlockTime
Definition: net.h:1275
NodeEvictionCandidate::nLastTXTime
int64_t nLastTXTime
Definition: net.h:1276
CConnman::DeleteNode
void DeleteNode(CNode *pnode)
Definition: net.cpp:2661
CNode::addrBind
const CAddress addrBind
Definition: net.h:434
CConnman::ForEachNode
void ForEachNode(const NodeFn &func) const
Definition: net.h:894
NodeEvictionCandidate::fRelevantServices
bool fRelevantServices
Definition: net.h:1277