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