Dash Core Source Documentation (0.16.0.1)

Find detailed information regarding the Dash Core source code.

net.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 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 <bloom.h>
12 #include <compat.h>
13 #include <fs.h>
14 #include <hash.h>
15 #include <limitedmap.h>
16 #include <netaddress.h>
17 #include <policy/feerate.h>
18 #include <protocol.h>
19 #include <random.h>
20 #include <saltedhasher.h>
21 #include <streams.h>
22 #include <sync.h>
23 #include <uint256.h>
24 #include <util.h>
25 #include <threadinterrupt.h>
26 #include <consensus/params.h>
27 
28 #include <atomic>
29 #include <deque>
30 #include <stdint.h>
31 #include <thread>
32 #include <memory>
33 #include <condition_variable>
34 #include <unordered_set>
35 #include <queue>
36 
37 #ifndef WIN32
38 #include <arpa/inet.h>
39 #endif
40 
41 
42 #ifndef WIN32
43 #define USE_WAKEUP_PIPE
44 #endif
45 
46 class CScheduler;
47 class CNode;
48 
49 namespace boost {
50  class thread_group;
51 } // namespace boost
52 
54 static const int PING_INTERVAL = 2 * 60;
56 static const int TIMEOUT_INTERVAL = 20 * 60;
58 static const int WARNING_INTERVAL = 10 * 60;
60 static const int FEELER_INTERVAL = 120;
62 static const unsigned int MAX_INV_SZ = 50000;
64 static const unsigned int MAX_ADDR_TO_SEND = 1000;
66 static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 3 * 1024 * 1024;
68 static const unsigned int MAX_SUBVERSION_LENGTH = 256;
70 static const int MAX_OUTBOUND_CONNECTIONS = 8;
72 static const int MAX_ADDNODE_CONNECTIONS = 8;
74 static const int INBOUND_EVICTION_PROTECTION_TIME = 1;
76 static const bool DEFAULT_LISTEN = true;
78 #ifdef USE_UPNP
79 static const bool DEFAULT_UPNP = USE_UPNP;
80 #else
81 static const bool DEFAULT_UPNP = false;
82 #endif
83 
86 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
88 static const uint64_t DEFAULT_MAX_UPLOAD_TARGET = 0;
90 static const uint64_t MAX_UPLOAD_TIMEFRAME = 60 * 60 * 24;
92 static const bool DEFAULT_BLOCKSONLY = false;
93 
94 static const bool DEFAULT_FORCEDNSSEED = false;
95 static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
96 static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
97 
98 // NOTE: When adjusting this, update rpcnet:setban's help ("24h")
99 static const unsigned int DEFAULT_MISBEHAVING_BANTIME = 60 * 60 * 24; // Default 24-hour ban
100 
101 #if defined USE_EPOLL
102 #define DEFAULT_SOCKETEVENTS "epoll"
103 #elif defined USE_POLL
104 #define DEFAULT_SOCKETEVENTS "poll"
105 #else
106 #define DEFAULT_SOCKETEVENTS "select"
107 #endif
108 
109 typedef int64_t NodeId;
110 
112 {
113  std::string strAddedNode;
116  bool fInbound;
117 };
118 
119 class CNodeStats;
120 class CClientUIInterface;
121 
123 {
124  CSerializedNetMsg() = default;
127  // No copying, only moves.
128  CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
130 
131  std::vector<unsigned char> data;
132  std::string command;
133 };
134 
135 class NetEventsInterface;
136 class CConnman
137 {
138 friend class CNode;
139 public:
140 
143  CONNECTIONS_IN = (1U << 0),
144  CONNECTIONS_OUT = (1U << 1),
146  };
147 
152  };
153 
154  struct Options
155  {
158  int nMaxOutbound = 0;
159  int nMaxAddnode = 0;
160  int nMaxFeeler = 0;
161  int nBestHeight = 0;
164  unsigned int nSendBufferMaxSize = 0;
165  unsigned int nReceiveFloodSize = 0;
166  uint64_t nMaxOutboundTimeframe = 0;
167  uint64_t nMaxOutboundLimit = 0;
168  std::vector<std::string> vSeedNodes;
169  std::vector<CSubNet> vWhitelistedRange;
170  std::vector<CService> vBinds, vWhiteBinds;
172  std::vector<std::string> m_specified_outgoing;
173  std::vector<std::string> m_added_nodes;
175  };
176 
177  void Init(const Options& connOptions) {
178  nLocalServices = connOptions.nLocalServices;
179  nMaxConnections = connOptions.nMaxConnections;
180  nMaxOutbound = std::min(connOptions.nMaxOutbound, connOptions.nMaxConnections);
181  nMaxAddnode = connOptions.nMaxAddnode;
182  nMaxFeeler = connOptions.nMaxFeeler;
183  nBestHeight = connOptions.nBestHeight;
184  clientInterface = connOptions.uiInterface;
185  m_msgproc = connOptions.m_msgproc;
187  nReceiveFloodSize = connOptions.nReceiveFloodSize;
188  {
190  nMaxOutboundTimeframe = connOptions.nMaxOutboundTimeframe;
191  nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
192  }
193  vWhitelistedRange = connOptions.vWhitelistedRange;
194  {
196  vAddedNodes = connOptions.m_added_nodes;
197  }
198  socketEventsMode = connOptions.socketEventsMode;
199  }
200 
201  CConnman(uint64_t seed0, uint64_t seed1);
202  ~CConnman();
203  bool Start(CScheduler& scheduler, const Options& options);
204  void Stop();
205  void Interrupt();
206  bool GetNetworkActive() const { return fNetworkActive; };
207  void SetNetworkActive(bool active);
209  void OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound = nullptr, const char *strDest = nullptr, bool fOneShot = false, bool fFeeler = false, bool manual_connection = false, bool fConnectToMasternode = false, bool fMasternodeProbe = false);
210  void OpenMasternodeConnection(const CAddress& addrConnect, bool probe = false);
211  bool CheckIncomingNonce(uint64_t nonce);
212 
214  bool operator() (const CNode* pnode) const {
215  return NodeFullyConnected(pnode);
216  }
217  };
218 
219  constexpr static const CFullyConnectedOnly FullyConnectedOnly{};
220 
221  struct CAllNodes {
222  bool operator() (const CNode*) const {return true;}
223  };
224 
225  constexpr static const CAllNodes AllNodes{};
226 
227  bool ForNode(NodeId id, std::function<bool(const CNode* pnode)> cond, std::function<bool(CNode* pnode)> func);
228  bool ForNode(const CService& addr, std::function<bool(const CNode* pnode)> cond, std::function<bool(CNode* pnode)> func);
229 
230  template<typename Callable>
231  bool ForNode(const CService& addr, Callable&& func)
232  {
233  return ForNode(addr, FullyConnectedOnly, func);
234  }
235 
236  template<typename Callable>
237  bool ForNode(NodeId id, Callable&& func)
238  {
239  return ForNode(id, FullyConnectedOnly, func);
240  }
241 
242  bool IsConnected(const CService& addr, std::function<bool(const CNode* pnode)> cond)
243  {
244  return ForNode(addr, cond, [](CNode* pnode){
245  return true;
246  });
247  }
248 
250 
251  void PushMessage(CNode* pnode, CSerializedNetMsg&& msg);
252 
253  template<typename Condition, typename Callable>
254  bool ForEachNodeContinueIf(const Condition& cond, Callable&& func)
255  {
256  LOCK(cs_vNodes);
257  for (auto&& node : vNodes)
258  if (cond(node))
259  if(!func(node))
260  return false;
261  return true;
262  };
263 
264  template<typename Callable>
265  bool ForEachNodeContinueIf(Callable&& func)
266  {
268  }
269 
270  template<typename Condition, typename Callable>
271  bool ForEachNodeContinueIf(const Condition& cond, Callable&& func) const
272  {
273  LOCK(cs_vNodes);
274  for (const auto& node : vNodes)
275  if (cond(node))
276  if(!func(node))
277  return false;
278  return true;
279  };
280 
281  template<typename Callable>
282  bool ForEachNodeContinueIf(Callable&& func) const
283  {
285  }
286 
287  template<typename Condition, typename Callable>
288  void ForEachNode(const Condition& cond, Callable&& func)
289  {
290  LOCK(cs_vNodes);
291  for (auto&& node : vNodes) {
292  if (cond(node))
293  func(node);
294  }
295  };
296 
297  template<typename Callable>
298  void ForEachNode(Callable&& func)
299  {
301  }
302 
303  template<typename Condition, typename Callable>
304  void ForEachNode(const Condition& cond, Callable&& func) const
305  {
306  LOCK(cs_vNodes);
307  for (auto&& node : vNodes) {
308  if (cond(node))
309  func(node);
310  }
311  };
312 
313  template<typename Callable>
314  void ForEachNode(Callable&& func) const
315  {
317  }
318 
319  template<typename Condition, typename Callable, typename CallableAfter>
320  void ForEachNodeThen(const Condition& cond, Callable&& pre, CallableAfter&& post)
321  {
322  LOCK(cs_vNodes);
323  for (auto&& node : vNodes) {
324  if (cond(node))
325  pre(node);
326  }
327  post();
328  };
329 
330  template<typename Callable, typename CallableAfter>
331  void ForEachNodeThen(Callable&& pre, CallableAfter&& post)
332  {
334  }
335 
336  template<typename Condition, typename Callable, typename CallableAfter>
337  void ForEachNodeThen(const Condition& cond, Callable&& pre, CallableAfter&& post) const
338  {
339  LOCK(cs_vNodes);
340  for (auto&& node : vNodes) {
341  if (cond(node))
342  pre(node);
343  }
344  post();
345  };
346 
347  template<typename Callable, typename CallableAfter>
348  void ForEachNodeThen(Callable&& pre, CallableAfter&& post) const
349  {
351  }
352 
353  std::vector<CNode*> CopyNodeVector(std::function<bool(const CNode* pnode)> cond);
354  std::vector<CNode*> CopyNodeVector();
355  void ReleaseNodeVector(const std::vector<CNode*>& vecNodes);
356 
357  void RelayTransaction(const CTransaction& tx);
358  void RelayInv(CInv &inv, const int minProtoVersion = MIN_PEER_PROTO_VERSION, bool fAllowMasternodeConnections = false);
359  void RelayInvFiltered(CInv &inv, const CTransaction &relatedTx, const int minProtoVersion = MIN_PEER_PROTO_VERSION, bool fAllowMasternodeConnections = false);
360  // This overload will not update node filters, so use it only for the cases when other messages will update related transaction data in filters
361  void RelayInvFiltered(CInv &inv, const uint256 &relatedTxHash, const int minProtoVersion = MIN_PEER_PROTO_VERSION, bool fAllowMasternodeConnections = false);
362 
363  // Addrman functions
364  size_t GetAddressCount() const;
365  void SetServices(const CService &addr, ServiceFlags nServices);
366  void MarkAddressGood(const CAddress& addr);
367  void AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
368  std::vector<CAddress> GetAddresses();
369 
370  // Denial-of-service detection/prevention
371  // The idea is to detect peers that are behaving
372  // badly and disconnect/ban them, but do it in a
373  // one-coding-mistake-won't-shatter-the-entire-network
374  // way.
375  // IMPORTANT: There should be nothing I can give a
376  // node that it will forward on that will make that
377  // node's peers drop it. If there is, an attacker
378  // can isolate a node and/or try to split the network.
379  // Dropping a node for sending stuff that is invalid
380  // now but might be valid in a later version is also
381  // dangerous, because it can cause a network split
382  // between nodes running old code and nodes running
383  // new code.
384  void Ban(const CNetAddr& netAddr, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
385  void Ban(const CSubNet& subNet, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
386  void ClearBanned(); // needed for unit testing
387  bool IsBanned(CNetAddr ip);
388  bool IsBanned(CSubNet subnet);
389  bool Unban(const CNetAddr &ip);
390  bool Unban(const CSubNet &ip);
391  void GetBanned(banmap_t &banmap);
392  void SetBanned(const banmap_t &banmap);
393 
394  // This allows temporarily exceeding nMaxOutbound, with the goal of finding
395  // a peer that is better than all our current peers.
396  void SetTryNewOutboundPeer(bool flag);
397  bool GetTryNewOutboundPeer();
398 
399  // Return the number of outbound peers we have in excess of our target (eg,
400  // if we previously called SetTryNewOutboundPeer(true), and have since set
401  // to false, we may have extra peers that we wish to disconnect). This may
402  // return a value less than (num_outbound_connections - num_outbound_slots)
403  // in cases where some outbound connections are not yet fully connected, or
404  // not yet fully disconnected.
405  int GetExtraOutboundCount();
406 
407  bool AddNode(const std::string& node);
408  bool RemoveAddedNode(const std::string& node);
409  std::vector<AddedNodeInfo> GetAddedNodeInfo();
410 
411  bool AddPendingMasternode(const uint256& proTxHash);
412  void SetMasternodeQuorumNodes(Consensus::LLMQType llmqType, const uint256& quorumHash, const std::set<uint256>& proTxHashes);
413  bool HasMasternodeQuorumNodes(Consensus::LLMQType llmqType, const uint256& quorumHash);
414  std::set<uint256> GetMasternodeQuorums(Consensus::LLMQType llmqType);
415  // also returns QWATCH nodes
416  std::set<NodeId> GetMasternodeQuorumNodes(Consensus::LLMQType llmqType, const uint256& quorumHash) const;
417  void RemoveMasternodeQuorumNodes(Consensus::LLMQType llmqType, const uint256& quorumHash);
418  bool IsMasternodeQuorumNode(const CNode* pnode);
419  void AddPendingProbeConnections(const std::set<uint256>& proTxHashes);
420 
421  size_t GetNodeCount(NumConnections num);
422  size_t GetMaxOutboundNodeCount();
423  void GetNodeStats(std::vector<CNodeStats>& vstats);
424  bool DisconnectNode(const std::string& node);
425  bool DisconnectNode(NodeId id);
426 
428 
430  void SetMaxOutboundTarget(uint64_t limit);
431  uint64_t GetMaxOutboundTarget();
432 
434  void SetMaxOutboundTimeframe(uint64_t timeframe);
435  uint64_t GetMaxOutboundTimeframe();
436 
438  // if param historicalBlockServingLimit is set true, the function will
439  // response true if the limit for serving historical blocks has been reached
440  bool OutboundTargetReached(bool historicalBlockServingLimit);
441 
443  // in case of no limit, it will always response 0
444  uint64_t GetOutboundTargetBytesLeft();
445 
447  // in case of no limit, it will always response 0
449 
450  uint64_t GetTotalBytesRecv();
451  uint64_t GetTotalBytesSent();
452 
453  void SetBestHeight(int height);
454  int GetBestHeight() const;
455 
457  CSipHasher GetDeterministicRandomizer(uint64_t id) const;
458 
459  unsigned int GetReceiveFloodSize() const;
460 
461  void WakeMessageHandler();
462  void WakeSelect();
463 
468  int64_t PoissonNextSendInbound(int64_t now, int average_interval_seconds);
469 
470 private:
471  struct ListenSocket {
474 
475  ListenSocket(SOCKET socket_, bool whitelisted_) : socket(socket_), whitelisted(whitelisted_) {}
476  };
477 
478  bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
479  bool Bind(const CService &addr, unsigned int flags);
480  bool InitBinds(const std::vector<CService>& binds, const std::vector<CService>& whiteBinds);
482  void AddOneShot(const std::string& strDest);
483  void ProcessOneShot();
484  void ThreadOpenConnections(std::vector<std::string> connect);
485  void ThreadMessageHandler();
486  void AcceptConnection(const ListenSocket& hListenSocket);
487  void DisconnectNodes();
489  void InactivityCheck(CNode *pnode);
490  bool GenerateSelectSet(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set);
491 #ifdef USE_EPOLL
492  void SocketEventsEpoll(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set, bool fOnlyPoll);
493 #endif
494 #ifdef USE_POLL
495  void SocketEventsPoll(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set, bool fOnlyPoll);
496 #endif
497  void SocketEventsSelect(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set, bool fOnlyPoll);
498  void SocketEvents(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set, bool fOnlyPoll);
499  void SocketHandler();
500  void ThreadSocketHandler();
501  void ThreadDNSAddressSeed();
503 
504  uint64_t CalculateKeyedNetGroup(const CAddress& ad) const;
505 
506  CNode* FindNode(const CNetAddr& ip, bool fExcludeDisconnecting = true);
507  CNode* FindNode(const CSubNet& subNet, bool fExcludeDisconnecting = true);
508  CNode* FindNode(const std::string& addrName, bool fExcludeDisconnecting = true);
509  CNode* FindNode(const CService& addr, bool fExcludeDisconnecting = true);
510 
512  CNode* ConnectNode(CAddress addrConnect, const char *pszDest = nullptr, bool fCountFailure = false);
513  bool IsWhitelistedRange(const CNetAddr &addr);
514 
515  void DeleteNode(CNode* pnode);
516 
518 
519  size_t SocketSendData(CNode *pnode);
520  size_t SocketRecvData(CNode* pnode);
522  bool BannedSetIsDirty();
524  void SetBannedSetDirty(bool dirty=true);
526  void SweepBanned();
527  void DumpAddresses();
528  void DumpData();
529  void DumpBanlist();
530 
531  // Network stats
532  void RecordBytesRecv(uint64_t bytes);
533  void RecordBytesSent(uint64_t bytes);
534 
535  // Whether the node should be passed out in ForEach* callbacks
536  static bool NodeFullyConnected(const CNode* pnode);
537 
538  void RegisterEvents(CNode* pnode);
539  void UnregisterEvents(CNode* pnode);
540 
541  // Network usage totals
544  uint64_t nTotalBytesRecv GUARDED_BY(cs_totalBytesRecv);
545  uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent);
546 
547  // outbound limit & stats
548  uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent);
549  uint64_t nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent);
550  uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent);
551  uint64_t nMaxOutboundTimeframe GUARDED_BY(cs_totalBytesSent);
552 
553  // Whitelisted ranges. Any node connecting from these is automatically
554  // whitelisted (as well as those connecting to whitelisted binds).
555  std::vector<CSubNet> vWhitelistedRange;
556 
557  unsigned int nSendBufferMaxSize;
558  unsigned int nReceiveFloodSize;
559 
560  std::vector<ListenSocket> vhListenSocket;
561  std::atomic<bool> fNetworkActive;
562  banmap_t setBanned GUARDED_BY(cs_setBanned);
564  bool setBannedIsDirty GUARDED_BY(cs_setBanned);
567  std::deque<std::string> vOneShots GUARDED_BY(cs_vOneShots);
569  std::vector<std::string> vAddedNodes GUARDED_BY(cs_vAddedNodes);
571  std::vector<uint256> vPendingMasternodes;
572  std::map<std::pair<Consensus::LLMQType, uint256>, std::set<uint256>> masternodeQuorumNodes; // protected by cs_vPendingMasternodes
573  std::set<uint256> masternodePendingProbes;
575  std::vector<CNode*> vNodes;
576  std::list<CNode*> vNodesDisconnected;
577  std::unordered_map<SOCKET, CNode*> mapSocketToNode;
579  std::atomic<NodeId> nLastNodeId;
580  unsigned int nPrevNodeCount;
581 
584 
585  std::unique_ptr<CSemaphore> semOutbound;
586  std::unique_ptr<CSemaphore> semAddnode;
591  std::atomic<int> nBestHeight;
594 
596  const uint64_t nSeed0, nSeed1;
597 
600 
601  std::condition_variable condMsgProc;
602  std::mutex mutexMsgProc;
603  std::atomic<bool> flagInterruptMsgProc;
604 
606 
607 #ifdef USE_WAKEUP_PIPE
608 
609  int wakeupPipe[2]{-1,-1};
610 #endif
611  std::atomic<bool> wakeupSelectNeeded{false};
612 
614 #ifdef USE_EPOLL
615  int epollfd{-1};
616 #endif
617 
619  std::unordered_map<NodeId, CNode*> mapReceivableNodes GUARDED_BY(cs_vNodes);
620  std::unordered_map<NodeId, CNode*> mapSendableNodes GUARDED_BY(cs_vNodes);
622  std::unordered_map<NodeId, CNode*> mapNodesWithDataToSend GUARDED_BY(cs_mapNodesWithDataToSend);
624 
625  std::thread threadDNSAddressSeed;
626  std::thread threadSocketHandler;
630  std::thread threadMessageHandler;
631 
635  std::atomic_bool m_try_another_outbound_peer;
636 
637  std::atomic<int64_t> m_next_send_inv_to_incoming;
638 
639  friend struct CConnmanTest;
640 };
641 extern std::unique_ptr<CConnman> g_connman;
642 void Discover(boost::thread_group& threadGroup);
643 void MapPort(bool fUseUPnP);
644 unsigned short GetListenPort();
645 bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
646 
648 {
649  typedef bool result_type;
650 
651  template<typename I>
652  bool operator()(I first, I last) const
653  {
654  while (first != last) {
655  if (!(*first)) return false;
656  ++first;
657  }
658  return true;
659  }
660 };
661 
666 {
667 public:
668  virtual bool ProcessMessages(CNode* pnode, std::atomic<bool>& interrupt) = 0;
669  virtual bool SendMessages(CNode* pnode, std::atomic<bool>& interrupt) = 0;
670  virtual void InitializeNode(CNode* pnode) = 0;
671  virtual void FinalizeNode(NodeId id, bool& update_connection_time) = 0;
672 };
673 
674 enum
675 {
676  LOCAL_NONE, // unknown
677  LOCAL_IF, // address a local interface listens on
678  LOCAL_BIND, // address explicit bound to
679  LOCAL_UPNP, // address reported by UPnP
680  LOCAL_MANUAL, // address explicitly specified (-externalip=)
681 
683 };
684 
685 bool IsPeerAddrLocalGood(CNode *pnode);
686 void AdvertiseLocal(CNode *pnode);
687 void SetLimited(enum Network net, bool fLimited = true);
688 bool IsLimited(enum Network net);
689 bool IsLimited(const CNetAddr& addr);
690 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
691 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
692 bool RemoveLocal(const CService& addr);
693 bool SeenLocal(const CService& addr);
694 bool IsLocal(const CService& addr);
695 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr);
696 bool IsReachable(enum Network net);
697 bool IsReachable(const CNetAddr &addr);
698 CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices);
699 
700 
701 extern bool fDiscover;
702 extern bool fListen;
703 extern bool fRelayTxes;
704 
706 extern std::string strSubVersion;
707 
709  int nScore;
710  int nPort;
711 };
712 
714 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(cs_mapLocalHost);
715 typedef std::map<std::string, uint64_t> mapMsgCmdSize; //command, total bytes
716 
718 {
719 public:
723  int64_t nLastSend;
724  int64_t nLastRecv;
725  int64_t nTimeConnected;
726  int64_t nTimeOffset;
727  std::string addrName;
728  int nVersion;
729  std::string cleanSubVer;
730  bool fInbound;
733  uint64_t nSendBytes;
735  uint64_t nRecvBytes;
738  double dPingTime;
739  double dPingWait;
740  double dMinPing;
741  // Our address, as reported by the peer
742  std::string addrLocal;
743  // Address of this peer
745  // Bind address of our side of the connection
747  // In case this is a verified MN, this value is the proTx of the MN
750 };
751 
752 
753 
754 
755 class CNetMessage {
756 private:
757  mutable CHash256 hasher;
759 public:
760  bool in_data; // parsing header (false) or data (true)
761 
762  CDataStream hdrbuf; // partially received header
763  CMessageHeader hdr; // complete header
764  unsigned int nHdrPos;
765 
766  CDataStream vRecv; // received message data
767  unsigned int nDataPos;
768 
769  int64_t nTime; // time (in microseconds) of message receipt.
770 
771  CNetMessage(const CMessageHeader::MessageStartChars& pchMessageStartIn, int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), hdr(pchMessageStartIn), vRecv(nTypeIn, nVersionIn) {
772  hdrbuf.resize(24);
773  in_data = false;
774  nHdrPos = 0;
775  nDataPos = 0;
776  nTime = 0;
777  }
778 
779  bool complete() const
780  {
781  if (!in_data)
782  return false;
783  return (hdr.nMessageSize == nDataPos);
784  }
785 
786  const uint256& GetMessageHash() const;
787 
788  void SetVersion(int nVersionIn)
789  {
790  hdrbuf.SetVersion(nVersionIn);
791  vRecv.SetVersion(nVersionIn);
792  }
793 
794  int readHeader(const char *pch, unsigned int nBytes);
795  int readData(const char *pch, unsigned int nBytes);
796 };
797 
798 
800 class CNode
801 {
802  friend class CConnman;
803 public:
804  // socket
805  std::atomic<ServiceFlags> nServices;
806  SOCKET hSocket GUARDED_BY(cs_hSocket);
807  size_t nSendSize; // total size of all vSendMsg entries
808  size_t nSendOffset; // offset inside the first vSendMsg already sent
809  uint64_t nSendBytes GUARDED_BY(cs_vSend);
810  std::list<std::vector<unsigned char>> vSendMsg GUARDED_BY(cs_vSend);
811  std::atomic<size_t> nSendMsgSize;
815 
817  std::list<CNetMessage> vProcessMsg GUARDED_BY(cs_vProcessMsg);
819 
821 
822  std::deque<CInv> vRecvGetData;
823  uint64_t nRecvBytes GUARDED_BY(cs_vRecv);
824  std::atomic<int> nRecvVersion;
825 
826  std::atomic<int64_t> nLastSend;
827  std::atomic<int64_t> nLastRecv;
828  const int64_t nTimeConnected;
829  std::atomic<int64_t> nTimeOffset;
830  std::atomic<int64_t> nLastWarningTime;
831  std::atomic<int64_t> nTimeFirstMessageReceived;
832  std::atomic<bool> fFirstMessageIsMNAUTH;
833  // Address of this peer
834  const CAddress addr;
835  // Bind address of our side of the connection
837  std::atomic<int> nNumWarningsSkipped;
838  std::atomic<int> nVersion;
839  // strSubVer is whatever byte array we read from the wire. However, this field is intended
840  // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
841  // store the sanitized version in cleanSubVer. The original should be used when dealing with
842  // the network or wire types and the cleaned string used when displayed or logged.
843  std::string strSubVer GUARDED_BY(cs_SubVer), cleanSubVer GUARDED_BY(cs_SubVer);
844  CCriticalSection cs_SubVer; // used for both cleanSubVer and strSubVer
845  bool fWhitelisted; // This peer can bypass DoS banning.
846  bool fFeeler; // If true this node is being used as a short lived feeler.
847  bool fOneShot;
849  bool fClient;
850  bool m_limited_node; //after BIP159
851  const bool fInbound;
852  std::atomic_bool fSuccessfullyConnected;
853  std::atomic_bool fDisconnect;
854  std::atomic<int64_t> nDisconnectLingerTime{0};
855  std::atomic_bool fSocketShutdown{false};
856  std::atomic_bool fOtherSideDisconnected { false };
857  // We use fRelayTxes for two purposes -
858  // a) it allows us to not relay tx invs before receiving the peer's version message
859  // b) the peer may tell us in its version message that we should not relay tx invs
860  // unless it loads a bloom filter.
861  bool fRelayTxes; //protected by cs_filter
862  bool fSentAddr;
863  // If 'true' this node will be disconnected on CMasternodeMan::ProcessMasternodeConnections()
865  // If 'true' this node will be disconnected after MNAUTH
869  std::unique_ptr<CBloomFilter> pfilter PT_GUARDED_BY(cs_filter);
870  std::atomic<int> nRefCount;
871 
872  const uint64_t nKeyedNetGroup;
873 
874  std::atomic_bool fPauseRecv;
875  std::atomic_bool fPauseSend;
876 
877  std::atomic_bool fHasRecvData;
878  std::atomic_bool fCanSendData;
879 
880 protected:
881 
883  mapMsgCmdSize mapRecvBytesPerMsgCmd GUARDED_BY(cs_vRecv);
884 
885 public:
887  std::atomic<int> nStartingHeight;
888 
889  // flood relay
890  std::vector<CAddress> vAddrToSend;
892  bool fGetAddr;
893  std::set<uint256> setKnown;
894  int64_t nNextAddrSend GUARDED_BY(cs_sendProcessing);
895  int64_t nNextLocalAddrSend GUARDED_BY(cs_sendProcessing);
896 
897  // inventory based relay
898  CRollingBloomFilter filterInventoryKnown GUARDED_BY(cs_inventory);
899  // Set of transaction ids we still have to announce.
900  // They are sorted by the mempool before relay, so the order is not important.
901  std::set<uint256> setInventoryTxToSend;
902  // List of block ids we still have announce.
903  // There is no final sorting before sending, as they are always sent immediately
904  // and in the order requested.
905  std::vector<uint256> vInventoryBlockToSend GUARDED_BY(cs_inventory);
906  // List of non-tx/non-block inventory items
907  std::vector<CInv> vInventoryOtherToSend;
909  std::chrono::microseconds nNextInvSend{0};
910  // Used for headers announcements - unfiltered blocks to relay
911  // Also protected by cs_inventory
912  std::vector<uint256> vBlockHashesToAnnounce;
913  // Used for BIP35 mempool sending, also protected by cs_inventory
915 
916  // Block and TXN accept times
917  std::atomic<int64_t> nLastBlockTime;
918  std::atomic<int64_t> nLastTXTime;
919 
920  // Last time a "MEMPOOL" request was serviced.
921  std::atomic<int64_t> timeLastMempoolReq;
922  // Ping time measurement:
923  // The pong reply we're expecting, or 0 if no pong expected.
924  std::atomic<uint64_t> nPingNonceSent;
925  // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
926  std::atomic<int64_t> nPingUsecStart;
927  // Last measured round-trip time.
928  std::atomic<int64_t> nPingUsecTime;
929  // Best measured round-trip time.
930  std::atomic<int64_t> nMinPingUsecTime;
931  // Whether a ping is requested.
932  std::atomic<bool> fPingQueued;
933 
934  // If true, we will send him PrivateSend queue messages
935  std::atomic<bool> fSendDSQueue{false};
936 
937  // Challenge sent in VERSION to be answered with MNAUTH (only happens between MNs)
943 
944  // If true, we will announce/send him plain recovered sigs (usually true for full nodes)
945  std::atomic<bool> fSendRecSigs{false};
946  // If true, we will send him all quorum related messages, even if he is not a member of our quorums
947  std::atomic<bool> qwatch{false};
948 
949  std::set<uint256> orphan_work_set;
950 
951  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);
952  ~CNode();
953  CNode(const CNode&) = delete;
954  CNode& operator=(const CNode&) = delete;
955 
956 private:
957  const NodeId id;
958  const uint64_t nLocalHostNonce;
959  // Services offered to this peer
961  const int nMyStartingHeight;
963  std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
964 
966  std::string addrName GUARDED_BY(cs_addrName);
967 
968  // Our address, as reported by the peer
969  CService addrLocal GUARDED_BY(cs_addrLocal);
971 public:
972 
973  NodeId GetId() const {
974  return id;
975  }
976 
977  uint64_t GetLocalNonce() const {
978  return nLocalHostNonce;
979  }
980 
981  int GetMyStartingHeight() const {
982  return nMyStartingHeight;
983  }
984 
985  int GetRefCount() const
986  {
987  assert(nRefCount >= 0);
988  return nRefCount;
989  }
990 
991  bool ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool& complete);
992 
993  void SetRecvVersion(int nVersionIn)
994  {
995  nRecvVersion = nVersionIn;
996  }
997  int GetRecvVersion() const
998  {
999  return nRecvVersion;
1000  }
1001  void SetSendVersion(int nVersionIn);
1002  int GetSendVersion() const;
1003 
1004  CService GetAddrLocal() const;
1006  void SetAddrLocal(const CService& addrLocalIn);
1007 
1009  {
1010  nRefCount++;
1011  return this;
1012  }
1013 
1014  void Release()
1015  {
1016  nRefCount--;
1017  }
1018 
1019 
1020 
1021  void AddAddressKnown(const CAddress& _addr)
1022  {
1023  addrKnown.insert(_addr.GetKey());
1024  }
1025 
1026  void PushAddress(const CAddress& _addr, FastRandomContext &insecure_rand)
1027  {
1028  // Known checking here is only to save space from duplicates.
1029  // SendMessages will filter it again for knowns that were added
1030  // after addresses were pushed.
1031  if (_addr.IsValid() && !addrKnown.contains(_addr.GetKey())) {
1032  if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
1033  vAddrToSend[insecure_rand.randrange(vAddrToSend.size())] = _addr;
1034  } else {
1035  vAddrToSend.push_back(_addr);
1036  }
1037  }
1038  }
1039 
1040 
1041  void AddInventoryKnown(const CInv& inv)
1042  {
1043  AddInventoryKnown(inv.hash);
1044  }
1045 
1046  void AddInventoryKnown(const uint256& hash)
1047  {
1048  {
1049  LOCK(cs_inventory);
1050  filterInventoryKnown.insert(hash);
1051  }
1052  }
1053 
1054  void PushInventory(const CInv& inv)
1055  {
1056  LOCK(cs_inventory);
1057  if (inv.type == MSG_TX || inv.type == MSG_DSTX) {
1058  if (!filterInventoryKnown.contains(inv.hash)) {
1059  LogPrint(BCLog::NET, "PushInventory -- inv: %s peer=%d\n", inv.ToString(), id);
1060  setInventoryTxToSend.insert(inv.hash);
1061  } else {
1062  LogPrint(BCLog::NET, "PushInventory -- filtered inv: %s peer=%d\n", inv.ToString(), id);
1063  }
1064  } else if (inv.type == MSG_BLOCK) {
1065  LogPrint(BCLog::NET, "PushInventory -- inv: %s peer=%d\n", inv.ToString(), id);
1066  vInventoryBlockToSend.push_back(inv.hash);
1067  } else {
1068  if (!filterInventoryKnown.contains(inv.hash)) {
1069  LogPrint(BCLog::NET, "PushInventory -- inv: %s peer=%d\n", inv.ToString(), id);
1070  vInventoryOtherToSend.push_back(inv);
1071  } else {
1072  LogPrint(BCLog::NET, "PushInventory -- filtered inv: %s peer=%d\n", inv.ToString(), id);
1073  }
1074  }
1075  }
1076 
1077  void PushBlockHash(const uint256 &hash)
1078  {
1079  LOCK(cs_inventory);
1080  vBlockHashesToAnnounce.push_back(hash);
1081  }
1082 
1083  void CloseSocketDisconnect(CConnman* connman);
1084 
1085  void copyStats(CNodeStats &stats);
1086 
1088  {
1089  return nLocalServices;
1090  }
1091 
1092  std::string GetAddrName() const;
1094  void MaybeSetAddrName(const std::string& addrNameIn);
1095 
1096  std::string GetLogString() const;
1097 };
1098 
1100 {
1101 public:
1102  static void callCleanup();
1103 };
1104 
1106 int64_t PoissonNextSend(int64_t now, int average_interval_seconds);
1107 
1109 inline std::chrono::microseconds PoissonNextSend(std::chrono::microseconds now, std::chrono::seconds average_interval)
1110 {
1111  return std::chrono::microseconds{PoissonNextSend(now.count(), average_interval.count())};
1112 }
1113 
1114 #endif // BITCOIN_NET_H
void ForEachNodeThen(const Condition &cond, Callable &&pre, CallableAfter &&post)
Definition: net.h:320
void RegisterEvents(CNode *pnode)
Definition: net.cpp:3870
std::vector< CService > vBinds
Definition: net.h:170
std::atomic< bool > flagInterruptMsgProc
Definition: net.h:603
static const int MAX_OUTBOUND_CONNECTIONS
Maximum number of automatic outgoing nodes.
Definition: net.h:70
SocketEventsMode
Definition: net.h:148
uint64_t CalculateKeyedNetGroup(const CAddress &ad) const
Definition: net.cpp:3863
std::unique_ptr< CConnman > g_connman
Definition: init.cpp:97
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)
Definition: net.cpp:3645
int nMaxFeeler
Definition: net.h:590
CNode * FindNode(const CNetAddr &ip, bool fExcludeDisconnecting=true)
Definition: net.cpp:330
bool BannedSetIsDirty()
check is the banlist has unwritten changes
Definition: net.cpp:703
std::vector< CSubNet > vWhitelistedRange
Definition: net.h:169
std::atomic< uint64_t > nPingNonceSent
Definition: net.h:924
uint256 data_hash
Definition: net.h:758
void SocketHandler()
Definition: net.cpp:1653
bool IsReachable(enum Network net)
check whether a given network is one we can probably connect to
Definition: net.cpp:316
static constexpr const CAllNodes AllNodes
Definition: net.h:225
CCriticalSection cs_addrName
Definition: net.h:965
int nStartingHeight
Definition: net.h:732
std::atomic_bool fPauseSend
Definition: net.h:875
std::vector< uint256 > vPendingMasternodes
Definition: net.h:571
void ThreadOpenAddedConnections()
Definition: net.cpp:2459
void SetBannedSetDirty(bool dirty=true)
set the "dirty" flag for the banlist
Definition: net.cpp:709
static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH
Maximum length of incoming protocol messages (no message over 3 MiB is currently acceptable).
Definition: net.h:66
int GetSendVersion() const
Definition: net.cpp:887
void OpenMasternodeConnection(const CAddress &addrConnect, bool probe=false)
Definition: net.cpp:2697
std::atomic_bool fCanSendData
Definition: net.h:878
mapMsgCmdSize mapRecvBytesPerMsgCmd
Definition: net.h:736
void SetBanned(const banmap_t &banmap)
Definition: net.cpp:668
std::atomic< bool > fNetworkActive
Definition: net.h:561
void UnregisterEvents(CNode *pnode)
Definition: net.cpp:3893
bool fMsgProcWake
flag for waking the message processor.
Definition: net.h:599
ServiceFlags
nServices flags
Definition: protocol.h:280
static const uint64_t MAX_UPLOAD_TIMEFRAME
The default timeframe for -maxuploadtarget.
Definition: net.h:90
CCriticalSection cs_filter
Definition: net.h:868
BanReason
Definition: addrdb.h:19
int64_t nTimeOffset
Definition: net.h:726
bool fListen
Definition: net.cpp:113
CConnman(uint64_t seed0, uint64_t seed1)
Definition: net.cpp:2903
void SetMasternodeQuorumNodes(Consensus::LLMQType llmqType, const uint256 &quorumHash, const std::set< uint256 > &proTxHashes)
Definition: net.cpp:3316
Definition: init.h:18
size_t GetAddressCount() const
Definition: net.cpp:3257
std::atomic< int > nBestHeight
Definition: net.h:591
void WakeMessageHandler()
Definition: net.cpp:1928
std::set< NodeId > GetMasternodeQuorumNodes(Consensus::LLMQType llmqType, const uint256 &quorumHash) const
Definition: net.cpp:3344
void SetServices(const CService &addr, ServiceFlags nServices)
Definition: net.cpp:3262
std::string ToString() const
Definition: protocol.cpp:283
void Interrupt()
Definition: net.cpp:3141
size_t SocketSendData(CNode *pnode)
Definition: net.cpp:956
std::atomic< bool > qwatch
Definition: net.h:947
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(cs_mapLocalHost)
static const bool DEFAULT_FORCEDNSSEED
Definition: net.h:94
const uint64_t nKeyedNetGroup
Definition: net.h:872
void SweepBanned()
clean unused entries (if bantime has expired)
Definition: net.cpp:675
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:296
bool ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool &complete)
Definition: net.cpp:820
bool ForEachNodeContinueIf(const Condition &cond, Callable &&func) const
Definition: net.h:271
CNode & operator=(const CNode &)=delete
int GetRecvVersion() const
Definition: net.h:997
mapMsgCmdSize mapSendBytesPerMsgCmd
Definition: net.h:882
void insert(const std::vector< unsigned char > &vKey)
Definition: bloom.cpp:341
std::vector< unsigned char > data
Definition: net.h:131
inv message data
Definition: protocol.h:429
bool fRelayTxes
Definition: net.cpp:114
unsigned int nReceiveFloodSize
Definition: net.h:165
mapMsgCmdSize mapSendBytesPerMsgCmd
Definition: net.h:734
CClientUIInterface * uiInterface
Definition: net.h:162
void resize(size_type n, value_type c=0)
Definition: streams.h:196
void CloseSocketDisconnect(CConnman *connman)
Definition: net.cpp:535
CCriticalSection cs_hSocket
Definition: net.h:813
std::atomic< bool > wakeupSelectNeeded
Definition: net.h:611
size_t GetMaxOutboundNodeCount()
Definition: net.cpp:3425
uint64_t randrange(uint64_t range)
Generate a random integer in the range [0..range).
Definition: random.h:107
ServiceFlags nServices
Definition: net.h:721
bool fSendMempool
Definition: net.h:914
CCriticalSection cs_SubVer
Definition: net.h:844
bool GetTryNewOutboundPeer()
Definition: net.cpp:2186
std::atomic< int64_t > m_next_send_inv_to_incoming
Definition: net.h:637
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:76
std::mutex mutexMsgProc
Definition: net.h:602
CCriticalSection cs_addrLocal
Definition: net.h:970
unsigned int nHdrPos
Definition: net.h:764
int nMaxAddnode
Definition: net.h:589
CCriticalSection cs_mnauth
Definition: net.h:938
RAII-style semaphore lock.
Definition: sync.h:231
friend struct CConnmanTest
Definition: net.h:639
bool Unban(const CNetAddr &ip)
Definition: net.cpp:642
uint64_t GetMaxOutboundTarget()
Definition: net.cpp:3549
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:72
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
Definition: net.cpp:3733
void SetMaxOutboundTimeframe(uint64_t timeframe)
set the timeframe for the max outbound target
Definition: net.cpp:3575
std::string cleanSubVer
Definition: net.h:729
Interface for message handling.
Definition: net.h:665
void SetVersion(int nVersionIn)
Definition: net.h:788
RollingBloomFilter is a probabilistic "keep track of most recently inserted" set. ...
Definition: bloom.h:126
int flags
Definition: dash-tx.cpp:462
void GetBanned(banmap_t &banmap)
Definition: net.cpp:660
NetEventsInterface * m_msgproc
Definition: net.h:593
std::atomic< int64_t > nPingUsecStart
Definition: net.h:926
uint256 verifiedPubKeyHash
Definition: net.h:942
void ClearBanned()
Definition: net.cpp:565
CCriticalSection cs_vNodes
Definition: net.h:578
int nMaxConnections
Definition: net.h:157
CSerializedNetMsg()=default
int64_t nTimeConnected
Definition: net.h:725
void AdvertiseLocal(CNode *pnode)
Definition: net.cpp:209
void MapPort(bool fUseUPnP)
Definition: net.cpp:2065
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:103
CCriticalSection cs_vAddedNodes
Definition: net.h:570
void SetTryNewOutboundPeer(bool flag)
Definition: net.cpp:2191
void AddInventoryKnown(const uint256 &hash)
Definition: net.h:1046
bool IsConnected(const CService &addr, std::function< bool(const CNode *pnode)> cond)
Definition: net.h:242
uint32_t nMessageSize
Definition: protocol.h:59
A hasher class for Bitcoin&#39;s 256-bit hash (double SHA-256).
Definition: hash.h:35
ListenSocket(SOCKET socket_, bool whitelisted_)
Definition: net.h:475
CCriticalSection cs_inventory
Definition: net.h:908
uint64_t GetLocalNonce() const
Definition: net.h:977
CDataStream hdrbuf
Definition: net.h:762
std::set< uint256 > setInventoryTxToSend
Definition: net.h:901
void ThreadSocketHandler()
Definition: net.cpp:1908
std::vector< CAddress > vAddrToSend
Definition: net.h:890
bool fMasternode
Definition: net.h:864
bool operator()(const CNode *) const
Definition: net.h:222
std::vector< CService > vWhiteBinds
Definition: net.h:170
size_t GetNodeCount(NumConnections num)
Definition: net.cpp:3408
static boost::thread_group threadGroup
Definition: init.cpp:212
std::atomic< int > nStartingHeight
Definition: net.h:887
void PushAddress(const CAddress &_addr, FastRandomContext &insecure_rand)
Definition: net.h:1026
static CScheduler scheduler
Definition: init.cpp:213
std::thread threadOpenMasternodeConnections
Definition: net.h:629
static const int FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes or 120 seconds.
Definition: net.h:60
std::set< uint256 > GetMasternodeQuorums(Consensus::LLMQType llmqType)
Definition: net.cpp:3331
static const int TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:56
void SetRecvVersion(int nVersionIn)
Definition: net.h:993
bool in_data
Definition: net.h:760
std::atomic< int64_t > timeLastMempoolReq
Definition: net.h:921
void AddOneShot(const std::string &strDest)
Definition: net.cpp:120
static constexpr const CFullyConnectedOnly FullyConnectedOnly
Definition: net.h:219
Signals for UI communication.
Definition: ui_interface.h:28
std::atomic_bool fOtherSideDisconnected
Definition: net.h:856
std::list< CNetMessage > vRecvMsg
Definition: net.h:963
std::set< uint256 > masternodePendingProbes
Definition: net.h:573
CNetMessage(const CMessageHeader::MessageStartChars &pchMessageStartIn, int nTypeIn, int nVersionIn)
Definition: net.h:771
void NotifyNumConnectionsChanged()
Definition: net.cpp:1388
void PushInventory(const CInv &inv)
Definition: net.h:1054
void SetMaxOutboundTarget(uint64_t limit)
set the max outbound target in bytes
Definition: net.cpp:3543
void RecordBytesSent(uint64_t bytes)
Definition: net.cpp:3526
CAddrMan addrman
Definition: net.h:566
std::set< uint256 > orphan_work_set
Definition: net.h:949
std::atomic< ServiceFlags > nServices
Definition: net.h:805
void SetAddrLocal(const CService &addrLocalIn)
May not be called more than once.
Definition: net.cpp:741
int nSendVersion
Definition: net.h:962
std::deque< CInv > vRecvGetData
Definition: net.h:822
void AddPendingProbeConnections(const std::set< uint256 > &proTxHashes)
Definition: net.cpp:3402
uint64_t GetMaxOutboundTimeframe()
Definition: net.cpp:3555
void ForEachNode(const Condition &cond, Callable &&func)
Definition: net.h:288
std::vector< CNode * > CopyNodeVector()
Definition: net.cpp:3845
bool fConnected
Definition: net.h:115
int GetRefCount() const
Definition: net.h:985
bool ForNode(NodeId id, Callable &&func)
Definition: net.h:237
ServiceFlags nLocalServices
Services this instance offers.
Definition: net.h:583
bool ForEachNodeContinueIf(Callable &&func) const
Definition: net.h:282
CDataStream vRecv
Definition: net.h:766
bool contains(const std::vector< unsigned char > &vKey) const
Definition: bloom.cpp:378
void WakeSelect()
Definition: net.cpp:1937
bool IsWhitelistedRange(const CNetAddr &addr)
Definition: net.cpp:716
SocketEventsMode socketEventsMode
Definition: net.h:613
bool IsValid() const
Definition: netaddress.cpp:191
bool DisconnectNode(const std::string &node)
Definition: net.cpp:3444
std::set< uint256 > setKnown
Definition: net.h:893
bool operator()(I first, I last) const
Definition: net.h:652
bool m_manual_connection
Definition: net.h:731
Stochastical (IP) address manager.
Definition: addrman.h:182
void ForEachNodeThen(const Condition &cond, Callable &&pre, CallableAfter &&post) const
Definition: net.h:337
std::atomic< int64_t > nLastSend
Definition: net.h:826
void RecordBytesRecv(uint64_t bytes)
Definition: net.cpp:3520
virtual bool SendMessages(CNode *pnode, std::atomic< bool > &interrupt)=0
void DumpAddresses()
Definition: net.cpp:2152
bool fSentAddr
Definition: net.h:862
std::atomic< bool > fFirstMessageIsMNAUTH
Definition: net.h:832
CHash256 hasher
Definition: net.h:757
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:95
std::unordered_map< SOCKET, CNode * > mapSocketToNode
Definition: net.h:577
bool IsMasternodeQuorumNode(const CNode *pnode)
Definition: net.cpp:3372
std::atomic< int64_t > nPingUsecTime
Definition: net.h:928
LLMQType
Definition: params.h:48
void RemoveMasternodeQuorumNodes(Consensus::LLMQType llmqType, const uint256 &quorumHash)
Definition: net.cpp:3366
std::atomic< int64_t > nMinPingUsecTime
Definition: net.h:930
int GetMyStartingHeight() const
Definition: net.h:981
void Ban(const CNetAddr &netAddr, const BanReason &reason, int64_t bantimeoffset=0, bool sinceUnixEpoch=false)
Definition: net.cpp:605
ServiceFlags GetLocalServices() const
Definition: net.h:1087
int nVersion
Definition: net.h:728
std::map< CSubNet, CBanEntry > banmap_t
Definition: addrdb.h:77
bool fClient
Definition: net.h:849
bool ForNode(NodeId id, std::function< bool(const CNode *pnode)> cond, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:3795
uint64_t GetOutboundTargetBytesLeft()
response the bytes left in the current max outbound cycle
Definition: net.cpp:3607
void ForEachNode(const Condition &cond, Callable &&func) const
Definition: net.h:304
void Release()
Definition: net.h:1014
bool GetLocal(CService &addr, const CNetAddr *paddrPeer=nullptr)
Definition: net.cpp:132
static bool NodeFullyConnected(const CNode *pnode)
Definition: net.cpp:3728
unsigned int nPrevNodeCount
Definition: net.h:580
bool AddNode(const std::string &node)
Definition: net.cpp:3282
size_t nProcessQueueSize
Definition: net.h:818
std::condition_variable condMsgProc
Definition: net.h:601
bool result_type
Definition: net.h:649
CService GetAddrLocal() const
Definition: net.cpp:736
uint64_t GetMaxOutboundTimeLeftInCycle()
response the time in second left in the current max outbound cycle
Definition: net.cpp:3561
NumConnections
Definition: clientmodel.h:34
void InactivityCheck(CNode *pnode)
Definition: net.cpp:1409
std::atomic< int64_t > nLastRecv
Definition: net.h:827
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition: net.h:596
bool fOneShot
Definition: net.h:847
bool InitBinds(const std::vector< CService > &binds, const std::vector< CService > &whiteBinds)
Definition: net.cpp:2940
bool BindListenPort(const CService &bindAddr, std::string &strError, bool fWhitelisted=false)
std::thread threadOpenAddedConnections
Definition: net.h:627
#define LOCK(cs)
Definition: sync.h:178
std::vector< CNode * > vNodes
Definition: net.h:575
ServiceFlags GetLocalServices() const
Definition: net.cpp:3628
bool IsPeerAddrLocalGood(CNode *pnode)
Definition: net.cpp:201
void ThreadOpenMasternodeConnections()
Definition: net.cpp:2486
NetEventsInterface * m_msgproc
Definition: net.h:163
int type
Definition: protocol.h:455
bool operator()(const CNode *pnode) const
Definition: net.h:214
std::string strAddedNode
Definition: net.h:113
bool fMasternode
Definition: net.h:749
void SocketEventsSelect(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set, bool fOnlyPoll)
Definition: net.cpp:1557
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:143
Fast randomness source.
Definition: random.h:48
const CAddress addrBind
Definition: net.h:836
std::vector< std::string > vSeedNodes
Definition: net.h:168
bool ForEachNodeContinueIf(Callable &&func)
Definition: net.h:265
int64_t PoissonNextSendInbound(int64_t now, int average_interval_seconds)
Attempts to obfuscate tx time through exponentially distributed emitting.
Definition: net.cpp:3814
bool OutboundTargetReached(bool historicalBlockServingLimit)
check if the outbound target is reached
Definition: net.cpp:3587
std::vector< std::string > m_specified_outgoing
Definition: net.h:172
void DumpData()
Definition: net.cpp:2163
std::vector< CAddress > GetAddresses()
Definition: net.cpp:3277
void DisconnectNodes()
Definition: net.cpp:1282
void RelayInvFiltered(CInv &inv, const CTransaction &relatedTx, const int minProtoVersion=MIN_PEER_PROTO_VERSION, bool fAllowMasternodeConnections=false)
Definition: net.cpp:3491
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:585
void ThreadOpenConnections(std::vector< std::string > connect)
Definition: net.cpp:2221
std::thread threadMessageHandler
Definition: net.h:630
CMessageHeader hdr
Definition: net.h:763
void ForEachNodeThen(Callable &&pre, CallableAfter &&post)
Definition: net.h:331
bool m_manual_connection
Definition: net.h:848
bool fInbound
Definition: net.h:730
void ProcessOneShot()
Definition: net.cpp:2169
bool RemoveLocal(const CService &addr)
Definition: net.cpp:267
A CService with information about it as peer.
Definition: protocol.h:358
bool ForEachNodeContinueIf(const Condition &cond, Callable &&func)
Definition: net.h:254
bool Start(CScheduler &scheduler, const Options &options)
Definition: net.cpp:2957
size_t SocketRecvData(CNode *pnode)
Definition: net.cpp:1840
uint64_t nRecvBytes
Definition: net.h:735
std::vector< unsigned char > GetKey() const
Definition: netaddress.cpp:557
void MaybeSetAddrName(const std::string &addrNameIn)
Sets the addrName only if it was not previously set.
Definition: net.cpp:729
uint256 hash
Definition: protocol.h:456
uint64_t GetTotalBytesRecv()
Definition: net.cpp:3616
bool fInbound
Definition: net.h:116
double dPingTime
Definition: net.h:738
std::string addrName
Definition: net.h:727
int nMaxFeeler
Definition: net.h:160
Network
Definition: netaddress.h:21
std::vector< uint256 > vBlockHashesToAnnounce
Definition: net.h:912
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:635
int64_t NodeId
Definition: net.h:109
virtual void FinalizeNode(NodeId id, bool &update_connection_time)=0
Definition: net.h:136
void SetNetworkActive(bool active)
Definition: net.cpp:2886
void AddNewAddresses(const std::vector< CAddress > &vAddr, const CAddress &addrFrom, int64_t nTimePenalty=0)
Definition: net.cpp:3272
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:86
bool GetNetworkActive() const
Definition: net.h:206
bool fMasternodeProbe
Definition: net.h:866
uint256 sentMNAuthChallenge
Definition: net.h:939
NumConnections
Definition: net.h:141
std::atomic< int64_t > nTimeFirstMessageReceived
Definition: net.h:831
bool fGetAddr
Definition: net.h:892
CClientUIInterface * clientInterface
Definition: net.h:592
NodeId GetId() const
Definition: net.h:973
void GetNodeStats(std::vector< CNodeStats > &vstats)
Definition: net.cpp:3430
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition: net.cpp:3858
uint64_t nSendBytes
Definition: net.h:733
int nMaxOutbound
Definition: net.h:158
size_t nSendOffset
Definition: net.h:808
std::atomic_bool fDisconnect
Definition: net.h:853
int nMaxConnections
Definition: net.h:587
void SetLimited(enum Network net, bool fLimited=true)
Make a particular network entirely off-limits (no automatic connects to it)
Definition: net.cpp:276
size_t nSendSize
Definition: net.h:807
void ForEachNode(Callable &&func)
Definition: net.h:298
std::atomic< int64_t > nLastWarningTime
Definition: net.h:830
CCriticalSection cs_vOneShots
Definition: net.h:568
CRollingBloomFilter addrKnown
Definition: net.h:891
bool IsBanned(CNetAddr ip)
Definition: net.cpp:577
void DumpBanlist()
Definition: net.cpp:515
CCriticalSection cs_setBanned
Definition: net.h:563
unsigned int GetReceiveFloodSize() const
Definition: net.cpp:3643
int readData(const char *pch, unsigned int nBytes)
Definition: net.cpp:931
unsigned char MessageStartChars[MESSAGE_START_SIZE]
Definition: protocol.h:38
static const int INBOUND_EVICTION_PROTECTION_TIME
Eviction protection time for incoming connections.
Definition: net.h:74
~CNode()
Definition: net.cpp:3723
void DeleteNode(CNode *pnode)
Definition: net.cpp:3240
unsigned int SOCKET
Definition: compat.h:62
bool CheckIncomingNonce(uint64_t nonce)
Definition: net.cpp:386
CCriticalSection cs_vPendingMasternodes
Definition: net.h:574
const CAddress addr
Definition: net.h:834
bool AddPendingMasternode(const uint256 &proTxHash)
Definition: net.cpp:3305
std::atomic< int > nRefCount
Definition: net.h:870
bool ForNode(const CService &addr, Callable &&func)
Definition: net.h:231
const int64_t nTimeConnected
Definition: net.h:828
int64_t nTime
Definition: net.h:769
uint64_t nMaxOutboundTimeframe
Definition: net.h:166
#define LogPrint(category,...)
Definition: util.h:214
std::unique_ptr< CBloomFilter > pfilter PT_GUARDED_BY(cs_filter)
std::atomic< NodeId > nLastNodeId
Definition: net.h:579
bool RemoveAddedNode(const std::string &node)
Definition: net.cpp:3293
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
Definition: netaddress.h:33
CCriticalSection cs_vRecv
Definition: net.h:814
std::list< CNode * > vNodesDisconnected
Definition: net.h:576
std::atomic< bool > fPingQueued
Definition: net.h:932
CNode * ConnectNode(CAddress addrConnect, const char *pszDest=nullptr, bool fCountFailure=false)
Definition: net.cpp:412
256-bit opaque blob.
Definition: uint256.h:123
int GetBestHeight() const
Definition: net.cpp:3638
void AddInventoryKnown(const CInv &inv)
Definition: net.h:1041
int nScore
Definition: net.h:709
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound=nullptr, const char *strDest=nullptr, bool fOneShot=false, bool fFeeler=false, bool manual_connection=false, bool fConnectToMasternode=false, bool fMasternodeProbe=false)
Definition: net.cpp:2628
SocketEventsMode GetSocketEventsMode() const
Definition: net.h:208
static const unsigned int MAX_ADDR_TO_SEND
The maximum number of new addresses to accumulate before announcing.
Definition: net.h:64
uint256 receivedMNAuthChallenge
Definition: net.h:940
void ReleaseNodeVector(const std::vector< CNode *> &vecNodes)
Definition: net.cpp:3850
bool Bind(const CService &addr, unsigned int flags)
Definition: net.cpp:2927
int nMaxAddnode
Definition: net.h:159
bool fFeeler
Definition: net.h:846
void ForEachNode(Callable &&func) const
Definition: net.h:314
uint256 verifiedProRegTxHash
Definition: net.h:941
std::atomic< int64_t > nLastTXTime
Definition: net.h:918
bool complete() const
Definition: net.h:779
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:96
CAddress addrBind
Definition: net.h:746
const bool fInbound
Definition: net.h:851
std::vector< CSubNet > vWhitelistedRange
Definition: net.h:555
~CConnman()
Definition: net.cpp:3251
CService resolvedAddress
Definition: net.h:114
std::thread threadOpenConnections
Definition: net.h:628
bool AttemptToEvictConnection()
Try to find a connection to evict when the node is full.
Definition: net.cpp:1073
static const uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:88
CSemaphoreGrant grantOutbound
Definition: net.h:867
std::map< std::pair< Consensus::LLMQType, uint256 >, std::set< uint256 > > masternodeQuorumNodes
Definition: net.h:572
uint256 hashContinue
Definition: net.h:886
bool fWhitelisted
Definition: net.h:845
std::map< std::string, uint64_t > mapMsgCmdSize
Definition: net.h:715
static const int MIN_PEER_PROTO_VERSION
disconnect from peers older than this proto version
Definition: version.h:23
const NodeId id
Definition: net.h:957
NodeId GetNewNodeId()
Definition: net.cpp:2921
unsigned int nDataPos
Definition: net.h:767
static const unsigned int DEFAULT_MISBEHAVING_BANTIME
Definition: net.h:99
std::string addrLocal
Definition: net.h:742
bool fAddressesInitialized
Definition: net.h:565
std::thread threadDNSAddressSeed
Definition: net.h:625
ServiceFlags nLocalServices
Definition: net.h:156
uint64_t nMaxOutboundLimit
Definition: net.h:167
void Discover(boost::thread_group &threadGroup)
Definition: net.cpp:2835
std::vector< std::string > m_added_nodes
Definition: net.h:173
CCriticalSection cs_vProcessMsg
Definition: net.h:816
void SetSendVersion(int nVersionIn)
Definition: net.cpp:873
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:3825
std::vector< ListenSocket > vhListenSocket
Definition: net.h:560
void SetBestHeight(int height)
Definition: net.cpp:3633
double dMinPing
Definition: net.h:740
std::atomic< int64_t > nTimeOffset
Definition: net.h:829
std::string GetLogString() const
Definition: net.cpp:750
void PushBlockHash(const uint256 &hash)
Definition: net.h:1077
std::string command
Definition: net.h:132
void ForEachNodeThen(Callable &&pre, CallableAfter &&post) const
Definition: net.h:348
CCriticalSection cs_totalBytesSent
Definition: net.h:543
std::atomic_bool fSuccessfullyConnected
Definition: net.h:852
SipHash-2-4.
Definition: hash.h:266
void ThreadMessageHandler()
Definition: net.cpp:2701
std::atomic< int64_t > nDisconnectLingerTime
Definition: net.h:854
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of strSubVer in version message.
Definition: net.h:68
void RelayInv(CInv &inv, const int minProtoVersion=MIN_PEER_PROTO_VERSION, bool fAllowMasternodeConnections=false)
Definition: net.cpp:3482
std::atomic_bool fHasRecvData
Definition: net.h:877
uint64_t nTotalBytesRecv GUARDED_BY(cs_totalBytesRecv)
std::atomic< int > nVersion
Definition: net.h:838
bool fRelayTxes
Definition: net.h:861
static const bool DEFAULT_UPNP
-upnp default
Definition: net.h:81
int nMaxOutbound
Definition: net.h:588
bool HasMasternodeQuorumNodes(Consensus::LLMQType llmqType, const uint256 &quorumHash)
Definition: net.cpp:3325
bool IsMasternodeOrDisconnectRequested(const CService &addr)
Definition: net.cpp:3808
unsigned int nSendBufferMaxSize
Definition: net.h:557
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:92
const uint64_t nLocalHostNonce
Definition: net.h:958
unsigned int nSendBufferMaxSize
Definition: net.h:164
static const int PING_INTERVAL
Time between pings automatically sent out for latency probing and keepalive (in seconds).
Definition: net.h:54
int readHeader(const char *pch, unsigned int nBytes)
Definition: net.cpp:900
bool m_limited_node
Definition: net.h:850
uint256 verifiedProRegTxHash
Definition: net.h:748
const ServiceFlags nLocalServices
Definition: net.h:960
int GetExtraOutboundCount()
Definition: net.cpp:2203
std::atomic_bool fSocketShutdown
Definition: net.h:855
std::atomic< bool > fSendRecSigs
Definition: net.h:945
SOCKET hSocket GUARDED_BY(cs_hSocket)
uint64_t GetTotalBytesSent()
Definition: net.cpp:3622
bool GenerateSelectSet(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set)
Definition: net.cpp:1442
void AcceptConnection(const ListenSocket &hListenSocket)
Definition: net.cpp:1167
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:118
std::atomic< bool > fSendDSQueue
Definition: net.h:935
CCriticalSection cs_sendProcessing
Definition: net.h:820
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:198
void MarkAddressGood(const CAddress &addr)
Definition: net.cpp:3267
Information about a peer.
Definition: net.h:800
SocketEventsMode socketEventsMode
Definition: net.h:174
std::thread threadSocketHandler
Definition: net.h:626
static const int WARNING_INTERVAL
Minimum time between warnings printed to log.
Definition: net.h:58
Definition: net.h:677
static void callCleanup()
Definition: net.cpp:3133
bool fWhitelisted
Definition: net.h:737
virtual void InitializeNode(CNode *pnode)=0
std::string GetAddrName() const
Definition: net.cpp:724
CCriticalSection cs_vSend
Definition: net.h:812
void RelayTransaction(const CTransaction &tx)
Definition: net.cpp:3465
bool fDiscover
Definition: net.cpp:112
void SetVersion(int n)
Definition: streams.h:296
void AddAddressKnown(const CAddress &_addr)
Definition: net.h:1021
std::atomic< size_t > nSendMsgSize
Definition: net.h:811
void copyStats(CNodeStats &stats)
Definition: net.cpp:757
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
std::atomic< int > nNumWarningsSkipped
Definition: net.h:837
std::atomic_bool fPauseRecv
Definition: net.h:874
CNode * AddRef()
Definition: net.h:1008
std::unique_ptr< CSemaphore > semAddnode
Definition: net.h:586
double dPingWait
Definition: net.h:739
void Init(const Options &connOptions)
Definition: net.h:177
CThreadInterrupt interruptNet
Definition: net.h:605
CCriticalSection cs_totalBytesRecv
Definition: net.h:542
CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
Definition: net.cpp:180
static const unsigned int MAX_INV_SZ
The maximum number of entries in an &#39;inv&#39; protocol message.
Definition: net.h:62
std::chrono::microseconds nNextInvSend
Definition: net.h:909
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
Definition: net.cpp:236
const uint64_t nSeed1
Definition: net.h:596
void Stop()
Definition: net.cpp:3165
bool m_use_addrman_outgoing
Definition: net.h:171
std::atomic< int > nRecvVersion
Definition: net.h:824
std::atomic< int64_t > nLastBlockTime
Definition: net.h:917
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:309
CCriticalSection cs_mapLocalHost
Definition: net.cpp:115
CCriticalSection cs_mapNodesWithDataToSend
Definition: net.h:623
std::vector< CInv > vInventoryOtherToSend
Definition: net.h:907
bool fRelayTxes
Definition: net.h:722
std::vector< AddedNodeInfo > GetAddedNodeInfo()
Definition: net.cpp:2405
Definition: net.h:682
int64_t nLastSend
Definition: net.h:723
const uint256 & GetMessageHash() const
Definition: net.cpp:948
unsigned short GetListenPort()
Definition: net.cpp:126
const int nMyStartingHeight
Definition: net.h:961
bool IsLimited(enum Network net)
Definition: net.cpp:284
void SocketEvents(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set, bool fOnlyPoll)
Definition: net.cpp:1632
virtual bool ProcessMessages(CNode *pnode, std::atomic< bool > &interrupt)=0
Wrapped mutex: supports recursive locking, but no waiting TODO: We should move away from using the re...
Definition: sync.h:94
int nBestHeight
Definition: net.h:161
NodeId nodeid
Definition: net.h:720
int wakeupPipe[2]
a pipe which is added to select() calls to wakeup before the timeout
Definition: net.h:609
int64_t nLastRecv
Definition: net.h:724
unsigned int nReceiveFloodSize
Definition: net.h:558
CAddress addr
Definition: net.h:744
Message header.
Definition: protocol.h:28
bool BindListenPort(const CService &bindAddr, std::string &strError, bool fWhitelisted=false)
Definition: net.cpp:2752
void ThreadDNSAddressSeed()
Definition: net.cpp:2076
Released under the MIT license