Bitcoin Core  0.21.1
P2P Digital Currency
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules
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 <net_permissions.h>
18 #include <netaddress.h>
19 #include <optional.h>
20 #include <policy/feerate.h>
21 #include <protocol.h>
22 #include <random.h>
23 #include <streams.h>
24 #include <sync.h>
25 #include <threadinterrupt.h>
26 #include <uint256.h>
27 
28 #include <atomic>
29 #include <cstdint>
30 #include <deque>
31 #include <map>
32 #include <thread>
33 #include <memory>
34 #include <condition_variable>
35 
36 #ifndef WIN32
37 #include <arpa/inet.h>
38 #endif
39 
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 const int FEELER_INTERVAL = 120;
56 static constexpr size_t MAX_ADDR_TO_SEND = 1000;
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 #ifdef USE_UPNP
73 static const bool DEFAULT_UPNP = USE_UPNP;
74 #else
75 static const bool DEFAULT_UPNP = false;
76 #endif
77 
78 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
80 static const uint64_t DEFAULT_MAX_UPLOAD_TARGET = 0;
82 static const uint64_t MAX_UPLOAD_TIMEFRAME = 60 * 60 * 24;
84 static const bool DEFAULT_BLOCKSONLY = false;
86 static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
87 
88 static const bool DEFAULT_FORCEDNSSEED = false;
89 static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
90 static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
91 
92 typedef int64_t NodeId;
93 
95 {
96  std::string strAddedNode;
98  bool fConnected;
99  bool fInbound;
100 };
101 
102 class CNodeStats;
103 class CClientUIInterface;
104 
106 {
107  CSerializedNetMsg() = default;
110  // No copying, only moves.
111  CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
113 
114  std::vector<unsigned char> data;
115  std::string m_type;
116 };
117 
124 enum class ConnectionType {
130  INBOUND,
131 
139 
140 
147  MANUAL,
148 
164  FEELER,
165 
175  BLOCK_RELAY,
176 
183  ADDR_FETCH,
184 };
185 
186 class NetEventsInterface;
187 class CConnman
188 {
189 public:
190 
193  CONNECTIONS_IN = (1U << 0),
194  CONNECTIONS_OUT = (1U << 1),
196  };
197 
198  struct Options
199  {
204  int nMaxAddnode = 0;
205  int nMaxFeeler = 0;
206  int nBestHeight = 0;
209  BanMan* m_banman = nullptr;
210  unsigned int nSendBufferMaxSize = 0;
211  unsigned int nReceiveFloodSize = 0;
212  uint64_t nMaxOutboundTimeframe = 0;
213  uint64_t nMaxOutboundLimit = 0;
215  std::vector<std::string> vSeedNodes;
216  std::vector<NetWhitelistPermissions> vWhitelistedRange;
217  std::vector<NetWhitebindPermissions> vWhiteBinds;
218  std::vector<CService> vBinds;
219  std::vector<CService> onion_binds;
221  std::vector<std::string> m_specified_outgoing;
222  std::vector<std::string> m_added_nodes;
223  std::vector<bool> m_asmap;
224  };
225 
226  void Init(const Options& connOptions) {
227  nLocalServices = connOptions.nLocalServices;
228  nMaxConnections = connOptions.nMaxConnections;
229  m_max_outbound_full_relay = std::min(connOptions.m_max_outbound_full_relay, connOptions.nMaxConnections);
232  nMaxAddnode = connOptions.nMaxAddnode;
233  nMaxFeeler = connOptions.nMaxFeeler;
235  nBestHeight = connOptions.nBestHeight;
236  clientInterface = connOptions.uiInterface;
237  m_banman = connOptions.m_banman;
238  m_msgproc = connOptions.m_msgproc;
240  nReceiveFloodSize = connOptions.nReceiveFloodSize;
242  {
244  nMaxOutboundTimeframe = connOptions.nMaxOutboundTimeframe;
245  nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
246  }
247  vWhitelistedRange = connOptions.vWhitelistedRange;
248  {
250  vAddedNodes = connOptions.m_added_nodes;
251  }
252  m_onion_binds = connOptions.onion_binds;
253  }
254 
255  CConnman(uint64_t seed0, uint64_t seed1, bool network_active = true);
256  ~CConnman();
257  bool Start(CScheduler& scheduler, const Options& options);
258 
259  void StopThreads();
260  void StopNodes();
261  void Stop()
262  {
263  StopThreads();
264  StopNodes();
265  };
266 
267  void Interrupt();
268  bool GetNetworkActive() const { return fNetworkActive; };
270  void SetNetworkActive(bool active);
271  void OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant* grantOutbound, const char* strDest, ConnectionType conn_type);
272  bool CheckIncomingNonce(uint64_t nonce);
273 
274  bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
275 
276  void PushMessage(CNode* pnode, CSerializedNetMsg&& msg);
277 
278  using NodeFn = std::function<void(CNode*)>;
279  void ForEachNode(const NodeFn& func)
280  {
281  LOCK(cs_vNodes);
282  for (auto&& node : vNodes) {
283  if (NodeFullyConnected(node))
284  func(node);
285  }
286  };
287 
288  void ForEachNode(const NodeFn& func) const
289  {
290  LOCK(cs_vNodes);
291  for (auto&& node : vNodes) {
292  if (NodeFullyConnected(node))
293  func(node);
294  }
295  };
296 
297  template<typename Callable, typename CallableAfter>
298  void ForEachNodeThen(Callable&& pre, CallableAfter&& post)
299  {
300  LOCK(cs_vNodes);
301  for (auto&& node : vNodes) {
302  if (NodeFullyConnected(node))
303  pre(node);
304  }
305  post();
306  };
307 
308  template<typename Callable, typename CallableAfter>
309  void ForEachNodeThen(Callable&& pre, CallableAfter&& post) const
310  {
311  LOCK(cs_vNodes);
312  for (auto&& node : vNodes) {
313  if (NodeFullyConnected(node))
314  pre(node);
315  }
316  post();
317  };
318 
319  // Addrman functions
320  void SetServices(const CService &addr, ServiceFlags nServices);
321  void MarkAddressGood(const CAddress& addr);
322  bool AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
323  std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct);
330  std::vector<CAddress> GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct);
331 
332  // This allows temporarily exceeding m_max_outbound_full_relay, with the goal of finding
333  // a peer that is better than all our current peers.
334  void SetTryNewOutboundPeer(bool flag);
335  bool GetTryNewOutboundPeer();
336 
337  // Return the number of outbound peers we have in excess of our target (eg,
338  // if we previously called SetTryNewOutboundPeer(true), and have since set
339  // to false, we may have extra peers that we wish to disconnect). This may
340  // return a value less than (num_outbound_connections - num_outbound_slots)
341  // in cases where some outbound connections are not yet fully connected, or
342  // not yet fully disconnected.
343  int GetExtraOutboundCount();
344 
345  bool AddNode(const std::string& node);
346  bool RemoveAddedNode(const std::string& node);
347  std::vector<AddedNodeInfo> GetAddedNodeInfo();
348 
349  size_t GetNodeCount(NumConnections num);
350  void GetNodeStats(std::vector<CNodeStats>& vstats);
351  bool DisconnectNode(const std::string& node);
352  bool DisconnectNode(const CSubNet& subnet);
353  bool DisconnectNode(const CNetAddr& addr);
354  bool DisconnectNode(NodeId id);
355 
363 
365  void SetMaxOutboundTarget(uint64_t limit);
366  uint64_t GetMaxOutboundTarget();
367 
369  void SetMaxOutboundTimeframe(uint64_t timeframe);
370  uint64_t GetMaxOutboundTimeframe();
371 
375  bool OutboundTargetReached(bool historicalBlockServingLimit);
376 
379  uint64_t GetOutboundTargetBytesLeft();
380 
384 
385  uint64_t GetTotalBytesRecv();
386  uint64_t GetTotalBytesSent();
387 
388  void SetBestHeight(int height);
389  int GetBestHeight() const;
390 
392  CSipHasher GetDeterministicRandomizer(uint64_t id) const;
393 
394  unsigned int GetReceiveFloodSize() const;
395 
396  void WakeMessageHandler();
397 
402  int64_t PoissonNextSendInbound(int64_t now, int average_interval_seconds);
403 
404  void SetAsmap(std::vector<bool> asmap) { addrman.m_asmap = std::move(asmap); }
405 
406 private:
407  struct ListenSocket {
408  public:
411  ListenSocket(SOCKET socket_, NetPermissionFlags permissions_) : socket(socket_), m_permissions(permissions_) {}
412  private:
414  };
415 
416  bool BindListenPort(const CService& bindAddr, bilingual_str& strError, NetPermissionFlags permissions);
417  bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions);
418  bool InitBinds(
419  const std::vector<CService>& binds,
420  const std::vector<NetWhitebindPermissions>& whiteBinds,
421  const std::vector<CService>& onion_binds);
422 
424  void AddAddrFetch(const std::string& strDest);
425  void ProcessAddrFetch();
426  void ThreadOpenConnections(std::vector<std::string> connect);
427  void ThreadMessageHandler();
428  void AcceptConnection(const ListenSocket& hListenSocket);
429  void DisconnectNodes();
431  void InactivityCheck(CNode *pnode);
432  bool GenerateSelectSet(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set);
433  void SocketEvents(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set);
434  void SocketHandler();
435  void ThreadSocketHandler();
436  void ThreadDNSAddressSeed();
437 
438  uint64_t CalculateKeyedNetGroup(const CAddress& ad) const;
439 
440  CNode* FindNode(const CNetAddr& ip);
441  CNode* FindNode(const CSubNet& subNet);
442  CNode* FindNode(const std::string& addrName);
443  CNode* FindNode(const CService& addr);
444 
449  bool AlreadyConnectedToAddress(const CAddress& addr);
450 
452  CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type);
454 
455  void DeleteNode(CNode* pnode);
456 
458 
459  size_t SocketSendData(CNode *pnode) const;
460  void DumpAddresses();
461 
462  // Network stats
463  void RecordBytesRecv(uint64_t bytes);
464  void RecordBytesSent(uint64_t bytes);
465 
469  std::vector<CAddress> GetCurrentBlockRelayOnlyConns() const;
470 
471  // Whether the node should be passed out in ForEach* callbacks
472  static bool NodeFullyConnected(const CNode* pnode);
473 
474  // Network usage totals
477  uint64_t nTotalBytesRecv GUARDED_BY(cs_totalBytesRecv) {0};
478  uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent) {0};
479 
480  // outbound limit & stats
481  uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent);
482  uint64_t nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent);
483  uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent);
484  uint64_t nMaxOutboundTimeframe GUARDED_BY(cs_totalBytesSent);
485 
486  // P2P timeout in seconds
488 
489  // Whitelisted ranges. Any node connecting from these is automatically
490  // whitelisted (as well as those connecting to whitelisted binds).
491  std::vector<NetWhitelistPermissions> vWhitelistedRange;
492 
493  unsigned int nSendBufferMaxSize{0};
494  unsigned int nReceiveFloodSize{0};
495 
496  std::vector<ListenSocket> vhListenSocket;
497  std::atomic<bool> fNetworkActive{true};
500  std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
502  std::vector<std::string> vAddedNodes GUARDED_BY(cs_vAddedNodes);
504  std::vector<CNode*> vNodes GUARDED_BY(cs_vNodes);
505  std::list<CNode*> vNodesDisconnected;
507  std::atomic<NodeId> nLastNodeId{0};
508  unsigned int nPrevNodeCount{0};
509 
517  std::vector<CAddress> m_addrs_response_cache;
518  std::chrono::microseconds m_cache_entry_expiration{0};
519  };
520 
535  std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
536 
550 
551  std::unique_ptr<CSemaphore> semOutbound;
552  std::unique_ptr<CSemaphore> semAddnode;
554 
555  // How many full-relay (tx, block, addr) outbound peers we want
557 
558  // How many block-relay only outbound peers we want
559  // We do not relay tx or addr messages with these peers
561 
566  std::atomic<int> nBestHeight;
571 
576  std::vector<CAddress> m_anchors;
577 
579  const uint64_t nSeed0, nSeed1;
580 
582  bool fMsgProcWake GUARDED_BY(mutexMsgProc);
583 
584  std::condition_variable condMsgProc;
586  std::atomic<bool> flagInterruptMsgProc{false};
587 
589 
590  std::thread threadDNSAddressSeed;
591  std::thread threadSocketHandler;
594  std::thread threadMessageHandler;
595 
599  std::atomic_bool m_try_another_outbound_peer;
600 
601  std::atomic<int64_t> m_next_send_inv_to_incoming{0};
602 
607  std::vector<CService> m_onion_binds;
608 
609  friend struct CConnmanTest;
610  friend struct ConnmanTestMsg;
611 };
612 void Discover();
613 void StartMapPort();
614 void InterruptMapPort();
615 void StopMapPort();
616 uint16_t GetListenPort();
617 
622 {
623 public:
624  virtual bool ProcessMessages(CNode* pnode, std::atomic<bool>& interrupt) = 0;
625  virtual bool SendMessages(CNode* pnode) = 0;
626  virtual void InitializeNode(CNode* pnode) = 0;
627  virtual void FinalizeNode(const CNode& node, bool& update_connection_time) = 0;
628 
629 protected:
634  ~NetEventsInterface() = default;
635 };
636 
637 enum
638 {
639  LOCAL_NONE, // unknown
640  LOCAL_IF, // address a local interface listens on
641  LOCAL_BIND, // address explicit bound to
642  LOCAL_UPNP, // address reported by UPnP
643  LOCAL_MANUAL, // address explicitly specified (-externalip=)
644 
646 };
647 
648 bool IsPeerAddrLocalGood(CNode *pnode);
649 void AdvertiseLocal(CNode *pnode);
650 
655 void SetReachable(enum Network net, bool reachable);
657 bool IsReachable(enum Network net);
659 bool IsReachable(const CNetAddr& addr);
660 
661 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
662 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
663 void RemoveLocal(const CService& addr);
664 bool SeenLocal(const CService& addr);
665 bool IsLocal(const CService& addr);
666 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr);
668 
669 
670 extern bool fDiscover;
671 extern bool fListen;
672 extern bool g_relay_txes;
673 
675 extern std::string strSubVersion;
676 
678  int nScore;
679  int nPort;
680 };
681 
683 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(cs_mapLocalHost);
684 
685 extern const std::string NET_MESSAGE_COMMAND_OTHER;
686 typedef std::map<std::string, uint64_t> mapMsgCmdSize; //command, total bytes
687 
689 {
690 public:
694  int64_t nLastSend;
695  int64_t nLastRecv;
696  int64_t nLastTXTime;
697  int64_t nLastBlockTime;
698  int64_t nTimeConnected;
699  int64_t nTimeOffset;
700  std::string addrName;
701  int nVersion;
702  std::string cleanSubVer;
703  bool fInbound;
706  uint64_t nSendBytes;
707  mapMsgCmdSize mapSendBytesPerMsgCmd;
708  uint64_t nRecvBytes;
709  mapMsgCmdSize mapRecvBytesPerMsgCmd;
712  int64_t m_ping_usec;
716  // Our address, as reported by the peer
717  std::string addrLocal;
718  // Address of this peer
720  // Bind address of our side of the connection
722  // Name of the network the peer connected through
723  std::string m_network;
724  uint32_t m_mapped_as;
725  std::string m_conn_type_string;
726 };
727 
728 
729 
734 class CNetMessage {
735 public:
737  std::chrono::microseconds m_time{0};
738  uint32_t m_message_size{0};
739  uint32_t m_raw_message_size{0};
740  std::string m_command;
741 
742  CNetMessage(CDataStream&& recv_in) : m_recv(std::move(recv_in)) {}
743 
744  void SetVersion(int nVersionIn)
745  {
746  m_recv.SetVersion(nVersionIn);
747  }
748 };
749 
755 public:
756  // returns true if the current deserialization is complete
757  virtual bool Complete() const = 0;
758  // set the serialization context version
759  virtual void SetVersion(int version) = 0;
760  // read and deserialize data
761  virtual int Read(const char *data, unsigned int bytes) = 0;
762  // decomposes a message from the context
763  virtual Optional<CNetMessage> GetMessage(std::chrono::microseconds time, uint32_t& out_err) = 0;
765 };
766 
768 {
769 private:
771  const NodeId m_node_id; // Only for logging
772  mutable CHash256 hasher;
774  bool in_data; // parsing header (false) or data (true)
775  CDataStream hdrbuf; // partially received header
776  CMessageHeader hdr; // complete header
777  CDataStream vRecv; // received message data
778  unsigned int nHdrPos;
779  unsigned int nDataPos;
780 
781  const uint256& GetMessageHash() const;
782  int readHeader(const char *pch, unsigned int nBytes);
783  int readData(const char *pch, unsigned int nBytes);
784 
785  void Reset() {
786  vRecv.clear();
787  hdrbuf.clear();
788  hdrbuf.resize(24);
789  in_data = false;
790  nHdrPos = 0;
791  nDataPos = 0;
792  data_hash.SetNull();
793  hasher.Reset();
794  }
795 
796 public:
797  V1TransportDeserializer(const CChainParams& chain_params, const NodeId node_id, int nTypeIn, int nVersionIn)
798  : m_chain_params(chain_params),
799  m_node_id(node_id),
800  hdrbuf(nTypeIn, nVersionIn),
801  vRecv(nTypeIn, nVersionIn)
802  {
803  Reset();
804  }
805 
806  bool Complete() const override
807  {
808  if (!in_data)
809  return false;
810  return (hdr.nMessageSize == nDataPos);
811  }
812  void SetVersion(int nVersionIn) override
813  {
814  hdrbuf.SetVersion(nVersionIn);
815  vRecv.SetVersion(nVersionIn);
816  }
817  int Read(const char *pch, unsigned int nBytes) override {
818  int ret = in_data ? readData(pch, nBytes) : readHeader(pch, nBytes);
819  if (ret < 0) Reset();
820  return ret;
821  }
822  Optional<CNetMessage> GetMessage(std::chrono::microseconds time, uint32_t& out_err_raw_size) override;
823 };
824 
828 public:
829  // prepare message for transport (header construction, error-correction computation, payload encryption, etc.)
830  virtual void prepareForTransport(CSerializedNetMsg& msg, std::vector<unsigned char>& header) = 0;
831  virtual ~TransportSerializer() {}
832 };
833 
835 public:
836  void prepareForTransport(CSerializedNetMsg& msg, std::vector<unsigned char>& header) override;
837 };
838 
840 class CNode
841 {
842  friend class CConnman;
843  friend struct ConnmanTestMsg;
844 
845 public:
846  std::unique_ptr<TransportDeserializer> m_deserializer;
847  std::unique_ptr<TransportSerializer> m_serializer;
848 
849  // socket
850  std::atomic<ServiceFlags> nServices{NODE_NONE};
851  SOCKET hSocket GUARDED_BY(cs_hSocket);
852  size_t nSendSize{0}; // total size of all vSendMsg entries
853  size_t nSendOffset{0}; // offset inside the first vSendMsg already sent
854  uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
855  std::deque<std::vector<unsigned char>> vSendMsg GUARDED_BY(cs_vSend);
859 
861  std::list<CNetMessage> vProcessMsg GUARDED_BY(cs_vProcessMsg);
862  size_t nProcessQueueSize{0};
863 
865 
866  uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
867 
868  std::atomic<int64_t> nLastSend{0};
869  std::atomic<int64_t> nLastRecv{0};
870  const int64_t nTimeConnected;
871  std::atomic<int64_t> nTimeOffset{0};
872  // Address of this peer
873  const CAddress addr;
874  // Bind address of our side of the connection
876  std::atomic<int> nVersion{0};
882  std::string cleanSubVer GUARDED_BY(cs_SubVer){};
883  bool m_prefer_evict{false}; // This peer is preferred for eviction.
884  bool HasPermission(NetPermissionFlags permission) const {
885  return NetPermissions::HasFlag(m_permissionFlags, permission);
886  }
887  // This boolean is unusued in actual processing, only present for backward compatibility at RPC/QT level
888  bool m_legacyWhitelisted{false};
889  bool fClient{false}; // set by version message
890  bool m_limited_node{false}; //after BIP159, set by version message
895  std::atomic_bool m_wants_addrv2{false};
896  std::atomic_bool fSuccessfullyConnected{false};
897  // Setting fDisconnect to true will cause the node to be disconnected the
898  // next time DisconnectNodes() runs
899  std::atomic_bool fDisconnect{false};
900  bool fSentAddr{false};
902  std::atomic<int> nRefCount{0};
903 
904  const uint64_t nKeyedNetGroup;
905  std::atomic_bool fPauseRecv{false};
906  std::atomic_bool fPauseSend{false};
907 
909  switch (m_conn_type) {
912  return true;
917  return false;
918  } // no default case, so the compiler can warn about missing cases
919 
920  assert(false);
921  }
922 
923  bool IsFullOutboundConn() const {
924  return m_conn_type == ConnectionType::OUTBOUND_FULL_RELAY;
925  }
926 
927  bool IsManualConn() const {
928  return m_conn_type == ConnectionType::MANUAL;
929  }
930 
931  bool IsBlockOnlyConn() const {
932  return m_conn_type == ConnectionType::BLOCK_RELAY;
933  }
934 
935  bool IsFeelerConn() const {
936  return m_conn_type == ConnectionType::FEELER;
937  }
938 
939  bool IsAddrFetchConn() const {
940  return m_conn_type == ConnectionType::ADDR_FETCH;
941  }
942 
943  bool IsInboundConn() const {
944  return m_conn_type == ConnectionType::INBOUND;
945  }
946 
947  /* Whether we send addr messages over this connection */
948  bool RelayAddrsWithConn() const
949  {
950  return m_conn_type != ConnectionType::BLOCK_RELAY;
951  }
952 
953  bool ExpectServicesFromConn() const {
954  switch (m_conn_type) {
958  return false;
962  return true;
963  } // no default case, so the compiler can warn about missing cases
964 
965  assert(false);
966  }
967 
978  Network ConnectedThroughNetwork() const;
979 
980 protected:
981  mapMsgCmdSize mapSendBytesPerMsgCmd;
982  mapMsgCmdSize mapRecvBytesPerMsgCmd GUARDED_BY(cs_vRecv);
983 
984 public:
986  std::atomic<int> nStartingHeight{-1};
987 
988  // flood relay
989  std::vector<CAddress> vAddrToSend;
990  std::unique_ptr<CRollingBloomFilter> m_addr_known{nullptr};
991  bool fGetAddr{false};
992  std::chrono::microseconds m_next_addr_send GUARDED_BY(cs_sendProcessing){0};
993  std::chrono::microseconds m_next_local_addr_send GUARDED_BY(cs_sendProcessing){0};
994 
995  // List of block ids we still have announce.
996  // There is no final sorting before sending, as they are always sent immediately
997  // and in the order requested.
998  std::vector<uint256> vInventoryBlockToSend GUARDED_BY(cs_inventory);
1000 
1001  struct TxRelay {
1003  // We use fRelayTxes for two purposes -
1004  // a) it allows us to not relay tx invs before receiving the peer's version message
1005  // b) the peer may tell us in its version message that we should not relay tx invs
1006  // unless it loads a bloom filter.
1007  bool fRelayTxes GUARDED_BY(cs_filter){false};
1008  std::unique_ptr<CBloomFilter> pfilter PT_GUARDED_BY(cs_filter) GUARDED_BY(cs_filter){nullptr};
1009 
1010  mutable RecursiveMutex cs_tx_inventory;
1011  CRollingBloomFilter filterInventoryKnown GUARDED_BY(cs_tx_inventory){50000, 0.000001};
1012  // Set of transaction ids we still have to announce.
1013  // They are sorted by the mempool before relay, so the order is not important.
1014  std::set<uint256> setInventoryTxToSend;
1015  // Used for BIP35 mempool sending
1016  bool fSendMempool GUARDED_BY(cs_tx_inventory){false};
1017  // Last time a "MEMPOOL" request was serviced.
1018  std::atomic<std::chrono::seconds> m_last_mempool_req{std::chrono::seconds{0}};
1019  std::chrono::microseconds nNextInvSend{0};
1020 
1022  // Minimum fee rate with which to filter inv's to this node
1023  CAmount minFeeFilter GUARDED_BY(cs_feeFilter){0};
1024  CAmount lastSentFeeFilter{0};
1025  int64_t nextSendTimeFeeFilter{0};
1026  };
1027 
1028  // m_tx_relay == nullptr if we're not relaying transactions with this peer
1029  std::unique_ptr<TxRelay> m_tx_relay;
1030 
1031  // Used for headers announcements - unfiltered blocks to relay
1032  std::vector<uint256> vBlockHashesToAnnounce GUARDED_BY(cs_inventory);
1033 
1039  std::atomic<int64_t> nLastBlockTime{0};
1040 
1045  std::atomic<int64_t> nLastTXTime{0};
1046 
1047  // Ping time measurement:
1048  // The pong reply we're expecting, or 0 if no pong expected.
1049  std::atomic<uint64_t> nPingNonceSent{0};
1051  std::atomic<std::chrono::microseconds> m_ping_start{std::chrono::microseconds{0}};
1052  // Last measured round-trip time.
1053  std::atomic<int64_t> nPingUsecTime{0};
1054  // Best measured round-trip time.
1055  std::atomic<int64_t> nMinPingUsecTime{std::numeric_limits<int64_t>::max()};
1056  // Whether a ping is requested.
1057  std::atomic<bool> fPingQueued{false};
1058 
1059  CNode(NodeId id, ServiceFlags nLocalServicesIn, int nMyStartingHeightIn, 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 = false);
1060  ~CNode();
1061  CNode(const CNode&) = delete;
1062  CNode& operator=(const CNode&) = delete;
1063 
1064 private:
1065  const NodeId id;
1066  const uint64_t nLocalHostNonce;
1068  std::atomic<int> m_greatest_common_version{INIT_PROTO_VERSION};
1069 
1086 
1088  NetPermissionFlags m_permissionFlags{ PF_NONE };
1089  std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
1090 
1092  std::string addrName GUARDED_BY(cs_addrName);
1093 
1094  // Our address, as reported by the peer
1095  CService addrLocal GUARDED_BY(cs_addrLocal);
1097 
1099  const bool m_inbound_onion{false};
1100 
1101 public:
1102 
1103  NodeId GetId() const {
1104  return id;
1105  }
1106 
1107  uint64_t GetLocalNonce() const {
1108  return nLocalHostNonce;
1109  }
1110 
1111  int GetMyStartingHeight() const {
1112  return nMyStartingHeight;
1113  }
1114 
1115  int GetRefCount() const
1116  {
1117  assert(nRefCount >= 0);
1118  return nRefCount;
1119  }
1120 
1121  bool ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool& complete);
1122 
1123  void SetCommonVersion(int greatest_common_version)
1124  {
1125  m_greatest_common_version = greatest_common_version;
1126  }
1127  int GetCommonVersion() const
1128  {
1129  return m_greatest_common_version;
1130  }
1131 
1132  CService GetAddrLocal() const;
1134  void SetAddrLocal(const CService& addrLocalIn);
1135 
1137  {
1138  nRefCount++;
1139  return this;
1140  }
1141 
1142  void Release()
1143  {
1144  nRefCount--;
1145  }
1146 
1147 
1148 
1149  void AddAddressKnown(const CAddress& _addr)
1150  {
1151  assert(m_addr_known);
1152  m_addr_known->insert(_addr.GetKey());
1153  }
1154 
1155  void PushAddress(const CAddress& _addr, FastRandomContext &insecure_rand)
1156  {
1157  // Whether the peer supports the address in `_addr`. For example,
1158  // nodes that do not implement BIP155 cannot receive Tor v3 addresses
1159  // because they require ADDRv2 (BIP155) encoding.
1160  const bool addr_format_supported = m_wants_addrv2 || _addr.IsAddrV1Compatible();
1161 
1162  // Known checking here is only to save space from duplicates.
1163  // SendMessages will filter it again for knowns that were added
1164  // after addresses were pushed.
1165  assert(m_addr_known);
1166  if (_addr.IsValid() && !m_addr_known->contains(_addr.GetKey()) && addr_format_supported) {
1167  if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
1168  vAddrToSend[insecure_rand.randrange(vAddrToSend.size())] = _addr;
1169  } else {
1170  vAddrToSend.push_back(_addr);
1171  }
1172  }
1173  }
1174 
1175 
1176  void AddKnownTx(const uint256& hash)
1177  {
1178  if (m_tx_relay != nullptr) {
1179  LOCK(m_tx_relay->cs_tx_inventory);
1180  m_tx_relay->filterInventoryKnown.insert(hash);
1181  }
1182  }
1183 
1184  void PushTxInventory(const uint256& hash)
1185  {
1186  if (m_tx_relay == nullptr) return;
1187  LOCK(m_tx_relay->cs_tx_inventory);
1188  if (!m_tx_relay->filterInventoryKnown.contains(hash)) {
1189  m_tx_relay->setInventoryTxToSend.insert(hash);
1190  }
1191  }
1192 
1193  void CloseSocketDisconnect();
1194 
1195  void copyStats(CNodeStats &stats, const std::vector<bool> &m_asmap);
1196 
1198  {
1199  return nLocalServices;
1200  }
1201 
1202  std::string GetAddrName() const;
1204  void MaybeSetAddrName(const std::string& addrNameIn);
1205 
1206  std::string ConnectionTypeAsString() const;
1207 };
1208 
1210 int64_t PoissonNextSend(int64_t now, int average_interval_seconds);
1211 
1213 inline std::chrono::microseconds PoissonNextSend(std::chrono::microseconds now, std::chrono::seconds average_interval)
1214 {
1215  return std::chrono::microseconds{PoissonNextSend(now.count(), average_interval.count())};
1216 }
1217 
1218 #endif // BITCOIN_NET_H
std::vector< CService > vBinds
Definition: net.h:218
int m_max_outbound_full_relay
Definition: net.h:202
std::atomic< bool > flagInterruptMsgProc
Definition: net.h:586
uint256 data_hash
Definition: net.h:773
std::vector< CAddress > m_addrs_response_cache
Definition: net.h:517
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:66
std::string m_type
Definition: net.h:115
uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent)
Definition: net.h:478
int nMaxFeeler
Definition: net.h:563
void SocketHandler()
bool HasPermission(NetPermissionFlags permission) const
Definition: net.h:884
std::vector< bool > m_asmap
Definition: net.h:223
bool IsReachable(enum Network net)
int nStartingHeight
Definition: net.h:705
void ThreadOpenAddedConnections()
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
int GetCommonVersion() const
Definition: net.h:1127
int m_max_outbound
Definition: net.h:564
mapMsgCmdSize mapRecvBytesPerMsgCmd
Definition: net.h:709
uint64_t CalculateKeyedNetGroup(const CAddress &ad) const
std::atomic< bool > fNetworkActive
Definition: net.h:497
uint64_t GetLocalNonce() const
Definition: net.h:1107
Definition: banman.h:57
static void AddFlag(NetPermissionFlags &flags, NetPermissionFlags f)
ServiceFlags
nServices flags
Definition: protocol.h:269
static const uint64_t MAX_UPLOAD_TIMEFRAME
The default timeframe for -maxuploadtarget.
Definition: net.h:82
void SetNull()
Definition: uint256.h:39
std::unique_ptr< TransportSerializer > m_serializer
Definition: net.h:847
RecursiveMutex cs_vNodes
Definition: net.h:506
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:882
unsigned int GetReceiveFloodSize() const
int64_t nTimeOffset
Definition: net.h:699
int64_t m_ping_usec
Definition: net.h:712
bool fListen
int m_max_outbound_block_relay
Definition: net.h:203
We open manual connections to addresses that users explicitly inputted via the addnode RPC...
CNode * FindNode(const CNetAddr &ip)
uint32_t m_mapped_as
Definition: net.h:724
std::atomic< int > nBestHeight
Definition: net.h:566
void WakeMessageHandler()
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
bool fRelayTxes GUARDED_BY(cs_filter)
Definition: net.h:1007
bool m_legacyWhitelisted
Definition: net.h:711
static bool NodeFullyConnected(const CNode *pnode)
void SetServices(const CService &addr, ServiceFlags nServices)
void Interrupt()
Bilingual messages:
Definition: translation.h:16
void SocketEvents(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set)
const std::string NET_MESSAGE_COMMAND_OTHER
ServiceFlags GetLocalServices() const
Used to convey which local services we are offering peers during node connection. ...
void SetVersion(int nVersionIn) override
Definition: net.h:812
void PushTxInventory(const uint256 &hash)
Definition: net.h:1184
BanMan * m_banman
Definition: net.h:209
Mutex mutexMsgProc
Definition: net.h:585
static const bool DEFAULT_FORCEDNSSEED
Definition: net.h:88
const uint64_t nKeyedNetGroup
Definition: net.h:904
bool SeenLocal(const CService &addr)
mapMsgCmdSize mapSendBytesPerMsgCmd
Definition: net.h:981
CDataStream hdrbuf
Definition: net.h:775
void StartMapPort()
std::vector< CAddress > GetAddresses(size_t max_addresses, size_t max_pct)
void StopMapPort()
std::vector< unsigned char > data
Definition: net.h:114
unsigned int nDataPos
Definition: net.h:779
const ConnectionType m_conn_type
Definition: net.h:1067
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:491
CAmount minFeeFilter GUARDED_BY(cs_feeFilter)
Definition: net.h:1023
#define USE_UPNP
unsigned int nReceiveFloodSize
Definition: net.h:211
uint16_t GetListenPort()
RecursiveMutex cs_filter
Definition: net.h:1002
int m_max_outbound_full_relay
Definition: net.h:556
mapMsgCmdSize mapSendBytesPerMsgCmd
Definition: net.h:707
CClientUIInterface * uiInterface
Definition: net.h:207
void resize(size_type n, value_type c=0)
Definition: streams.h:295
bool g_relay_txes
std::vector< CService > m_onion_binds
A vector of -bind=
:=onion arguments each of which is an address and port that are desi...
Definition: net.h:607
void SetAsmap(std::vector< bool > asmap)
Definition: net.h:404
void ProcessAddrFetch()
ServiceFlags nServices
Definition: net.h:692
bool AlreadyConnectedToAddress(const CAddress &addr)
Determine whether we're already connected to a given address, in order to avoid initiating duplicate ...
void ForEachNodeThen(Callable &&pre, CallableAfter &&post) const
Definition: net.h:309
Mutex cs_inventory
Definition: net.h:999
bool GetTryNewOutboundPeer()
std::atomic< int64_t > m_next_send_inv_to_incoming
Definition: net.h:601
CDataStream m_recv
received message data
Definition: net.h:736
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:70
CNetMessage(CDataStream &&recv_in)
Definition: net.h:742
int nMaxAddnode
Definition: net.h:562
RAII-style semaphore lock.
Definition: sync.h:296
friend struct CConnmanTest
Definition: net.h:609
void SetCommonVersion(int greatest_common_version)
Definition: net.h:1123
uint64_t GetMaxOutboundTarget()
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:64
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
RecursiveMutex cs_vProcessMsg
Definition: net.h:860
void SetMaxOutboundTimeframe(uint64_t timeframe)
set the timeframe for the max outbound target
std::string cleanSubVer
Definition: net.h:702
Interface for message handling.
Definition: net.h:621
void SetVersion(int nVersionIn)
Definition: net.h:744
RecursiveMutex cs_addrName
Definition: net.h:1091
RollingBloomFilter is a probabilistic "keep track of most recently inserted" set. ...
Definition: bloom.h:99
NetEventsInterface * m_msgproc
Definition: net.h:568
CAmount minFeeFilter
Definition: net.h:715
int nMaxConnections
Definition: net.h:201
CSerializedNetMsg()=default
int64_t nTimeConnected
Definition: net.h:698
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:52
void AdvertiseLocal(CNode *pnode)
int m_max_outbound_block_relay
Definition: net.h:560
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:202
void SetTryNewOutboundPeer(bool flag)
uint32_t nMessageSize
Definition: protocol.h:54
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
Definition: hash.h:24
std::unique_ptr< TransportDeserializer > m_deserializer
Definition: net.h:846
void ThreadSocketHandler()
std::vector< CAddress > vAddrToSend
Definition: net.h:989
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const
Return vector of current BLOCK_RELAY peers.
bool IsBlockOnlyConn() const
Definition: net.h:931
size_t GetNodeCount(NumConnections num)
bool IsFeelerConn() const
Definition: net.h:935
void PushAddress(const CAddress &_addr, FastRandomContext &insecure_rand)
Definition: net.h:1155
static const int FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes or 120 seconds.
Definition: net.h:54
RecursiveMutex cs_vRecv
Definition: net.h:858
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Definition: net.h:854
static const int TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:52
Definition: net.h:645
Signals for UI communication.
Definition: ui_interface.h:24
void StopThreads()
std::list< CNetMessage > vRecvMsg
Definition: net.h:1089
void NotifyNumConnectionsChanged()
const NodeId m_node_id
Definition: net.h:771
void SetMaxOutboundTarget(uint64_t limit)
set the max outbound target in bytes
void RecordBytesSent(uint64_t bytes)
CAddrMan addrman
Definition: net.h:499
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:535
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition: net.h:68
uint64_t GetMaxOutboundTimeframe()
bool fConnected
Definition: net.h:98
virtual ~TransportDeserializer()
Definition: net.h:764
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
RecursiveMutex cs_sendProcessing
Definition: net.h:864
ServiceFlags nLocalServices
Services this instance offers.
Definition: net.h:549
bool DisconnectNode(const std::string &node)
bool RelayAddrsWithConn() const
Definition: net.h:948
bool m_manual_connection
Definition: net.h:704
CHash256 hasher
Definition: net.h:772
Stochastical (IP) address manager.
Definition: addrman.h:172
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
void RecordBytesRecv(uint64_t bytes)
void DumpAddresses()
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:89
int64_t nLastTXTime
Definition: net.h:696
bool IsAddrFetchConn() const
Definition: net.h:939
std::chrono::microseconds m_next_local_addr_send GUARDED_BY(cs_sendProcessing)
Definition: net.h:993
int nVersion
Definition: net.h:701
bool GetUseAddrmanOutgoing() const
Definition: net.h:269
void InterruptMapPort()
int64_t m_ping_wait_usec
Definition: net.h:713
bool IsInboundConn() const
Definition: net.h:943
uint64_t GetOutboundTargetBytesLeft()
response the bytes left in the current max outbound cycle in case of no limit, it will always respons...
void Release()
Definition: net.h:1142
std::chrono::microseconds m_cache_entry_expiration
Definition: net.h:518
void AddAddrFetch(const std::string &strDest)
bool GetLocal(CService &addr, const CNetAddr *paddrPeer=nullptr)
unsigned int nPrevNodeCount
Definition: net.h:508
bool AddNode(const std::string &node)
std::condition_variable condMsgProc
Definition: net.h:584
bool IsFullOutboundConn() const
Definition: net.h:923
RecursiveMutex cs_vAddedNodes
Definition: net.h:503
uint64_t GetMaxOutboundTimeLeftInCycle()
response the time in second left in the current max outbound cycle in case of no limit, it will always response 0
NumConnections
Definition: clientmodel.h:38
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *strDest, ConnectionType conn_type)
ListenSocket(SOCKET socket_, NetPermissionFlags permissions_)
Definition: net.h:411
void InactivityCheck(CNode *pnode)
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition: net.h:579
bool IsValid() const
Definition: netaddress.cpp:432
std::thread threadOpenAddedConnections
Definition: net.h:592
#define LOCK(cs)
Definition: sync.h:230
RecursiveMutex m_addr_fetches_mutex
Definition: net.h:501
bool IsPeerAddrLocalGood(CNode *pnode)
std::function< void(CNode *)> NodeFn
Definition: net.h:278
NetEventsInterface * m_msgproc
Definition: net.h:208
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:96
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:523
Fast randomness source.
Definition: random.h:119
Transport protocol agnostic message container.
Definition: net.h:734
const CAddress addrBind
Definition: net.h:875
std::vector< std::string > vSeedNodes
Definition: net.h:215
int64_t PoissonNextSendInbound(int64_t now, int average_interval_seconds)
Attempts to obfuscate tx time through exponentially distributed emitting.
bool OutboundTargetReached(bool historicalBlockServingLimit)
check if the outbound target is reached if param historicalBlockServingLimit is set true...
std::vector< std::string > m_specified_outgoing
Definition: net.h:221
int64_t m_peer_connect_timeout
Definition: net.h:487
void DisconnectNodes()
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:551
void ThreadOpenConnections(std::vector< std::string > connect)
std::thread threadMessageHandler
Definition: net.h:594
static bool HasFlag(const NetPermissionFlags &flags, NetPermissionFlags f)
void ForEachNodeThen(Callable &&pre, CallableAfter &&post)
Definition: net.h:298
friend struct ConnmanTestMsg
Definition: net.h:610
bool fInbound
Definition: net.h:703
A CService with information about it as peer.
Definition: protocol.h:360
bool Start(CScheduler &scheduler, const Options &options)
uint64_t nRecvBytes
Definition: net.h:708
int Read(const char *pch, unsigned int nBytes) override
Definition: net.h:817
uint64_t GetTotalBytesRecv()
RecursiveMutex cs_mapLocalHost
bool fInbound
Definition: net.h:99
std::string addrName
Definition: net.h:700
int nMaxFeeler
Definition: net.h:205
Network
A network type.
Definition: netaddress.h:43
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:599
int64_t NodeId
Definition: net.h:92
Definition: net.h:187
void SetNetworkActive(bool active)
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:78
NumConnections
Definition: net.h:191
CClientUIInterface * clientInterface
Definition: net.h:567
void GetNodeStats(std::vector< CNodeStats > &vstats)
uint64_t nSendBytes
Definition: net.h:706
bool AddNewAddresses(const std::vector< CAddress > &vAddr, const CAddress &addrFrom, int64_t nTimePenalty=0)
int nMaxConnections
Definition: net.h:553
bool InitBinds(const std::vector< CService > &binds, const std::vector< NetWhitebindPermissions > &whiteBinds, const std::vector< CService > &onion_binds)
int GetMyStartingHeight() const
Definition: net.h:1111
The TransportSerializer prepares messages for the network transport.
Definition: net.h:827
ServiceFlags GetLocalServices() const
Definition: net.h:1197
NetPermissionFlags
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Definition: net.h:866
bool GetNetworkActive() const
Definition: net.h:268
void Discover()
Inbound connections are those initiated by a peer.
RecursiveMutex cs_SubVer
Definition: net.h:877
void DeleteNode(CNode *pnode)
unsigned int SOCKET
Definition: compat.h:45
NetPermissionFlags m_permissions
Definition: net.h:413
bool CheckIncomingNonce(uint64_t nonce)
bool IsAddrV1Compatible() const
Check if the current object can be serialized in pre-ADDRv2/BIP155 format.
Definition: netaddress.cpp:481
const CAddress addr
Definition: net.h:873
bool Complete() const override
Definition: net.h:806
CDataStream vRecv
Definition: net.h:777
const int64_t nTimeConnected
Definition: net.h:870
CMessageHeader hdr
Definition: net.h:776
virtual ~TransportSerializer()
Definition: net.h:831
int flags
Definition: bitcoin-tx.cpp:506
uint64_t nMaxOutboundTimeframe
Definition: net.h:212
std::atomic< NodeId > nLastNodeId
Definition: net.h:507
Network address.
Definition: netaddress.h:119
bool RemoveAddedNode(const std::string &node)
RecursiveMutex cs_feeFilter
Definition: net.h:1021
std::list< CNode * > vNodesDisconnected
Definition: net.h:505
256-bit opaque blob.
Definition: uint256.h:124
void RemoveLocal(const CService &addr)
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:216
std::vector< CService > onion_binds
Definition: net.h:219
bool ExpectServicesFromConn() const
Definition: net.h:953
int nScore
Definition: net.h:678
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
Definition: net.h:49
int nMaxAddnode
Definition: net.h:204
int GetRefCount() const
Definition: net.h:1115
void AddKnownTx(const uint256 &hash)
Definition: net.h:1176
BanMan * m_banman
Pointer to this node's banman.
Definition: net.h:570
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:90
CAddress addrBind
Definition: net.h:721
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, const CNetAddr &addr) const
bool fSendMempool GUARDED_BY(cs_tx_inventory)
Definition: net.h:1016
int GetBestHeight() const
CService resolvedAddress
Definition: net.h:97
std::thread threadOpenConnections
Definition: net.h:593
bool AttemptToEvictConnection()
static const uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:80
ConnectionType
Different types of connections to a peer.
Definition: net.h:124
bool IsOutboundOrBlockRelayConn() const
Definition: net.h:908
CSemaphoreGrant grantOutbound
Definition: net.h:901
The TransportDeserializer takes care of holding and deserializing the network receive buffer...
Definition: net.h:754
const CChainParams & m_chain_params
Definition: net.h:770
uint256 hashContinue
Definition: net.h:985
std::map< std::string, uint64_t > mapMsgCmdSize
Definition: net.h:686
const NodeId id
Definition: net.h:1065
NodeId GetNewNodeId()
Feeler connections are short-lived connections made to check that a node is alive.
std::string addrLocal
Definition: net.h:717
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:56
bool fAddressesInitialized
Definition: net.h:498
std::thread threadDNSAddressSeed
Definition: net.h:590
ServiceFlags nLocalServices
Definition: net.h:200
uint64_t nMaxOutboundLimit
Definition: net.h:213
NodeId GetId() const
Definition: net.h:1103
std::vector< std::string > m_added_nodes
Definition: net.h:222
RecursiveMutex cs_vSend
Definition: net.h:856
int64_t PoissonNextSend(int64_t now, int average_interval_seconds)
Return a timestamp in the future (in microseconds) for exponentially distributed events.
std::vector< ListenSocket > vhListenSocket
Definition: net.h:496
void SetBestHeight(int height)
SipHash-2-4.
Definition: siphash.h:13
std::string m_conn_type_string
Definition: net.h:725
void ThreadMessageHandler()
These are the default connections that we use to connect with the network.
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:60
uint64_t nTotalBytesRecv GUARDED_BY(cs_totalBytesRecv)
Definition: net.h:477
void StopNodes()
static const bool DEFAULT_UPNP
-upnp default
Definition: net.h:73
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition: net.h:86
unsigned int nSendBufferMaxSize
Definition: net.h:493
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:84
const uint64_t nLocalHostNonce
Definition: net.h:1066
unsigned int nSendBufferMaxSize
Definition: net.h:210
std::vector< bool > m_asmap
Definition: addrman.h:305
void ForEachNode(const NodeFn &func) const
Definition: net.h:288
std::string m_command
Definition: net.h:740
void clear()
Definition: streams.h:299
const ServiceFlags nLocalServices
Services offered to this peer.
Definition: net.h:1085
int GetExtraOutboundCount()
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
Definition: net.h:47
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type)
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks, tx, addrs, etc)
Definition: net.h:62
uint64_t GetTotalBytesSent()
bool GenerateSelectSet(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set)
void AcceptConnection(const ListenSocket &hListenSocket)
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
void MarkAddressGood(const CAddress &addr)
Definition: net.h:640
boost::optional< T > Optional
Substitute for C++17 std::optional.
Definition: optional.h:14
Information about a peer.
Definition: net.h:840
std::string m_network
Definition: net.h:723
void ForEachNode(const NodeFn &func)
Definition: net.h:279
std::thread threadSocketHandler
Definition: net.h:591
Simple class for background tasks that should be run periodically or once "after a while"...
Definition: scheduler.h:32
We use block-relay-only connections to help prevent against partition attacks.
RecursiveMutex cs_totalBytesRecv
Definition: net.h:475
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
NetPermissionFlags m_permissionFlags
Definition: net.h:710
CConnman(uint64_t seed0, uint64_t seed1, bool network_active=true)
V1TransportDeserializer(const CChainParams &chain_params, const NodeId node_id, int nTypeIn, int nVersionIn)
Definition: net.h:797
RecursiveMutex cs_addrLocal
Definition: net.h:1096
bool IsManualConn() const
Definition: net.h:927
bool fDiscover
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
Definition: net.h:576
void SetVersion(int n)
Definition: streams.h:395
AddrFetch connections are short lived connections used to solicit addresses from peers.
void AddAddressKnown(const CAddress &_addr)
Definition: net.h:1149
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
CNode * AddRef()
Definition: net.h:1136
std::unique_ptr< CSemaphore > semAddnode
Definition: net.h:552
void Init(const Options &connOptions)
Definition: net.h:226
CThreadInterrupt interruptNet
Definition: net.h:588
unsigned int nHdrPos
Definition: net.h:778
CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
const uint64_t nSeed1
Definition: net.h:579
void Stop()
Definition: net.h:261
bool m_use_addrman_outgoing
Definition: net.h:220
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:217
bool IsLocal(const CService &addr)
size_t SocketSendData(CNode *pnode) const
CHash256 & Reset()
Definition: hash.h:42
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
Definition: random.h:190
bool fRelayTxes
Definition: net.h:693
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition: net.h:410
int64_t nLastSend
Definition: net.h:694
RecursiveMutex cs_hSocket
Definition: net.h:857
int64_t m_min_ping_usec
Definition: net.h:714
const int nMyStartingHeight
Definition: net.h:1087
bool m_use_addrman_outgoing
Definition: net.h:565
Cache responses to addr requests to minimize privacy leak.
Definition: net.h:516
int nBestHeight
Definition: net.h:206
std::vector< AddedNodeInfo > GetAddedNodeInfo()
NodeId nodeid
Definition: net.h:691
int64_t nLastRecv
Definition: net.h:695
RecursiveMutex cs_totalBytesSent
Definition: net.h:476
unsigned int nReceiveFloodSize
Definition: net.h:494
std::chrono::microseconds m_next_addr_send GUARDED_BY(cs_sendProcessing)
Definition: net.h:992
std::vector< unsigned char > GetKey() const
Definition: netaddress.cpp:959
std::unique_ptr< TxRelay > m_tx_relay
Definition: net.h:1029
CAddress addr
Definition: net.h:719
Message header.
Definition: protocol.h:28
void ThreadDNSAddressSeed()
int64_t nLastBlockTime
Definition: net.h:697
int64_t m_peer_connect_timeout
Definition: net.h:214
std::unique_ptr< CBloomFilter > pfilter PT_GUARDED_BY(cs_filter) GUARDED_BY(cs_filter)
Definition: net.h:1008