Bitcoin Core  0.20.99
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 <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;
109  CSerializedNetMsg& operator=(CSerializedNetMsg&&) = default;
110  // No copying, only moves.
111  CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
112  CSerializedNetMsg& operator=(const CSerializedNetMsg&) = 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  {
200  ServiceFlags nLocalServices = NODE_NONE;
201  int nMaxConnections = 0;
202  int m_max_outbound_full_relay = 0;
203  int m_max_outbound_block_relay = 0;
204  int nMaxAddnode = 0;
205  int nMaxFeeler = 0;
206  int nBestHeight = 0;
208  NetEventsInterface* m_msgproc = nullptr;
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;
214  int64_t m_peer_connect_timeout = DEFAULT_PEER_CONNECT_TIMEOUT;
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;
220  bool m_use_addrman_outgoing = true;
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);
230  m_max_outbound_block_relay = connOptions.m_max_outbound_block_relay;
231  m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
232  nMaxAddnode = connOptions.nMaxAddnode;
233  nMaxFeeler = connOptions.nMaxFeeler;
234  m_max_outbound = m_max_outbound_full_relay + m_max_outbound_block_relay + nMaxFeeler;
235  nBestHeight = connOptions.nBestHeight;
236  clientInterface = connOptions.uiInterface;
237  m_banman = connOptions.m_banman;
238  m_msgproc = connOptions.m_msgproc;
239  nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
240  nReceiveFloodSize = connOptions.nReceiveFloodSize;
241  m_peer_connect_timeout = connOptions.m_peer_connect_timeout;
242  {
243  LOCK(cs_totalBytesSent);
244  nMaxOutboundTimeframe = connOptions.nMaxOutboundTimeframe;
245  nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
246  }
247  vWhitelistedRange = connOptions.vWhitelistedRange;
248  {
249  LOCK(cs_vAddedNodes);
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; };
269  bool GetUseAddrmanOutgoing() const { return m_use_addrman_outgoing; };
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 
362  ServiceFlags GetLocalServices() const;
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 
383  uint64_t GetMaxOutboundTimeLeftInCycle();
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:
410  inline void AddSocketPermissionFlags(NetPermissionFlags& flags) const { NetPermissions::AddFlag(flags, m_permissions); }
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 
423  void ThreadOpenAddedConnections();
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 
445  bool AttemptToEvictConnection();
446  CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type);
447  void AddWhitelistPermissionFlags(NetPermissionFlags& flags, const CNetAddr &addr) const;
448 
449  void DeleteNode(CNode* pnode);
450 
451  NodeId GetNewNodeId();
452 
453  size_t SocketSendData(CNode *pnode) const;
454  void DumpAddresses();
455 
456  // Network stats
457  void RecordBytesRecv(uint64_t bytes);
458  void RecordBytesSent(uint64_t bytes);
459 
463  std::vector<CAddress> GetCurrentBlockRelayOnlyConns() const;
464 
465  // Whether the node should be passed out in ForEach* callbacks
466  static bool NodeFullyConnected(const CNode* pnode);
467 
468  // Network usage totals
471  uint64_t nTotalBytesRecv GUARDED_BY(cs_totalBytesRecv) {0};
472  uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent) {0};
473 
474  // outbound limit & stats
475  uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent);
476  uint64_t nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent);
477  uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent);
478  uint64_t nMaxOutboundTimeframe GUARDED_BY(cs_totalBytesSent);
479 
480  // P2P timeout in seconds
482 
483  // Whitelisted ranges. Any node connecting from these is automatically
484  // whitelisted (as well as those connecting to whitelisted binds).
485  std::vector<NetWhitelistPermissions> vWhitelistedRange;
486 
487  unsigned int nSendBufferMaxSize{0};
488  unsigned int nReceiveFloodSize{0};
489 
490  std::vector<ListenSocket> vhListenSocket;
491  std::atomic<bool> fNetworkActive{true};
492  bool fAddressesInitialized{false};
494  std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
496  std::vector<std::string> vAddedNodes GUARDED_BY(cs_vAddedNodes);
498  std::vector<CNode*> vNodes GUARDED_BY(cs_vNodes);
499  std::list<CNode*> vNodesDisconnected;
501  std::atomic<NodeId> nLastNodeId{0};
502  unsigned int nPrevNodeCount{0};
503 
511  std::vector<CAddress> m_addrs_response_cache;
512  std::chrono::microseconds m_cache_entry_expiration{0};
513  };
514 
529  std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
530 
544 
545  std::unique_ptr<CSemaphore> semOutbound;
546  std::unique_ptr<CSemaphore> semAddnode;
548 
549  // How many full-relay (tx, block, addr) outbound peers we want
551 
552  // How many block-relay only outbound peers we want
553  // We do not relay tx or addr messages with these peers
555 
560  std::atomic<int> nBestHeight;
565 
570  std::vector<CAddress> m_anchors;
571 
573  const uint64_t nSeed0, nSeed1;
574 
576  bool fMsgProcWake GUARDED_BY(mutexMsgProc);
577 
578  std::condition_variable condMsgProc;
580  std::atomic<bool> flagInterruptMsgProc{false};
581 
583 
584  std::thread threadDNSAddressSeed;
585  std::thread threadSocketHandler;
588  std::thread threadMessageHandler;
589 
593  std::atomic_bool m_try_another_outbound_peer;
594 
595  std::atomic<int64_t> m_next_send_inv_to_incoming{0};
596 
601  std::vector<CService> m_onion_binds;
602 
603  friend struct CConnmanTest;
604  friend struct ConnmanTestMsg;
605 };
606 void Discover();
607 void StartMapPort();
608 void InterruptMapPort();
609 void StopMapPort();
610 uint16_t GetListenPort();
611 
616 {
617 public:
618  virtual bool ProcessMessages(CNode* pnode, std::atomic<bool>& interrupt) = 0;
619  virtual bool SendMessages(CNode* pnode) = 0;
620  virtual void InitializeNode(CNode* pnode) = 0;
621  virtual void FinalizeNode(NodeId id, bool& update_connection_time) = 0;
622 
623 protected:
628  ~NetEventsInterface() = default;
629 };
630 
631 enum
632 {
633  LOCAL_NONE, // unknown
634  LOCAL_IF, // address a local interface listens on
635  LOCAL_BIND, // address explicit bound to
636  LOCAL_UPNP, // address reported by UPnP
637  LOCAL_MANUAL, // address explicitly specified (-externalip=)
638 
640 };
641 
642 bool IsPeerAddrLocalGood(CNode *pnode);
643 void AdvertiseLocal(CNode *pnode);
644 
649 void SetReachable(enum Network net, bool reachable);
651 bool IsReachable(enum Network net);
653 bool IsReachable(const CNetAddr& addr);
654 
655 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
656 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
657 void RemoveLocal(const CService& addr);
658 bool SeenLocal(const CService& addr);
659 bool IsLocal(const CService& addr);
660 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr);
661 CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices);
662 
663 
664 extern bool fDiscover;
665 extern bool fListen;
666 extern bool g_relay_txes;
667 
669 extern std::string strSubVersion;
670 
672  int nScore;
673  int nPort;
674 };
675 
677 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(cs_mapLocalHost);
678 
679 extern const std::string NET_MESSAGE_COMMAND_OTHER;
680 typedef std::map<std::string, uint64_t> mapMsgCmdSize; //command, total bytes
681 
683 {
684 public:
688  int64_t nLastSend;
689  int64_t nLastRecv;
690  int64_t nLastTXTime;
691  int64_t nLastBlockTime;
692  int64_t nTimeConnected;
693  int64_t nTimeOffset;
694  std::string addrName;
695  int nVersion;
696  std::string cleanSubVer;
697  bool fInbound;
700  uint64_t nSendBytes;
701  mapMsgCmdSize mapSendBytesPerMsgCmd;
702  uint64_t nRecvBytes;
703  mapMsgCmdSize mapRecvBytesPerMsgCmd;
706  int64_t m_ping_usec;
710  // Our address, as reported by the peer
711  std::string addrLocal;
712  // Address of this peer
714  // Bind address of our side of the connection
716  // Name of the network the peer connected through
717  std::string m_network;
718  uint32_t m_mapped_as;
719  std::string m_conn_type_string;
720 };
721 
722 
723 
728 class CNetMessage {
729 public:
731  std::chrono::microseconds m_time{0};
732  uint32_t m_message_size{0};
733  uint32_t m_raw_message_size{0};
734  std::string m_command;
735 
736  CNetMessage(CDataStream&& recv_in) : m_recv(std::move(recv_in)) {}
737 
738  void SetVersion(int nVersionIn)
739  {
740  m_recv.SetVersion(nVersionIn);
741  }
742 };
743 
749 public:
750  // returns true if the current deserialization is complete
751  virtual bool Complete() const = 0;
752  // set the serialization context version
753  virtual void SetVersion(int version) = 0;
754  // read and deserialize data
755  virtual int Read(const char *data, unsigned int bytes) = 0;
756  // decomposes a message from the context
757  virtual Optional<CNetMessage> GetMessage(std::chrono::microseconds time, uint32_t& out_err) = 0;
759 };
760 
762 {
763 private:
765  const NodeId m_node_id; // Only for logging
766  mutable CHash256 hasher;
768  bool in_data; // parsing header (false) or data (true)
769  CDataStream hdrbuf; // partially received header
770  CMessageHeader hdr; // complete header
771  CDataStream vRecv; // received message data
772  unsigned int nHdrPos;
773  unsigned int nDataPos;
774 
775  const uint256& GetMessageHash() const;
776  int readHeader(const char *pch, unsigned int nBytes);
777  int readData(const char *pch, unsigned int nBytes);
778 
779  void Reset() {
780  vRecv.clear();
781  hdrbuf.clear();
782  hdrbuf.resize(24);
783  in_data = false;
784  nHdrPos = 0;
785  nDataPos = 0;
786  data_hash.SetNull();
787  hasher.Reset();
788  }
789 
790 public:
791  V1TransportDeserializer(const CChainParams& chain_params, const NodeId node_id, int nTypeIn, int nVersionIn)
792  : m_chain_params(chain_params),
793  m_node_id(node_id),
794  hdrbuf(nTypeIn, nVersionIn),
795  vRecv(nTypeIn, nVersionIn)
796  {
797  Reset();
798  }
799 
800  bool Complete() const override
801  {
802  if (!in_data)
803  return false;
804  return (hdr.nMessageSize == nDataPos);
805  }
806  void SetVersion(int nVersionIn) override
807  {
808  hdrbuf.SetVersion(nVersionIn);
809  vRecv.SetVersion(nVersionIn);
810  }
811  int Read(const char *pch, unsigned int nBytes) override {
812  int ret = in_data ? readData(pch, nBytes) : readHeader(pch, nBytes);
813  if (ret < 0) Reset();
814  return ret;
815  }
816  Optional<CNetMessage> GetMessage(std::chrono::microseconds time, uint32_t& out_err_raw_size) override;
817 };
818 
822 public:
823  // prepare message for transport (header construction, error-correction computation, payload encryption, etc.)
824  virtual void prepareForTransport(CSerializedNetMsg& msg, std::vector<unsigned char>& header) = 0;
825  virtual ~TransportSerializer() {}
826 };
827 
829 public:
830  void prepareForTransport(CSerializedNetMsg& msg, std::vector<unsigned char>& header) override;
831 };
832 
834 class CNode
835 {
836  friend class CConnman;
837  friend struct ConnmanTestMsg;
838 
839 public:
840  std::unique_ptr<TransportDeserializer> m_deserializer;
841  std::unique_ptr<TransportSerializer> m_serializer;
842 
843  // socket
844  std::atomic<ServiceFlags> nServices{NODE_NONE};
845  SOCKET hSocket GUARDED_BY(cs_hSocket);
846  size_t nSendSize{0}; // total size of all vSendMsg entries
847  size_t nSendOffset{0}; // offset inside the first vSendMsg already sent
848  uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
849  std::deque<std::vector<unsigned char>> vSendMsg GUARDED_BY(cs_vSend);
853 
855  std::list<CNetMessage> vProcessMsg GUARDED_BY(cs_vProcessMsg);
856  size_t nProcessQueueSize{0};
857 
859 
860  uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
861 
862  std::atomic<int64_t> nLastSend{0};
863  std::atomic<int64_t> nLastRecv{0};
864  const int64_t nTimeConnected;
865  std::atomic<int64_t> nTimeOffset{0};
866  // Address of this peer
867  const CAddress addr;
868  // Bind address of our side of the connection
870  std::atomic<int> nVersion{0};
876  std::string cleanSubVer GUARDED_BY(cs_SubVer){};
877  bool m_prefer_evict{false}; // This peer is preferred for eviction.
878  bool HasPermission(NetPermissionFlags permission) const {
879  return NetPermissions::HasFlag(m_permissionFlags, permission);
880  }
881  // This boolean is unusued in actual processing, only present for backward compatibility at RPC/QT level
882  bool m_legacyWhitelisted{false};
883  bool fClient{false}; // set by version message
884  bool m_limited_node{false}; //after BIP159, set by version message
889  std::atomic_bool m_wants_addrv2{false};
890  std::atomic_bool fSuccessfullyConnected{false};
891  // Setting fDisconnect to true will cause the node to be disconnected the
892  // next time DisconnectNodes() runs
893  std::atomic_bool fDisconnect{false};
894  bool fSentAddr{false};
896  std::atomic<int> nRefCount{0};
897 
898  const uint64_t nKeyedNetGroup;
899  std::atomic_bool fPauseRecv{false};
900  std::atomic_bool fPauseSend{false};
901 
903  switch (m_conn_type) {
906  return true;
911  return false;
912  } // no default case, so the compiler can warn about missing cases
913 
914  assert(false);
915  }
916 
917  bool IsFullOutboundConn() const {
918  return m_conn_type == ConnectionType::OUTBOUND_FULL_RELAY;
919  }
920 
921  bool IsManualConn() const {
922  return m_conn_type == ConnectionType::MANUAL;
923  }
924 
925  bool IsBlockOnlyConn() const {
926  return m_conn_type == ConnectionType::BLOCK_RELAY;
927  }
928 
929  bool IsFeelerConn() const {
930  return m_conn_type == ConnectionType::FEELER;
931  }
932 
933  bool IsAddrFetchConn() const {
934  return m_conn_type == ConnectionType::ADDR_FETCH;
935  }
936 
937  bool IsInboundConn() const {
938  return m_conn_type == ConnectionType::INBOUND;
939  }
940 
941  /* Whether we send addr messages over this connection */
942  bool RelayAddrsWithConn() const
943  {
944  return m_conn_type != ConnectionType::BLOCK_RELAY;
945  }
946 
947  bool ExpectServicesFromConn() const {
948  switch (m_conn_type) {
952  return false;
956  return true;
957  } // no default case, so the compiler can warn about missing cases
958 
959  assert(false);
960  }
961 
972  Network ConnectedThroughNetwork() const;
973 
974 protected:
975  mapMsgCmdSize mapSendBytesPerMsgCmd;
976  mapMsgCmdSize mapRecvBytesPerMsgCmd GUARDED_BY(cs_vRecv);
977 
978 public:
980  std::atomic<int> nStartingHeight{-1};
981 
982  // flood relay
983  std::vector<CAddress> vAddrToSend;
984  std::unique_ptr<CRollingBloomFilter> m_addr_known{nullptr};
985  bool fGetAddr{false};
986  std::chrono::microseconds m_next_addr_send GUARDED_BY(cs_sendProcessing){0};
987  std::chrono::microseconds m_next_local_addr_send GUARDED_BY(cs_sendProcessing){0};
988 
989  // List of block ids we still have announce.
990  // There is no final sorting before sending, as they are always sent immediately
991  // and in the order requested.
992  std::vector<uint256> vInventoryBlockToSend GUARDED_BY(cs_inventory);
994 
995  struct TxRelay {
997  // We use fRelayTxes for two purposes -
998  // a) it allows us to not relay tx invs before receiving the peer's version message
999  // b) the peer may tell us in its version message that we should not relay tx invs
1000  // unless it loads a bloom filter.
1001  bool fRelayTxes GUARDED_BY(cs_filter){false};
1002  std::unique_ptr<CBloomFilter> pfilter PT_GUARDED_BY(cs_filter) GUARDED_BY(cs_filter){nullptr};
1003 
1004  mutable RecursiveMutex cs_tx_inventory;
1005  CRollingBloomFilter filterInventoryKnown GUARDED_BY(cs_tx_inventory){50000, 0.000001};
1006  // Set of transaction ids we still have to announce.
1007  // They are sorted by the mempool before relay, so the order is not important.
1008  std::set<uint256> setInventoryTxToSend;
1009  // Used for BIP35 mempool sending
1010  bool fSendMempool GUARDED_BY(cs_tx_inventory){false};
1011  // Last time a "MEMPOOL" request was serviced.
1012  std::atomic<std::chrono::seconds> m_last_mempool_req{std::chrono::seconds{0}};
1013  std::chrono::microseconds nNextInvSend{0};
1014 
1016  // Minimum fee rate with which to filter inv's to this node
1017  CAmount minFeeFilter GUARDED_BY(cs_feeFilter){0};
1018  CAmount lastSentFeeFilter{0};
1019  int64_t nextSendTimeFeeFilter{0};
1020  };
1021 
1022  // m_tx_relay == nullptr if we're not relaying transactions with this peer
1023  std::unique_ptr<TxRelay> m_tx_relay;
1024 
1025  // Used for headers announcements - unfiltered blocks to relay
1026  std::vector<uint256> vBlockHashesToAnnounce GUARDED_BY(cs_inventory);
1027 
1033  std::atomic<int64_t> nLastBlockTime{0};
1034 
1039  std::atomic<int64_t> nLastTXTime{0};
1040 
1041  // Ping time measurement:
1042  // The pong reply we're expecting, or 0 if no pong expected.
1043  std::atomic<uint64_t> nPingNonceSent{0};
1045  std::atomic<std::chrono::microseconds> m_ping_start{std::chrono::microseconds{0}};
1046  // Last measured round-trip time.
1047  std::atomic<int64_t> nPingUsecTime{0};
1048  // Best measured round-trip time.
1049  std::atomic<int64_t> nMinPingUsecTime{std::numeric_limits<int64_t>::max()};
1050  // Whether a ping is requested.
1051  std::atomic<bool> fPingQueued{false};
1052 
1053  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);
1054  ~CNode();
1055  CNode(const CNode&) = delete;
1056  CNode& operator=(const CNode&) = delete;
1057 
1058 private:
1059  const NodeId id;
1060  const uint64_t nLocalHostNonce;
1062  std::atomic<int> m_greatest_common_version{INIT_PROTO_VERSION};
1063 
1080 
1082  NetPermissionFlags m_permissionFlags{ PF_NONE };
1083  std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
1084 
1086  std::string addrName GUARDED_BY(cs_addrName);
1087 
1088  // Our address, as reported by the peer
1089  CService addrLocal GUARDED_BY(cs_addrLocal);
1091 
1093  const bool m_inbound_onion{false};
1094 
1095 public:
1096 
1097  NodeId GetId() const {
1098  return id;
1099  }
1100 
1101  uint64_t GetLocalNonce() const {
1102  return nLocalHostNonce;
1103  }
1104 
1105  int GetMyStartingHeight() const {
1106  return nMyStartingHeight;
1107  }
1108 
1109  int GetRefCount() const
1110  {
1111  assert(nRefCount >= 0);
1112  return nRefCount;
1113  }
1114 
1115  bool ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool& complete);
1116 
1117  void SetCommonVersion(int greatest_common_version)
1118  {
1119  m_greatest_common_version = greatest_common_version;
1120  }
1121  int GetCommonVersion() const
1122  {
1123  return m_greatest_common_version;
1124  }
1125 
1126  CService GetAddrLocal() const;
1128  void SetAddrLocal(const CService& addrLocalIn);
1129 
1131  {
1132  nRefCount++;
1133  return this;
1134  }
1135 
1136  void Release()
1137  {
1138  nRefCount--;
1139  }
1140 
1141 
1142 
1143  void AddAddressKnown(const CAddress& _addr)
1144  {
1145  assert(m_addr_known);
1146  m_addr_known->insert(_addr.GetKey());
1147  }
1148 
1149  void PushAddress(const CAddress& _addr, FastRandomContext &insecure_rand)
1150  {
1151  // Whether the peer supports the address in `_addr`. For example,
1152  // nodes that do not implement BIP155 cannot receive Tor v3 addresses
1153  // because they require ADDRv2 (BIP155) encoding.
1154  const bool addr_format_supported = m_wants_addrv2 || _addr.IsAddrV1Compatible();
1155 
1156  // Known checking here is only to save space from duplicates.
1157  // SendMessages will filter it again for knowns that were added
1158  // after addresses were pushed.
1159  assert(m_addr_known);
1160  if (_addr.IsValid() && !m_addr_known->contains(_addr.GetKey()) && addr_format_supported) {
1161  if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
1162  vAddrToSend[insecure_rand.randrange(vAddrToSend.size())] = _addr;
1163  } else {
1164  vAddrToSend.push_back(_addr);
1165  }
1166  }
1167  }
1168 
1169 
1170  void AddKnownTx(const uint256& hash)
1171  {
1172  if (m_tx_relay != nullptr) {
1173  LOCK(m_tx_relay->cs_tx_inventory);
1174  m_tx_relay->filterInventoryKnown.insert(hash);
1175  }
1176  }
1177 
1178  void PushTxInventory(const uint256& hash)
1179  {
1180  if (m_tx_relay == nullptr) return;
1181  LOCK(m_tx_relay->cs_tx_inventory);
1182  if (!m_tx_relay->filterInventoryKnown.contains(hash)) {
1183  m_tx_relay->setInventoryTxToSend.insert(hash);
1184  }
1185  }
1186 
1187  void CloseSocketDisconnect();
1188 
1189  void copyStats(CNodeStats &stats, const std::vector<bool> &m_asmap);
1190 
1192  {
1193  return nLocalServices;
1194  }
1195 
1196  std::string GetAddrName() const;
1198  void MaybeSetAddrName(const std::string& addrNameIn);
1199 
1200  std::string ConnectionTypeAsString() const;
1201 };
1202 
1204 int64_t PoissonNextSend(int64_t now, int average_interval_seconds);
1205 
1207 inline std::chrono::microseconds PoissonNextSend(std::chrono::microseconds now, std::chrono::seconds average_interval)
1208 {
1209  return std::chrono::microseconds{PoissonNextSend(now.count(), average_interval.count())};
1210 }
1211 
1212 #endif // BITCOIN_NET_H
std::vector< CService > vBinds
Definition: net.h:218
int m_max_outbound_full_relay
Definition: net.h:202
uint256 data_hash
Definition: net.h:767
std::vector< CAddress > m_addrs_response_cache
Definition: net.h:511
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:472
int nMaxFeeler
Definition: net.h:557
std::vector< bool > m_asmap
Definition: net.h:223
bool IsReachable(enum Network net)
Definition: net.cpp:282
int nStartingHeight
Definition: net.h:699
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 m_max_outbound
Definition: net.h:558
mapMsgCmdSize mapRecvBytesPerMsgCmd
Definition: net.h:703
const std::chrono::seconds now
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:841
RecursiveMutex cs_vNodes
Definition: net.h:500
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:876
int64_t nTimeOffset
Definition: net.h:693
int64_t m_ping_usec
Definition: net.h:706
bool fListen
Definition: net.cpp:113
int m_max_outbound_block_relay
Definition: net.h:203
We open manual connections to addresses that users explicitly inputted via the addnode RPC...
uint32_t m_mapped_as
Definition: net.h:718
std::atomic< int > nBestHeight
Definition: net.h:560
bool fRelayTxes GUARDED_BY(cs_filter)
Definition: net.h:1001
bool m_legacyWhitelisted
Definition: net.h:705
Bilingual messages:
Definition: translation.h:16
const std::string NET_MESSAGE_COMMAND_OTHER
Definition: net.cpp:104
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(cs_mapLocalHost)
void SetVersion(int nVersionIn) override
Definition: net.h:806
void PushTxInventory(const uint256 &hash)
Definition: net.h:1178
BanMan * m_banman
Definition: net.h:209
Mutex mutexMsgProc
Definition: net.h:579
static const bool DEFAULT_FORCEDNSSEED
Definition: net.h:88
const uint64_t nKeyedNetGroup
Definition: net.h:898
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:294
mapMsgCmdSize mapSendBytesPerMsgCmd
Definition: net.h:975
CDataStream hdrbuf
Definition: net.h:769
bool IsOutboundOrBlockRelayConn() const
Definition: net.h:902
void StartMapPort()
Definition: net.cpp:1664
void StopMapPort()
Definition: net.cpp:1672
std::vector< unsigned char > data
Definition: net.h:114
unsigned int nDataPos
Definition: net.h:773
const ConnectionType m_conn_type
Definition: net.h:1061
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:485
CAmount minFeeFilter GUARDED_BY(cs_feeFilter)
Definition: net.h:1017
bool IsFeelerConn() const
Definition: net.h:929
unsigned int nReceiveFloodSize
Definition: net.h:211
uint16_t GetListenPort()
Definition: net.cpp:126
RecursiveMutex cs_filter
Definition: net.h:996
int m_max_outbound_full_relay
Definition: net.h:550
mapMsgCmdSize mapSendBytesPerMsgCmd
Definition: net.h:701
CClientUIInterface * uiInterface
Definition: net.h:207
void resize(size_type n, value_type c=0)
Definition: streams.h:295
bool g_relay_txes
Definition: net.cpp:114
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:601
void SetAsmap(std::vector< bool > asmap)
Definition: net.h:404
ServiceFlags nServices
Definition: net.h:686
Mutex cs_inventory
Definition: net.h:993
CDataStream m_recv
received message data
Definition: net.h:730
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:70
CNetMessage(CDataStream &&recv_in)
Definition: net.h:736
int nMaxAddnode
Definition: net.h:556
RAII-style semaphore lock.
Definition: sync.h:296
void SetCommonVersion(int greatest_common_version)
Definition: net.h:1117
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:64
RecursiveMutex cs_vProcessMsg
Definition: net.h:854
std::string cleanSubVer
Definition: net.h:696
Interface for message handling.
Definition: net.h:615
void SetVersion(int nVersionIn)
Definition: net.h:738
RecursiveMutex cs_addrName
Definition: net.h:1085
RollingBloomFilter is a probabilistic "keep track of most recently inserted" set. ...
Definition: bloom.h:99
NetEventsInterface * m_msgproc
Definition: net.h:562
CAmount minFeeFilter
Definition: net.h:709
int nMaxConnections
Definition: net.h:201
int64_t nTimeConnected
Definition: net.h:692
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:52
void ForEachNode(const NodeFn &func) const
Definition: net.h:288
void AdvertiseLocal(CNode *pnode)
Definition: net.cpp:209
int m_max_outbound_block_relay
Definition: net.h:554
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:202
uint32_t nMessageSize
Definition: protocol.h:54
A hasher class for Bitcoin&#39;s 256-bit hash (double SHA-256).
Definition: hash.h:24
uint64_t GetLocalNonce() const
Definition: net.h:1101
std::unique_ptr< TransportDeserializer > m_deserializer
Definition: net.h:840
std::vector< CAddress > vAddrToSend
Definition: net.h:983
void PushAddress(const CAddress &_addr, FastRandomContext &insecure_rand)
Definition: net.h:1149
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:852
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Definition: net.h:848
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:639
Signals for UI communication.
Definition: ui_interface.h:24
std::list< CNetMessage > vRecvMsg
Definition: net.h:1083
const NodeId m_node_id
Definition: net.h:765
CAddrMan addrman
Definition: net.h:493
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:529
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition: net.h:68
bool fConnected
Definition: net.h:98
virtual ~TransportDeserializer()
Definition: net.h:758
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition: net.h:410
int GetRefCount() const
Definition: net.h:1109
RecursiveMutex cs_sendProcessing
Definition: net.h:858
ServiceFlags nLocalServices
Services this instance offers.
Definition: net.h:543
bool IsValid() const
Definition: netaddress.cpp:428
bool m_manual_connection
Definition: net.h:698
CHash256 hasher
Definition: net.h:766
Stochastical (IP) address manager.
Definition: addrman.h:171
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:89
int64_t nLastTXTime
Definition: net.h:690
int GetMyStartingHeight() const
Definition: net.h:1105
std::chrono::microseconds m_next_local_addr_send GUARDED_BY(cs_sendProcessing)
Definition: net.h:987
ServiceFlags GetLocalServices() const
Definition: net.h:1191
int nVersion
Definition: net.h:695
void InterruptMapPort()
Definition: net.cpp:1668
int64_t m_ping_wait_usec
Definition: net.h:707
void Release()
Definition: net.h:1136
bool GetLocal(CService &addr, const CNetAddr *paddrPeer=nullptr)
Definition: net.cpp:132
std::condition_variable condMsgProc
Definition: net.h:578
RecursiveMutex cs_vAddedNodes
Definition: net.h:497
void Interrupt(NodeContext &node)
Interrupt threads.
Definition: init.cpp:162
ListenSocket(SOCKET socket_, NetPermissionFlags permissions_)
Definition: net.h:411
std::thread threadOpenAddedConnections
Definition: net.h:586
#define LOCK(cs)
Definition: sync.h:230
RecursiveMutex m_addr_fetches_mutex
Definition: net.h:495
bool IsPeerAddrLocalGood(CNode *pnode)
Definition: net.cpp:201
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:501
Fast randomness source.
Definition: random.h:119
Transport protocol agnostic message container.
Definition: net.h:728
const CAddress addrBind
Definition: net.h:869
std::vector< std::string > vSeedNodes
Definition: net.h:215
std::vector< std::string > m_specified_outgoing
Definition: net.h:221
int64_t m_peer_connect_timeout
Definition: net.h:481
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:545
std::thread threadMessageHandler
Definition: net.h:588
bool RelayAddrsWithConn() const
Definition: net.h:942
static bool HasFlag(const NetPermissionFlags &flags, NetPermissionFlags f)
void ForEachNodeThen(Callable &&pre, CallableAfter &&post)
Definition: net.h:298
bool fInbound
Definition: net.h:697
bool IsManualConn() const
Definition: net.h:921
A CService with information about it as peer.
Definition: protocol.h:360
uint64_t nRecvBytes
Definition: net.h:702
std::vector< unsigned char > GetKey() const
Definition: netaddress.cpp:955
int Read(const char *pch, unsigned int nBytes) override
Definition: net.h:811
RecursiveMutex cs_mapLocalHost
Definition: net.cpp:115
bool fInbound
Definition: net.h:99
std::string addrName
Definition: net.h:694
int nMaxFeeler
Definition: net.h:205
Network
A network type.
Definition: netaddress.h:43
bool ExpectServicesFromConn() const
Definition: net.h:947
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:593
int64_t NodeId
Definition: net.h:92
Definition: net.h:187
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:78
bool GetNetworkActive() const
Definition: net.h:268
NumConnections
Definition: net.h:191
CClientUIInterface * clientInterface
Definition: net.h:561
NodeId GetId() const
Definition: net.h:1097
uint64_t nSendBytes
Definition: net.h:700
int nMaxConnections
Definition: net.h:547
The TransportSerializer prepares messages for the network transport.
Definition: net.h:821
NetPermissionFlags
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Definition: net.h:860
void Discover()
Definition: net.cpp:2296
Inbound connections are those initiated by a peer.
RecursiveMutex cs_SubVer
Definition: net.h:871
unsigned int SOCKET
Definition: compat.h:45
NetPermissionFlags m_permissions
Definition: net.h:413
const CAddress addr
Definition: net.h:867
bool Complete() const override
Definition: net.h:800
bool IsBlockOnlyConn() const
Definition: net.h:925
CDataStream vRecv
Definition: net.h:771
const int64_t nTimeConnected
Definition: net.h:864
CMessageHeader hdr
Definition: net.h:770
virtual ~TransportSerializer()
Definition: net.h:825
int flags
Definition: bitcoin-tx.cpp:506
uint64_t nMaxOutboundTimeframe
Definition: net.h:212
Network address.
Definition: netaddress.h:119
RecursiveMutex cs_feeFilter
Definition: net.h:1015
std::list< CNode * > vNodesDisconnected
Definition: net.h:499
256-bit opaque blob.
Definition: uint256.h:124
void RemoveLocal(const CService &addr)
Definition: net.cpp:267
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:216
std::vector< CService > onion_binds
Definition: net.h:219
int nScore
Definition: net.h:672
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
Definition: net.h:49
int nMaxAddnode
Definition: net.h:204
void AddKnownTx(const uint256 &hash)
Definition: net.h:1170
BanMan * m_banman
Pointer to this node&#39;s banman.
Definition: net.h:564
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:90
CAddress addrBind
Definition: net.h:715
bool fSendMempool GUARDED_BY(cs_tx_inventory)
Definition: net.h:1010
CService resolvedAddress
Definition: net.h:97
std::thread threadOpenConnections
Definition: net.h:587
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
CSemaphoreGrant grantOutbound
Definition: net.h:895
The TransportDeserializer takes care of holding and deserializing the network receive buffer...
Definition: net.h:748
const CChainParams & m_chain_params
Definition: net.h:764
uint256 hashContinue
Definition: net.h:979
std::map< std::string, uint64_t > mapMsgCmdSize
Definition: net.h:680
const NodeId id
Definition: net.h:1059
Feeler connections are short-lived connections made to check that a node is alive.
std::string addrLocal
Definition: net.h:711
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
std::thread threadDNSAddressSeed
Definition: net.h:584
ServiceFlags nLocalServices
Definition: net.h:200
uint64_t nMaxOutboundLimit
Definition: net.h:213
std::vector< std::string > m_added_nodes
Definition: net.h:222
RecursiveMutex cs_vSend
Definition: net.h:850
int64_t PoissonNextSend(int64_t now, int average_interval_seconds)
Return a timestamp in the future (in microseconds) for exponentially distributed events.
Definition: net.cpp:3031
std::vector< ListenSocket > vhListenSocket
Definition: net.h:490
void ForEachNodeThen(Callable &&pre, CallableAfter &&post) const
Definition: net.h:309
SipHash-2-4.
Definition: siphash.h:13
std::string m_conn_type_string
Definition: net.h:719
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:471
static const bool DEFAULT_UPNP
-upnp default
Definition: net.h:75
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition: net.h:86
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:84
const uint64_t nLocalHostNonce
Definition: net.h:1060
unsigned int nSendBufferMaxSize
Definition: net.h:210
std::string m_command
Definition: net.h:734
void clear()
Definition: streams.h:299
const ServiceFlags nLocalServices
Services offered to this peer.
Definition: net.h:1079
bool IsAddrFetchConn() const
Definition: net.h:933
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
Definition: net.h:47
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we&#39;ll relay everything (blocks, tx, addrs, etc)
Definition: net.h:62
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:118
CClientUIInterface uiInterface
Definition: net.h:634
boost::optional< T > Optional
Substitute for C++17 std::optional.
Definition: optional.h:14
Information about a peer.
Definition: net.h:834
std::string m_network
Definition: net.h:717
void ForEachNode(const NodeFn &func)
Definition: net.h:279
std::thread threadSocketHandler
Definition: net.h:585
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:469
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:274
NetPermissionFlags m_permissionFlags
Definition: net.h:704
V1TransportDeserializer(const CChainParams &chain_params, const NodeId node_id, int nTypeIn, int nVersionIn)
Definition: net.h:791
RecursiveMutex cs_addrLocal
Definition: net.h:1090
bool fDiscover
Definition: net.cpp:112
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
Definition: net.h:570
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:1143
int GetCommonVersion() const
Definition: net.h:1121
CNode * AddRef()
Definition: net.h:1130
std::unique_ptr< CSemaphore > semAddnode
Definition: net.h:546
bool IsAddrV1Compatible() const
Check if the current object can be serialized in pre-ADDRv2/BIP155 format.
Definition: netaddress.cpp:477
void Init(const Options &connOptions)
Definition: net.h:226
CThreadInterrupt interruptNet
Definition: net.h:582
unsigned int nHdrPos
Definition: net.h:772
static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections)
bool HasPermission(NetPermissionFlags permission) const
Definition: net.h:878
CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
Definition: net.cpp:181
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
Definition: net.cpp:236
bool IsInboundConn() const
Definition: net.h:937
const uint64_t nSeed1
Definition: net.h:573
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)
check whether a given address is potentially local
Definition: net.cpp:307
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 GetUseAddrmanOutgoing() const
Definition: net.h:269
bool fRelayTxes
Definition: net.h:687
int64_t nLastSend
Definition: net.h:688
RecursiveMutex cs_hSocket
Definition: net.h:851
int64_t m_min_ping_usec
Definition: net.h:708
const int nMyStartingHeight
Definition: net.h:1081
bool m_use_addrman_outgoing
Definition: net.h:559
Cache responses to addr requests to minimize privacy leak.
Definition: net.h:510
bool IsFullOutboundConn() const
Definition: net.h:917
int nBestHeight
Definition: net.h:206
NodeId nodeid
Definition: net.h:685
int64_t nLastRecv
Definition: net.h:689
RecursiveMutex cs_totalBytesSent
Definition: net.h:470
std::chrono::microseconds m_next_addr_send GUARDED_BY(cs_sendProcessing)
Definition: net.h:986
std::unique_ptr< TxRelay > m_tx_relay
Definition: net.h:1023
CAddress addr
Definition: net.h:713
Message header.
Definition: protocol.h:28
int64_t nLastBlockTime
Definition: net.h:691
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:1002