Bitcoin Core  0.18.99
P2P Digital Currency
net.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2019 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 <compat.h>
14 #include <crypto/siphash.h>
15 #include <hash.h>
16 #include <limitedmap.h>
17 #include <netaddress.h>
18 #include <net_permissions.h>
19 #include <policy/feerate.h>
20 #include <protocol.h>
21 #include <random.h>
22 #include <streams.h>
23 #include <sync.h>
24 #include <uint256.h>
25 #include <threadinterrupt.h>
26 
27 #include <atomic>
28 #include <deque>
29 #include <stdint.h>
30 #include <thread>
31 #include <memory>
32 #include <condition_variable>
33 
34 #ifndef WIN32
35 #include <arpa/inet.h>
36 #endif
37 
38 
39 class CScheduler;
40 class CNode;
41 class BanMan;
42 
44 static const bool DEFAULT_WHITELISTRELAY = true;
46 static const bool DEFAULT_WHITELISTFORCERELAY = false;
47 
49 static const int PING_INTERVAL = 2 * 60;
51 static const int TIMEOUT_INTERVAL = 20 * 60;
53 static const int FEELER_INTERVAL = 120;
55 static const unsigned int MAX_INV_SZ = 50000;
57 static const unsigned int MAX_LOCATOR_SZ = 101;
59 static const unsigned int MAX_ADDR_TO_SEND = 1000;
61 static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
63 static const unsigned int MAX_SUBVERSION_LENGTH = 256;
65 static const int MAX_OUTBOUND_CONNECTIONS = 8;
67 static const int MAX_ADDNODE_CONNECTIONS = 8;
69 static const bool DEFAULT_LISTEN = true;
71 #ifdef USE_UPNP
72 static const bool DEFAULT_UPNP = USE_UPNP;
73 #else
74 static const bool DEFAULT_UPNP = false;
75 #endif
76 
77 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
79 static const uint64_t DEFAULT_MAX_UPLOAD_TARGET = 0;
81 static const uint64_t MAX_UPLOAD_TIMEFRAME = 60 * 60 * 24;
83 static const bool DEFAULT_BLOCKSONLY = false;
85 static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
86 
87 static const bool DEFAULT_FORCEDNSSEED = false;
88 static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
89 static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
90 
91 typedef int64_t NodeId;
92 
94 {
95  std::string strAddedNode;
97  bool fConnected;
98  bool fInbound;
99 };
100 
101 class CNodeStats;
102 class CClientUIInterface;
103 
105 {
106  CSerializedNetMsg() = default;
108  CSerializedNetMsg& operator=(CSerializedNetMsg&&) = default;
109  // No copying, only moves.
110  CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
111  CSerializedNetMsg& operator=(const CSerializedNetMsg&) = delete;
112 
113  std::vector<unsigned char> data;
114  std::string command;
115 };
116 
117 
118 class NetEventsInterface;
119 class CConnman
120 {
121 public:
122 
125  CONNECTIONS_IN = (1U << 0),
126  CONNECTIONS_OUT = (1U << 1),
128  };
129 
130  struct Options
131  {
132  ServiceFlags nLocalServices = NODE_NONE;
133  int nMaxConnections = 0;
134  int nMaxOutbound = 0;
135  int nMaxAddnode = 0;
136  int nMaxFeeler = 0;
137  int nBestHeight = 0;
139  NetEventsInterface* m_msgproc = nullptr;
140  BanMan* m_banman = nullptr;
141  unsigned int nSendBufferMaxSize = 0;
142  unsigned int nReceiveFloodSize = 0;
143  uint64_t nMaxOutboundTimeframe = 0;
144  uint64_t nMaxOutboundLimit = 0;
145  int64_t m_peer_connect_timeout = DEFAULT_PEER_CONNECT_TIMEOUT;
146  std::vector<std::string> vSeedNodes;
147  std::vector<NetWhitelistPermissions> vWhitelistedRange;
148  std::vector<NetWhitebindPermissions> vWhiteBinds;
149  std::vector<CService> vBinds;
150  bool m_use_addrman_outgoing = true;
151  std::vector<std::string> m_specified_outgoing;
152  std::vector<std::string> m_added_nodes;
153  };
154 
155  void Init(const Options& connOptions) {
156  nLocalServices = connOptions.nLocalServices;
157  nMaxConnections = connOptions.nMaxConnections;
158  nMaxOutbound = std::min(connOptions.nMaxOutbound, connOptions.nMaxConnections);
159  m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
160  nMaxAddnode = connOptions.nMaxAddnode;
161  nMaxFeeler = connOptions.nMaxFeeler;
162  nBestHeight = connOptions.nBestHeight;
163  clientInterface = connOptions.uiInterface;
164  m_banman = connOptions.m_banman;
165  m_msgproc = connOptions.m_msgproc;
166  nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
167  nReceiveFloodSize = connOptions.nReceiveFloodSize;
168  m_peer_connect_timeout = connOptions.m_peer_connect_timeout;
169  {
170  LOCK(cs_totalBytesSent);
171  nMaxOutboundTimeframe = connOptions.nMaxOutboundTimeframe;
172  nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
173  }
174  vWhitelistedRange = connOptions.vWhitelistedRange;
175  {
176  LOCK(cs_vAddedNodes);
177  vAddedNodes = connOptions.m_added_nodes;
178  }
179  }
180 
181  CConnman(uint64_t seed0, uint64_t seed1);
182  ~CConnman();
183  bool Start(CScheduler& scheduler, const Options& options);
184 
185  // TODO: Remove NO_THREAD_SAFETY_ANALYSIS. Lock cs_vNodes before reading the variable vNodes.
186  //
187  // When removing NO_THREAD_SAFETY_ANALYSIS be aware of the following lock order requirements:
188  // * CheckForStaleTipAndEvictPeers locks cs_main before indirectly calling GetExtraOutboundCount
189  // which locks cs_vNodes.
190  // * ProcessMessage locks cs_main and g_cs_orphans before indirectly calling ForEachNode which
191  // locks cs_vNodes.
192  //
193  // Thus the implicit locking order requirement is: (1) cs_main, (2) g_cs_orphans, (3) cs_vNodes.
194  void Stop() NO_THREAD_SAFETY_ANALYSIS;
195 
196  void Interrupt();
197  bool GetNetworkActive() const { return fNetworkActive; };
198  bool GetUseAddrmanOutgoing() const { return m_use_addrman_outgoing; };
199  void SetNetworkActive(bool active);
200  void OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound = nullptr, const char *strDest = nullptr, bool fOneShot = false, bool fFeeler = false, bool manual_connection = false);
201  bool CheckIncomingNonce(uint64_t nonce);
202 
203  bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
204 
205  void PushMessage(CNode* pnode, CSerializedNetMsg&& msg);
206 
207  template<typename Callable>
208  void ForEachNode(Callable&& func)
209  {
210  LOCK(cs_vNodes);
211  for (auto&& node : vNodes) {
212  if (NodeFullyConnected(node))
213  func(node);
214  }
215  };
216 
217  template<typename Callable>
218  void ForEachNode(Callable&& func) const
219  {
220  LOCK(cs_vNodes);
221  for (auto&& node : vNodes) {
222  if (NodeFullyConnected(node))
223  func(node);
224  }
225  };
226 
227  template<typename Callable, typename CallableAfter>
228  void ForEachNodeThen(Callable&& pre, CallableAfter&& post)
229  {
230  LOCK(cs_vNodes);
231  for (auto&& node : vNodes) {
232  if (NodeFullyConnected(node))
233  pre(node);
234  }
235  post();
236  };
237 
238  template<typename Callable, typename CallableAfter>
239  void ForEachNodeThen(Callable&& pre, CallableAfter&& post) const
240  {
241  LOCK(cs_vNodes);
242  for (auto&& node : vNodes) {
243  if (NodeFullyConnected(node))
244  pre(node);
245  }
246  post();
247  };
248 
249  // Addrman functions
250  size_t GetAddressCount() const;
251  void SetServices(const CService &addr, ServiceFlags nServices);
252  void MarkAddressGood(const CAddress& addr);
253  void AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
254  std::vector<CAddress> GetAddresses();
255 
256  // This allows temporarily exceeding nMaxOutbound, with the goal of finding
257  // a peer that is better than all our current peers.
258  void SetTryNewOutboundPeer(bool flag);
259  bool GetTryNewOutboundPeer();
260 
261  // Return the number of outbound peers we have in excess of our target (eg,
262  // if we previously called SetTryNewOutboundPeer(true), and have since set
263  // to false, we may have extra peers that we wish to disconnect). This may
264  // return a value less than (num_outbound_connections - num_outbound_slots)
265  // in cases where some outbound connections are not yet fully connected, or
266  // not yet fully disconnected.
267  int GetExtraOutboundCount();
268 
269  bool AddNode(const std::string& node);
270  bool RemoveAddedNode(const std::string& node);
271  std::vector<AddedNodeInfo> GetAddedNodeInfo();
272 
273  size_t GetNodeCount(NumConnections num);
274  void GetNodeStats(std::vector<CNodeStats>& vstats);
275  bool DisconnectNode(const std::string& node);
276  bool DisconnectNode(const CSubNet& subnet);
277  bool DisconnectNode(const CNetAddr& addr);
278  bool DisconnectNode(NodeId id);
279 
280  ServiceFlags GetLocalServices() const;
281 
283  void SetMaxOutboundTarget(uint64_t limit);
284  uint64_t GetMaxOutboundTarget();
285 
287  void SetMaxOutboundTimeframe(uint64_t timeframe);
288  uint64_t GetMaxOutboundTimeframe();
289 
293  bool OutboundTargetReached(bool historicalBlockServingLimit);
294 
297  uint64_t GetOutboundTargetBytesLeft();
298 
301  uint64_t GetMaxOutboundTimeLeftInCycle();
302 
303  uint64_t GetTotalBytesRecv();
304  uint64_t GetTotalBytesSent();
305 
306  void SetBestHeight(int height);
307  int GetBestHeight() const;
308 
310  CSipHasher GetDeterministicRandomizer(uint64_t id) const;
311 
312  unsigned int GetReceiveFloodSize() const;
313 
314  void WakeMessageHandler();
315 
320  int64_t PoissonNextSendInbound(int64_t now, int average_interval_seconds);
321 
322 private:
323  struct ListenSocket {
324  public:
326  inline void AddSocketPermissionFlags(NetPermissionFlags& flags) const { NetPermissions::AddFlag(flags, m_permissions); }
327  ListenSocket(SOCKET socket_, NetPermissionFlags permissions_) : socket(socket_), m_permissions(permissions_) {}
328  private:
330  };
331 
332  bool BindListenPort(const CService& bindAddr, std::string& strError, NetPermissionFlags permissions);
333  bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions);
334  bool InitBinds(const std::vector<CService>& binds, const std::vector<NetWhitebindPermissions>& whiteBinds);
335  void ThreadOpenAddedConnections();
336  void AddOneShot(const std::string& strDest);
337  void ProcessOneShot();
338  void ThreadOpenConnections(std::vector<std::string> connect);
339  void ThreadMessageHandler();
340  void AcceptConnection(const ListenSocket& hListenSocket);
341  void DisconnectNodes();
343  void InactivityCheck(CNode *pnode);
344  bool GenerateSelectSet(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set);
345  void SocketEvents(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set);
346  void SocketHandler();
347  void ThreadSocketHandler();
348  void ThreadDNSAddressSeed();
349 
350  uint64_t CalculateKeyedNetGroup(const CAddress& ad) const;
351 
352  CNode* FindNode(const CNetAddr& ip);
353  CNode* FindNode(const CSubNet& subNet);
354  CNode* FindNode(const std::string& addrName);
355  CNode* FindNode(const CService& addr);
356 
357  bool AttemptToEvictConnection();
358  CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, bool manual_connection);
359  void AddWhitelistPermissionFlags(NetPermissionFlags& flags, const CNetAddr &addr) const;
360 
361  void DeleteNode(CNode* pnode);
362 
363  NodeId GetNewNodeId();
364 
365  size_t SocketSendData(CNode *pnode) const;
366  void DumpAddresses();
367 
368  // Network stats
369  void RecordBytesRecv(uint64_t bytes);
370  void RecordBytesSent(uint64_t bytes);
371 
372  // Whether the node should be passed out in ForEach* callbacks
373  static bool NodeFullyConnected(const CNode* pnode);
374 
375  // Network usage totals
378  uint64_t nTotalBytesRecv GUARDED_BY(cs_totalBytesRecv);
379  uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent);
380 
381  // outbound limit & stats
382  uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent);
383  uint64_t nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent);
384  uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent);
385  uint64_t nMaxOutboundTimeframe GUARDED_BY(cs_totalBytesSent);
386 
387  // P2P timeout in seconds
389 
390  // Whitelisted ranges. Any node connecting from these is automatically
391  // whitelisted (as well as those connecting to whitelisted binds).
392  std::vector<NetWhitelistPermissions> vWhitelistedRange;
393 
394  unsigned int nSendBufferMaxSize{0};
395  unsigned int nReceiveFloodSize{0};
396 
397  std::vector<ListenSocket> vhListenSocket;
398  std::atomic<bool> fNetworkActive{true};
399  bool fAddressesInitialized{false};
401  std::deque<std::string> vOneShots GUARDED_BY(cs_vOneShots);
403  std::vector<std::string> vAddedNodes GUARDED_BY(cs_vAddedNodes);
405  std::vector<CNode*> vNodes GUARDED_BY(cs_vNodes);
406  std::list<CNode*> vNodesDisconnected;
408  std::atomic<NodeId> nLastNodeId{0};
409  unsigned int nPrevNodeCount{0};
410 
413 
414  std::unique_ptr<CSemaphore> semOutbound;
415  std::unique_ptr<CSemaphore> semAddnode;
421  std::atomic<int> nBestHeight;
425 
427  const uint64_t nSeed0, nSeed1;
428 
431 
432  std::condition_variable condMsgProc;
434  std::atomic<bool> flagInterruptMsgProc{false};
435 
437 
438  std::thread threadDNSAddressSeed;
439  std::thread threadSocketHandler;
442  std::thread threadMessageHandler;
443 
447  std::atomic_bool m_try_another_outbound_peer;
448 
449  std::atomic<int64_t> m_next_send_inv_to_incoming{0};
450 
451  friend struct CConnmanTest;
452 };
453 extern std::unique_ptr<CConnman> g_connman;
454 extern std::unique_ptr<BanMan> g_banman;
455 void Discover();
456 void StartMapPort();
457 void InterruptMapPort();
458 void StopMapPort();
459 unsigned short GetListenPort();
460 
462 {
463  typedef bool result_type;
464 
465  template<typename I>
466  bool operator()(I first, I last) const
467  {
468  while (first != last) {
469  if (!(*first)) return false;
470  ++first;
471  }
472  return true;
473  }
474 };
475 
480 {
481 public:
482  virtual bool ProcessMessages(CNode* pnode, std::atomic<bool>& interrupt) = 0;
483  virtual bool SendMessages(CNode* pnode) = 0;
484  virtual void InitializeNode(CNode* pnode) = 0;
485  virtual void FinalizeNode(NodeId id, bool& update_connection_time) = 0;
486 
487 protected:
492  ~NetEventsInterface() = default;
493 };
494 
495 enum
496 {
497  LOCAL_NONE, // unknown
498  LOCAL_IF, // address a local interface listens on
499  LOCAL_BIND, // address explicit bound to
500  LOCAL_UPNP, // address reported by UPnP
501  LOCAL_MANUAL, // address explicitly specified (-externalip=)
502 
504 };
505 
506 bool IsPeerAddrLocalGood(CNode *pnode);
507 void AdvertiseLocal(CNode *pnode);
508 
513 void SetReachable(enum Network net, bool reachable);
515 bool IsReachable(enum Network net);
517 bool IsReachable(const CNetAddr& addr);
518 
519 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
520 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
521 void RemoveLocal(const CService& addr);
522 bool SeenLocal(const CService& addr);
523 bool IsLocal(const CService& addr);
524 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr);
525 CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices);
526 
527 
528 extern bool fDiscover;
529 extern bool fListen;
530 extern bool g_relay_txes;
531 
533 extern std::string strSubVersion;
534 
536  int nScore;
537  int nPort;
538 };
539 
541 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(cs_mapLocalHost);
542 
543 extern const std::string NET_MESSAGE_COMMAND_OTHER;
544 typedef std::map<std::string, uint64_t> mapMsgCmdSize; //command, total bytes
545 
547 {
548 public:
552  int64_t nLastSend;
553  int64_t nLastRecv;
554  int64_t nTimeConnected;
555  int64_t nTimeOffset;
556  std::string addrName;
557  int nVersion;
558  std::string cleanSubVer;
559  bool fInbound;
562  uint64_t nSendBytes;
563  mapMsgCmdSize mapSendBytesPerMsgCmd;
564  uint64_t nRecvBytes;
565  mapMsgCmdSize mapRecvBytesPerMsgCmd;
568  double dPingTime;
569  double dPingWait;
570  double dMinPing;
572  // Our address, as reported by the peer
573  std::string addrLocal;
574  // Address of this peer
576  // Bind address of our side of the connection
578 };
579 
580 
581 
582 
583 class CNetMessage {
584 private:
585  mutable CHash256 hasher;
587 public:
588  bool in_data; // parsing header (false) or data (true)
589 
590  CDataStream hdrbuf; // partially received header
591  CMessageHeader hdr; // complete header
592  unsigned int nHdrPos;
593 
594  CDataStream vRecv; // received message data
595  unsigned int nDataPos;
596 
597  int64_t nTime; // time (in microseconds) of message receipt.
598 
599  CNetMessage(const CMessageHeader::MessageStartChars& pchMessageStartIn, int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), hdr(pchMessageStartIn), vRecv(nTypeIn, nVersionIn) {
600  hdrbuf.resize(24);
601  in_data = false;
602  nHdrPos = 0;
603  nDataPos = 0;
604  nTime = 0;
605  }
606 
607  bool complete() const
608  {
609  if (!in_data)
610  return false;
611  return (hdr.nMessageSize == nDataPos);
612  }
613 
614  const uint256& GetMessageHash() const;
615 
616  void SetVersion(int nVersionIn)
617  {
618  hdrbuf.SetVersion(nVersionIn);
619  vRecv.SetVersion(nVersionIn);
620  }
621 
622  int readHeader(const char *pch, unsigned int nBytes);
623  int readData(const char *pch, unsigned int nBytes);
624 };
625 
626 
628 class CNode
629 {
630  friend class CConnman;
631 public:
632  // socket
633  std::atomic<ServiceFlags> nServices{NODE_NONE};
634  SOCKET hSocket GUARDED_BY(cs_hSocket);
635  size_t nSendSize{0}; // total size of all vSendMsg entries
636  size_t nSendOffset{0}; // offset inside the first vSendMsg already sent
637  uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
638  std::deque<std::vector<unsigned char>> vSendMsg GUARDED_BY(cs_vSend);
642 
644  std::list<CNetMessage> vProcessMsg GUARDED_BY(cs_vProcessMsg);
645  size_t nProcessQueueSize{0};
646 
648 
649  std::deque<CInv> vRecvGetData;
650  uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
651  std::atomic<int> nRecvVersion{INIT_PROTO_VERSION};
652 
653  std::atomic<int64_t> nLastSend{0};
654  std::atomic<int64_t> nLastRecv{0};
655  const int64_t nTimeConnected;
656  std::atomic<int64_t> nTimeOffset{0};
657  // Address of this peer
658  const CAddress addr;
659  // Bind address of our side of the connection
661  std::atomic<int> nVersion{0};
667  std::string cleanSubVer GUARDED_BY(cs_SubVer){};
668  bool m_prefer_evict{false}; // This peer is preferred for eviction.
669  bool HasPermission(NetPermissionFlags permission) const {
670  return NetPermissions::HasFlag(m_permissionFlags, permission);
671  }
672  // This boolean is unusued in actual processing, only present for backward compatibility at RPC/QT level
673  bool m_legacyWhitelisted{false};
674  bool fFeeler{false}; // If true this node is being used as a short lived feeler.
675  bool fOneShot{false};
676  bool m_manual_connection{false};
677  bool fClient{false}; // set by version message
678  bool m_limited_node{false}; //after BIP159, set by version message
679  const bool fInbound;
680  std::atomic_bool fSuccessfullyConnected{false};
681  // Setting fDisconnect to true will cause the node to be disconnected the
682  // next time DisconnectNodes() runs
683  std::atomic_bool fDisconnect{false};
684  // We use fRelayTxes for two purposes -
685  // a) it allows us to not relay tx invs before receiving the peer's version message
686  // b) the peer may tell us in its version message that we should not relay tx invs
687  // unless it loads a bloom filter.
688  bool fRelayTxes GUARDED_BY(cs_filter){false};
689  bool fSentAddr{false};
692  std::unique_ptr<CBloomFilter> pfilter PT_GUARDED_BY(cs_filter);
693  std::atomic<int> nRefCount{0};
694 
695  const uint64_t nKeyedNetGroup;
696  std::atomic_bool fPauseRecv{false};
697  std::atomic_bool fPauseSend{false};
698 
699 protected:
700  mapMsgCmdSize mapSendBytesPerMsgCmd;
701  mapMsgCmdSize mapRecvBytesPerMsgCmd GUARDED_BY(cs_vRecv);
702 
703 public:
705  std::atomic<int> nStartingHeight{-1};
706 
707  // flood relay
708  std::vector<CAddress> vAddrToSend;
710  bool fGetAddr{false};
711  std::set<uint256> setKnown;
712  int64_t nNextAddrSend GUARDED_BY(cs_sendProcessing){0};
713  int64_t nNextLocalAddrSend GUARDED_BY(cs_sendProcessing){0};
714 
715  // inventory based relay
716  CRollingBloomFilter filterInventoryKnown GUARDED_BY(cs_inventory);
717  // Set of transaction ids we still have to announce.
718  // They are sorted by the mempool before relay, so the order is not important.
719  std::set<uint256> setInventoryTxToSend;
720  // List of block ids we still have announce.
721  // There is no final sorting before sending, as they are always sent immediately
722  // and in the order requested.
723  std::vector<uint256> vInventoryBlockToSend GUARDED_BY(cs_inventory);
725  int64_t nNextInvSend{0};
726  // Used for headers announcements - unfiltered blocks to relay
727  std::vector<uint256> vBlockHashesToAnnounce GUARDED_BY(cs_inventory);
728  // Used for BIP35 mempool sending
729  bool fSendMempool GUARDED_BY(cs_inventory){false};
730 
731  // Last time a "MEMPOOL" request was serviced.
732  std::atomic<int64_t> timeLastMempoolReq{0};
733 
734  // Block and TXN accept times
735  std::atomic<int64_t> nLastBlockTime{0};
736  std::atomic<int64_t> nLastTXTime{0};
737 
738  // Ping time measurement:
739  // The pong reply we're expecting, or 0 if no pong expected.
740  std::atomic<uint64_t> nPingNonceSent{0};
741  // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
742  std::atomic<int64_t> nPingUsecStart{0};
743  // Last measured round-trip time.
744  std::atomic<int64_t> nPingUsecTime{0};
745  // Best measured round-trip time.
746  std::atomic<int64_t> nMinPingUsecTime{std::numeric_limits<int64_t>::max()};
747  // Whether a ping is requested.
748  std::atomic<bool> fPingQueued{false};
749  // Minimum fee rate with which to filter inv's to this node
750  CAmount minFeeFilter GUARDED_BY(cs_feeFilter){0};
751  CCriticalSection cs_feeFilter;
752  CAmount lastSentFeeFilter{0};
753  int64_t nextSendTimeFeeFilter{0};
754 
755  std::set<uint256> orphan_work_set;
756 
757  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 = "", bool fInboundIn = false);
758  ~CNode();
759  CNode(const CNode&) = delete;
760  CNode& operator=(const CNode&) = delete;
761 
762 private:
763  const NodeId id;
764  const uint64_t nLocalHostNonce;
765  // Services offered to this peer
767  const int nMyStartingHeight;
768  int nSendVersion{0};
769  NetPermissionFlags m_permissionFlags{ PF_NONE };
770  std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
771 
773  std::string addrName GUARDED_BY(cs_addrName);
774 
775  // Our address, as reported by the peer
776  CService addrLocal GUARDED_BY(cs_addrLocal);
778 public:
779 
780  NodeId GetId() const {
781  return id;
782  }
783 
784  uint64_t GetLocalNonce() const {
785  return nLocalHostNonce;
786  }
787 
788  int GetMyStartingHeight() const {
789  return nMyStartingHeight;
790  }
791 
792  int GetRefCount() const
793  {
794  assert(nRefCount >= 0);
795  return nRefCount;
796  }
797 
798  bool ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool& complete);
799 
800  void SetRecvVersion(int nVersionIn)
801  {
802  nRecvVersion = nVersionIn;
803  }
804  int GetRecvVersion() const
805  {
806  return nRecvVersion;
807  }
808  void SetSendVersion(int nVersionIn);
809  int GetSendVersion() const;
810 
811  CService GetAddrLocal() const;
813  void SetAddrLocal(const CService& addrLocalIn);
814 
816  {
817  nRefCount++;
818  return this;
819  }
820 
821  void Release()
822  {
823  nRefCount--;
824  }
825 
826 
827 
828  void AddAddressKnown(const CAddress& _addr)
829  {
830  addrKnown.insert(_addr.GetKey());
831  }
832 
833  void PushAddress(const CAddress& _addr, FastRandomContext &insecure_rand)
834  {
835  // Known checking here is only to save space from duplicates.
836  // SendMessages will filter it again for knowns that were added
837  // after addresses were pushed.
838  if (_addr.IsValid() && !addrKnown.contains(_addr.GetKey())) {
839  if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
840  vAddrToSend[insecure_rand.randrange(vAddrToSend.size())] = _addr;
841  } else {
842  vAddrToSend.push_back(_addr);
843  }
844  }
845  }
846 
847 
848  void AddInventoryKnown(const CInv& inv)
849  {
850  {
851  LOCK(cs_inventory);
852  filterInventoryKnown.insert(inv.hash);
853  }
854  }
855 
856  void PushInventory(const CInv& inv)
857  {
858  LOCK(cs_inventory);
859  if (inv.type == MSG_TX) {
860  if (!filterInventoryKnown.contains(inv.hash)) {
861  setInventoryTxToSend.insert(inv.hash);
862  }
863  } else if (inv.type == MSG_BLOCK) {
864  vInventoryBlockToSend.push_back(inv.hash);
865  }
866  }
867 
868  void PushBlockHash(const uint256 &hash)
869  {
870  LOCK(cs_inventory);
871  vBlockHashesToAnnounce.push_back(hash);
872  }
873 
874  void CloseSocketDisconnect();
875 
876  void copyStats(CNodeStats &stats);
877 
879  {
880  return nLocalServices;
881  }
882 
883  std::string GetAddrName() const;
885  void MaybeSetAddrName(const std::string& addrNameIn);
886 };
887 
888 
889 
890 
891 
893 int64_t PoissonNextSend(int64_t now, int average_interval_seconds);
894 
895 #endif // BITCOIN_NET_H
std::vector< CService > vBinds
Definition: net.h:149
CAmount minFeeFilter GUARDED_BY(cs_feeFilter)
Definition: net.h:750
static const int MAX_OUTBOUND_CONNECTIONS
Maximum number of automatic outgoing nodes.
Definition: net.h:65
bool fRelayTxes GUARDED_BY(cs_filter)
Definition: net.h:688
#define NO_THREAD_SAFETY_ANALYSIS
Definition: threadsafety.h:53
std::unique_ptr< CConnman > g_connman
Definition: init.cpp:87
int nMaxFeeler
Definition: net.h:419
uint256 data_hash
Definition: net.h:586
bool IsReachable(enum Network net)
Definition: net.cpp:254
CCriticalSection cs_addrName
Definition: net.h:772
int nStartingHeight
Definition: net.h:561
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:61
int64_t nNextLocalAddrSend GUARDED_BY(cs_sendProcessing)
Definition: net.h:713
mapMsgCmdSize mapRecvBytesPerMsgCmd
Definition: net.h:565
Definition: banman.h:37
static void AddFlag(NetPermissionFlags &flags, NetPermissionFlags f)
bool fMsgProcWake
flag for waking the message processor.
Definition: net.h:430
ServiceFlags
nServices flags
Definition: protocol.h:247
static const uint64_t MAX_UPLOAD_TIMEFRAME
The default timeframe for -maxuploadtarget.
Definition: net.h:81
CCriticalSection cs_filter
Definition: net.h:691
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:667
int64_t nTimeOffset
Definition: net.h:555
bool fListen
Definition: net.cpp:85
std::atomic< int > nBestHeight
Definition: net.h:421
bool m_legacyWhitelisted
Definition: net.h:567
const std::string NET_MESSAGE_COMMAND_OTHER
Definition: net.cpp:77
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(cs_mapLocalHost)
BanMan * m_banman
Definition: net.h:140
Mutex mutexMsgProc
Definition: net.h:433
static const bool DEFAULT_FORCEDNSSEED
Definition: net.h:87
const uint64_t nKeyedNetGroup
Definition: net.h:695
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:266
int GetRecvVersion() const
Definition: net.h:804
mapMsgCmdSize mapSendBytesPerMsgCmd
Definition: net.h:700
void insert(const std::vector< unsigned char > &vKey)
Definition: bloom.cpp:246
void StartMapPort()
Definition: net.cpp:1507
void StopMapPort()
Definition: net.cpp:1515
std::vector< unsigned char > data
Definition: net.h:113
inv message data
Definition: protocol.h:382
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:392
unsigned int nReceiveFloodSize
Definition: net.h:142
mapMsgCmdSize mapSendBytesPerMsgCmd
Definition: net.h:563
CClientUIInterface * uiInterface
Definition: net.h:138
void resize(size_type n, value_type c=0)
Definition: streams.h:296
bool g_relay_txes
Definition: net.cpp:86
CCriticalSection cs_hSocket
Definition: net.h:640
ServiceFlags nServices
Definition: net.h:550
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:69
CCriticalSection cs_addrLocal
Definition: net.h:777
unsigned int nHdrPos
Definition: net.h:592
int nMaxAddnode
Definition: net.h:418
RAII-style semaphore lock.
Definition: sync.h:248
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:67
void Interrupt()
Interrupt threads.
Definition: init.cpp:157
bool fSendMempool GUARDED_BY(cs_inventory)
Definition: net.h:729
std::string cleanSubVer
Definition: net.h:558
Interface for message handling.
Definition: net.h:479
void SetVersion(int nVersionIn)
Definition: net.h:616
RollingBloomFilter is a probabilistic "keep track of most recently inserted" set. ...
Definition: bloom.h:115
NetEventsInterface * m_msgproc
Definition: net.h:423
CAmount minFeeFilter
Definition: net.h:571
CCriticalSection cs_vNodes
Definition: net.h:407
int nMaxConnections
Definition: net.h:133
int64_t nTimeConnected
Definition: net.h:554
void AdvertiseLocal(CNode *pnode)
Definition: net.cpp:181
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:203
CCriticalSection cs_vAddedNodes
Definition: net.h:404
uint32_t nMessageSize
Definition: protocol.h:59
A hasher class for Bitcoin&#39;s 256-bit hash (double SHA-256).
Definition: hash.h:22
CCriticalSection cs_inventory
Definition: net.h:724
uint64_t GetLocalNonce() const
Definition: net.h:784
CDataStream hdrbuf
Definition: net.h:590
std::set< uint256 > setInventoryTxToSend
Definition: net.h:719
std::vector< CAddress > vAddrToSend
Definition: net.h:708
void PushAddress(const CAddress &_addr, FastRandomContext &insecure_rand)
Definition: net.h:833
static CScheduler scheduler
Definition: init.cpp:155
static const int FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes or 120 seconds.
Definition: net.h:53
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Definition: net.h:637
static const int TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:51
void SetRecvVersion(int nVersionIn)
Definition: net.h:800
bool in_data
Definition: net.h:588
Definition: net.h:503
Signals for UI communication.
Definition: ui_interface.h:34
std::list< CNetMessage > vRecvMsg
Definition: net.h:770
CNetMessage(const CMessageHeader::MessageStartChars &pchMessageStartIn, int nTypeIn, int nVersionIn)
Definition: net.h:599
void PushInventory(const CInv &inv)
Definition: net.h:856
CAddrMan addrman
Definition: net.h:400
std::set< uint256 > orphan_work_set
Definition: net.h:755
std::deque< CInv > vRecvGetData
Definition: net.h:649
bool fConnected
Definition: net.h:97
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition: net.h:326
int GetRefCount() const
Definition: net.h:792
ServiceFlags nLocalServices
Services this instance offers.
Definition: net.h:412
CDataStream vRecv
Definition: net.h:594
bool contains(const std::vector< unsigned char > &vKey) const
Definition: bloom.cpp:283
bool IsValid() const
Definition: netaddress.cpp:247
std::set< uint256 > setKnown
Definition: net.h:711
bool operator()(I first, I last) const
Definition: net.h:466
static const unsigned int MAX_LOCATOR_SZ
The maximum number of entries in a locator.
Definition: net.h:57
bool m_manual_connection
Definition: net.h:560
Stochastical (IP) address manager.
Definition: addrman.h:175
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
CHash256 hasher
Definition: net.h:585
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:88
int GetMyStartingHeight() const
Definition: net.h:788
ServiceFlags GetLocalServices() const
Definition: net.h:878
int nVersion
Definition: net.h:557
void InterruptMapPort()
Definition: net.cpp:1511
void Release()
Definition: net.h:821
bool GetLocal(CService &addr, const CNetAddr *paddrPeer=nullptr)
Definition: net.cpp:104
std::condition_variable condMsgProc
Definition: net.h:432
bool result_type
Definition: net.h:463
ListenSocket(SOCKET socket_, NetPermissionFlags permissions_)
Definition: net.h:327
std::thread threadOpenAddedConnections
Definition: net.h:440
#define LOCK(cs)
Definition: sync.h:182
bool IsPeerAddrLocalGood(CNode *pnode)
Definition: net.cpp:173
NetEventsInterface * m_msgproc
Definition: net.h:139
int type
Definition: protocol.h:403
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:95
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:140
Fast randomness source.
Definition: random.h:100
const CAddress addrBind
Definition: net.h:660
std::vector< std::string > vSeedNodes
Definition: net.h:146
std::vector< std::string > m_specified_outgoing
Definition: net.h:151
int64_t m_peer_connect_timeout
Definition: net.h:388
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:414
std::thread threadMessageHandler
Definition: net.h:442
static bool HasFlag(const NetPermissionFlags &flags, NetPermissionFlags f)
CMessageHeader hdr
Definition: net.h:591
void ForEachNodeThen(Callable &&pre, CallableAfter &&post)
Definition: net.h:228
bool fInbound
Definition: net.h:559
A CService with information about it as peer.
Definition: protocol.h:325
uint64_t nRecvBytes
Definition: net.h:564
std::vector< unsigned char > GetKey() const
Definition: netaddress.cpp:669
uint256 hash
Definition: protocol.h:404
bool fInbound
Definition: net.h:98
double dPingTime
Definition: net.h:568
std::string addrName
Definition: net.h:556
int nMaxFeeler
Definition: net.h:136
Network
Definition: netaddress.h:20
std::atomic_bool m_try_another_outbound_peer
flag for deciding to connect to an extra outbound peer, in excess of nMaxOutbound This takes the plac...
Definition: net.h:447
int64_t NodeId
Definition: net.h:91
Definition: net.h:119
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:77
bool GetNetworkActive() const
Definition: net.h:197
NumConnections
Definition: net.h:123
CClientUIInterface * clientInterface
Definition: net.h:422
NodeId GetId() const
Definition: net.h:780
uint64_t nSendBytes
Definition: net.h:562
int nMaxOutbound
Definition: net.h:134
int nMaxConnections
Definition: net.h:416
std::unique_ptr< BanMan > g_banman
Definition: init.cpp:89
NetPermissionFlags
void ForEachNode(Callable &&func)
Definition: net.h:208
CCriticalSection cs_vOneShots
Definition: net.h:402
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Definition: net.h:650
CRollingBloomFilter addrKnown
Definition: net.h:709
void Discover()
Definition: net.cpp:2072
unsigned char MessageStartChars[MESSAGE_START_SIZE]
Definition: protocol.h:38
RecursiveMutex cs_SubVer
Definition: net.h:662
unsigned int SOCKET
Definition: compat.h:48
NetPermissionFlags m_permissions
Definition: net.h:329
const CAddress addr
Definition: net.h:658
const int64_t nTimeConnected
Definition: net.h:655
int64_t nTime
Definition: net.h:597
int flags
Definition: bitcoin-tx.cpp:509
uint64_t nMaxOutboundTimeframe
Definition: net.h:143
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
Definition: netaddress.h:32
CCriticalSection cs_vRecv
Definition: net.h:641
std::list< CNode * > vNodesDisconnected
Definition: net.h:406
256-bit opaque blob.
Definition: uint256.h:121
void RemoveLocal(const CService &addr)
Definition: net.cpp:239
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:147
void AddInventoryKnown(const CInv &inv)
Definition: net.h:848
int nScore
Definition: net.h:536
static const unsigned int MAX_ADDR_TO_SEND
The maximum number of new addresses to accumulate before announcing.
Definition: net.h:59
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
Definition: net.h:46
int nMaxAddnode
Definition: net.h:135
int64_t nNextAddrSend GUARDED_BY(cs_sendProcessing)
Definition: net.h:712
void ForEachNode(Callable &&func) const
Definition: net.h:218
BanMan * m_banman
Definition: net.h:424
bool complete() const
Definition: net.h:607
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:89
CAddress addrBind
Definition: net.h:577
const bool fInbound
Definition: net.h:679
CService resolvedAddress
Definition: net.h:96
std::thread threadOpenConnections
Definition: net.h:441
static const uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:79
CSemaphoreGrant grantOutbound
Definition: net.h:690
uint256 hashContinue
Definition: net.h:704
std::map< std::string, uint64_t > mapMsgCmdSize
Definition: net.h:544
const NodeId id
Definition: net.h:763
unsigned int nDataPos
Definition: net.h:595
std::string addrLocal
Definition: net.h:573
std::thread threadDNSAddressSeed
Definition: net.h:438
ServiceFlags nLocalServices
Definition: net.h:132
uint64_t nMaxOutboundLimit
Definition: net.h:144
std::vector< std::string > m_added_nodes
Definition: net.h:152
CCriticalSection cs_vProcessMsg
Definition: net.h:643
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:2721
std::vector< ListenSocket > vhListenSocket
Definition: net.h:397
double dMinPing
Definition: net.h:570
void PushBlockHash(const uint256 &hash)
Definition: net.h:868
std::string command
Definition: net.h:114
void ForEachNodeThen(Callable &&pre, CallableAfter &&post) const
Definition: net.h:239
CCriticalSection cs_totalBytesSent
Definition: net.h:377
SipHash-2-4.
Definition: siphash.h:13
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:63
static const bool DEFAULT_UPNP
-upnp default
Definition: net.h:74
int nMaxOutbound
Definition: net.h:417
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition: net.h:85
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:83
const uint64_t nLocalHostNonce
Definition: net.h:764
unsigned int nSendBufferMaxSize
Definition: net.h:141
static const int PING_INTERVAL
Time between pings automatically sent out for latency probing and keepalive (in seconds).
Definition: net.h:49
const ServiceFlags nLocalServices
Definition: net.h:766
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
Definition: net.h:44
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:90
CClientUIInterface uiInterface
CCriticalSection cs_sendProcessing
Definition: net.h:647
Definition: net.h:498
Information about a peer.
Definition: net.h:628
std::thread threadSocketHandler
Definition: net.h:439
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:246
NetPermissionFlags m_permissionFlags
Definition: net.h:566
CCriticalSection cs_vSend
Definition: net.h:639
bool fDiscover
Definition: net.cpp:84
void SetVersion(int n)
Definition: streams.h:396
void AddAddressKnown(const CAddress &_addr)
Definition: net.h:828
CNode * AddRef()
Definition: net.h:815
std::unique_ptr< CSemaphore > semAddnode
Definition: net.h:415
double dPingWait
Definition: net.h:569
void Init(const Options &connOptions)
Definition: net.h:155
CThreadInterrupt interruptNet
Definition: net.h:436
static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections)
bool HasPermission(NetPermissionFlags permission) const
Definition: net.h:669
CCriticalSection cs_totalBytesRecv
Definition: net.h:376
CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
Definition: net.cpp:153
static const unsigned int MAX_INV_SZ
The maximum number of entries in an &#39;inv&#39; protocol message.
Definition: net.h:55
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
Definition: net.cpp:208
const uint64_t nSeed1
Definition: net.h:427
bool m_use_addrman_outgoing
Definition: net.h:150
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:148
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:279
CCriticalSection cs_mapLocalHost
Definition: net.cpp:87
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
Definition: random.h:167
bool GetUseAddrmanOutgoing() const
Definition: net.h:198
bool fRelayTxes
Definition: net.h:551
int64_t nLastSend
Definition: net.h:552
unsigned short GetListenPort()
Definition: net.cpp:98
const int nMyStartingHeight
Definition: net.h:767
bool m_use_addrman_outgoing
Definition: net.h:420
int nBestHeight
Definition: net.h:137
NodeId nodeid
Definition: net.h:549
int64_t nLastRecv
Definition: net.h:553
#define PT_GUARDED_BY(x)
Definition: threadsafety.h:40
CAddress addr
Definition: net.h:575
Message header.
Definition: protocol.h:28
int64_t m_peer_connect_timeout
Definition: net.h:145