PIVX Core  5.6.99
P2P Digital Currency
net.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 The Bitcoin developers
3 // Copyright (c) 2015-2022 The PIVX Core developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #ifndef PIVX_NET_H
8 #define PIVX_NET_H
9 
10 #include "addrdb.h"
11 #include "addrman.h"
12 #include "bloom.h"
13 #include "compat.h"
14 #include "crypto/siphash.h"
15 #include "fs.h"
16 #include "hash.h"
17 #include "limitedmap.h"
18 #include "netaddress.h"
19 #include "protocol.h"
20 #include "random.h"
21 #include "streams.h"
22 #include "sync.h"
23 #include "uint256.h"
24 #include "utilstrencodings.h"
25 #include "threadinterrupt.h"
26 #include "validation.h"
27 
28 #include <atomic>
29 #include <cstdint>
30 #include <deque>
31 #include <thread>
32 #include <memory>
33 #include <condition_variable>
34 
35 #ifndef WIN32
36 #include <arpa/inet.h>
37 #endif
38 
39 // "Optimistic send" was introduced in the beginning of the Bitcoin project. I assume this was done because it was
40 // thought that "send" would be very cheap when the send buffer is empty. This is not true, as shown by profiling.
41 // When a lot of load is seen on the network, the "send" call done in the message handler thread can easily use up 20%
42 // of time, effectively blocking things that could be done in parallel. We have introduced a way to wake up the select()
43 // call in the network thread, which allows us to disable optimistic send without introducing an artificial latency/delay
44 // when sending data. This however only works on non-WIN32 platforms for now. When we add support for WIN32 platforms,
45 // we can completely remove optimistic send.
46 #ifdef WIN32
47 #define DEFAULT_ALLOW_OPTIMISTIC_SEND true
48 #else
49 #define DEFAULT_ALLOW_OPTIMISTIC_SEND false
50 #define USE_WAKEUP_PIPE
51 #endif
52 
53 class CAddrMan;
54 class CBlockIndex;
55 class CScheduler;
56 class CNode;
57 class TierTwoConnMan;
58 
60 static const int PING_INTERVAL = 2 * 60;
62 static const int TIMEOUT_INTERVAL = 20 * 60;
64 static const int FEELER_INTERVAL = 120;
66 static const unsigned int MAX_INV_SZ = 50000;
68 static const unsigned int MAX_LOCATOR_SZ = 101;
70 static constexpr size_t MAX_ADDR_TO_SEND = 1000;
72 static constexpr double MAX_ADDR_RATE_PER_SECOND{0.1};
76 static constexpr size_t MAX_ADDR_PROCESSING_TOKEN_BUCKET{MAX_ADDR_TO_SEND};
78 static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 2 * 1024 * 1024;
80 static const unsigned int MAX_SUBVERSION_LENGTH = 256;
82 static const int MAX_OUTBOUND_CONNECTIONS = 16;
84 static const int MAX_ADDNODE_CONNECTIONS = 16;
86 static const int INBOUND_EVICTION_PROTECTION_TIME = 1;
88 static const bool DEFAULT_LISTEN = true;
90 static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ;
92 static const size_t SETASKFOR_MAX_SZ = 2 * MAX_INV_SZ;
94 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
96 #define ENOUGH_CONNECTIONS 2
98 #define MAX_TIMEOFFSET_DISCONNECTIONS 16
99 
100 static const ServiceFlags REQUIRED_SERVICES = NODE_NETWORK;
101 
102 static const bool DEFAULT_FORCEDNSSEED = false;
103 static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
104 static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
105 
106 // NOTE: When adjusting this, update rpcnet:setban's help ("24h")
107 static const unsigned int DEFAULT_MISBEHAVING_BANTIME = 60 * 60 * 24; // Default 24-hour ban
108 
109 typedef int NodeId;
110 
112 {
113  std::string strAddedNode;
116  bool fInbound;
117 
118  AddedNodeInfo(const std::string& _strAddedNode, const CService& _resolvedAddress, bool _fConnected, bool _fInbound):
119  strAddedNode(_strAddedNode),
120  resolvedAddress(_resolvedAddress),
121  fConnected(_fConnected),
122  fInbound(_fInbound)
123  {}
124 };
125 
126 class CTransaction;
127 class CNodeStats;
128 class CClientUIInterface;
129 
131 {
132  CSerializedNetMsg() = default;
135  // No copying, only moves.
136  CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
138 
139  std::vector<unsigned char> data;
140  std::string command;
141 };
142 
143 class NetEventsInterface;
144 class CConnman
145 {
146 public:
147 
150  CONNECTIONS_IN = (1U << 0),
151  CONNECTIONS_OUT = (1U << 1),
153  };
154 
155  struct Options
156  {
160  int nMaxOutbound = 0;
161  int nMaxAddnode = 0;
162  int nMaxFeeler = 0;
163  int nBestHeight = 0;
166  unsigned int nSendBufferMaxSize = 0;
167  unsigned int nReceiveFloodSize = 0;
168  std::vector<bool> m_asmap;
169  std::vector<std::string> vSeedNodes;
170  std::vector<CSubNet> vWhitelistedRange;
171  std::vector<CService> vBinds, vWhiteBinds;
173  std::vector<std::string> m_specified_outgoing;
174  std::vector<std::string> m_added_nodes;
175  };
176 
177  void Init(const Options& connOptions) {
178  nLocalServices = connOptions.nLocalServices;
179  nRelevantServices = connOptions.nRelevantServices;
180  nMaxConnections = connOptions.nMaxConnections;
181  nMaxOutbound = std::min(connOptions.nMaxOutbound, connOptions.nMaxConnections);
182  nMaxAddnode = connOptions.nMaxAddnode;
183  nMaxFeeler = connOptions.nMaxFeeler;
184  nBestHeight = connOptions.nBestHeight;
185  clientInterface = connOptions.uiInterface;
187  nReceiveFloodSize = connOptions.nReceiveFloodSize;
188  vWhitelistedRange = connOptions.vWhitelistedRange;
189  {
191  vAddedNodes = connOptions.m_added_nodes;
192  }
193  }
194 
195  CConnman(uint64_t seed0, uint64_t seed1);
196  ~CConnman();
197  bool Start(CScheduler& scheduler, const Options& options);
198  void Stop();
199  void Interrupt();
200  bool GetNetworkActive() const { return fNetworkActive; };
201  void SetNetworkActive(bool active);
202  void OpenNetworkConnection(const CAddress& addrConnect,
203  bool fCountFailure,
204  CSemaphoreGrant* grantOutbound = nullptr,
205  const char* strDest = nullptr,
206  bool fOneShot = false,
207  bool fFeeler = false,
208  bool fAddnode = false,
209  bool masternode_connection = false,
210  bool masternode_probe_connection = false);
211  bool CheckIncomingNonce(uint64_t nonce);
212 
214  bool operator() (const CNode* pnode) const {
215  return NodeFullyConnected(pnode);
216  }
217  };
218  struct CAllNodes {
219  bool operator() (const CNode*) const {return true;}
220  };
221  constexpr static const CFullyConnectedOnly FullyConnectedOnly{};
222  constexpr static const CAllNodes AllNodes{};
223 
224  bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
225  bool ForNode(const CService& addr, const std::function<bool(const CNode* pnode)>& cond, const std::function<bool(CNode* pnode)>& func);
226 
227  void PushMessage(CNode* pnode, CSerializedNetMsg&& msg, bool allowOptimisticSend = DEFAULT_ALLOW_OPTIMISTIC_SEND);
228 
229  template<typename Callable>
230  bool ForEachNodeContinueIf(Callable&& func)
231  {
232  LOCK(cs_vNodes);
233  for (auto&& node : vNodes)
234  if (NodeFullyConnected(node)) {
235  if (!func(node))
236  return false;
237  }
238  return true;
239  };
240 
241  template<typename Callable>
243  {
244  FastRandomContext ctx;
245  LOCK(cs_vNodes);
246  std::vector<CNode*> nodesCopy = vNodes;
247  std::shuffle(nodesCopy.begin(), nodesCopy.end(), ctx);
248  for (auto&& node : nodesCopy)
249  if (NodeFullyConnected(node)) {
250  if (!func(node))
251  return false;
252  }
253  return true;
254  };
255 
256  template<typename Callable>
257  void ForEachNode(Callable&& func)
258  {
259  LOCK(cs_vNodes);
260  for (auto&& node : vNodes) {
261  if (NodeFullyConnected(node))
262  func(node);
263  }
264  };
265 
266  template<typename Callable>
267  void ForEachNode(Callable&& func) const
268  {
269  LOCK(cs_vNodes);
270  for (auto&& node : vNodes) {
271  if (NodeFullyConnected(node))
272  func(node);
273  }
274  };
275 
276  template<typename Callable, typename CallableAfter>
277  void ForEachNodeThen(Callable&& pre, CallableAfter&& post)
278  {
279  LOCK(cs_vNodes);
280  for (auto&& node : vNodes) {
281  if (NodeFullyConnected(node))
282  pre(node);
283  }
284  post();
285  };
286 
287  template<typename Callable, typename CallableAfter>
288  void ForEachNodeThen(Callable&& pre, CallableAfter&& post) const
289  {
290  LOCK(cs_vNodes);
291  for (auto&& node : vNodes) {
292  if (NodeFullyConnected(node))
293  pre(node);
294  }
295  post();
296  };
297 
298  std::vector<CNode*> CopyNodeVector(std::function<bool(const CNode* pnode)> cond);
299  std::vector<CNode*> CopyNodeVector();
300  void ReleaseNodeVector(const std::vector<CNode*>& vecNodes);
301 
302  // Clears AskFor requests for every known peer
303  void RemoveAskFor(const uint256& invHash, int invType);
304 
305  void RelayInv(CInv& inv, int minProtoVersion = ActiveProtocol());
306  bool IsNodeConnected(const CAddress& addr);
307  // Retrieves a connected peer (if connection success). Used only to check peer address availability for now.
308  CNode* ConnectNode(const CAddress& addrConnect);
309 
310  // Addrman functions
311  void SetServices(const CService &addr, ServiceFlags nServices);
312  void MarkAddressGood(const CAddress& addr);
313  void AddNewAddress(const CAddress& addr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
314  bool AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
322  std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct, Optional<Network> network);
323 
324  // Denial-of-service detection/prevention
325  // The idea is to detect peers that are behaving
326  // badly and disconnect/ban them, but do it in a
327  // one-coding-mistake-won't-shatter-the-entire-network
328  // way.
329  // IMPORTANT: There should be nothing I can give a
330  // node that it will forward on that will make that
331  // node's peers drop it. If there is, an attacker
332  // can isolate a node and/or try to split the network.
333  // Dropping a node for sending stuff that is invalid
334  // now but might be valid in a later version is also
335  // dangerous, because it can cause a network split
336  // between nodes running old code and nodes running
337  // new code.
338  void Ban(const CNetAddr& netAddr, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
339  void Ban(const CSubNet& subNet, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
340  void ClearBanned(); // needed for unit testing
341  bool IsBanned(CNetAddr ip);
342  bool IsBanned(CSubNet subnet);
343  bool Unban(const CNetAddr &ip);
344  bool Unban(const CSubNet &ip);
345  void GetBanned(banmap_t &banmap);
346  void SetBanned(const banmap_t &banmap);
347 
348  bool AddNode(const std::string& node);
349  bool RemoveAddedNode(const std::string& node);
350  std::vector<AddedNodeInfo> GetAddedNodeInfo();
351 
352  size_t GetNodeCount(NumConnections num);
353  size_t GetMaxOutboundNodeCount();
354  void GetNodeStats(std::vector<CNodeStats>& vstats);
355  bool DisconnectNode(const std::string& node);
356  bool DisconnectNode(NodeId id);
357 
358  unsigned int GetSendBufferSize() const;
359 
361 
362  uint64_t GetTotalBytesRecv();
363  uint64_t GetTotalBytesSent();
364 
365  void SetBestHeight(int height);
366  int GetBestHeight() const;
367 
370 
371  unsigned int GetReceiveFloodSize() const;
372 
373  void SetAsmap(std::vector<bool> asmap) { addrman.m_asmap = std::move(asmap); }
379  void WakeSelect();
380 
381 private:
382  struct ListenSocket {
385 
386  ListenSocket(SOCKET socket_, bool whitelisted_) : socket(socket_), whitelisted(whitelisted_) {}
387  };
388 
389  bool BindListenPort(const CService& bindAddr, std::string& strError, bool fWhitelisted = false);
390  bool Bind(const CService& addr, unsigned int flags);
391  bool InitBinds(const std::vector<CService>& binds, const std::vector<CService>& whiteBinds);
393  void AddOneShot(const std::string& strDest);
394  void ProcessOneShot();
395  void ThreadOpenConnections(const std::vector<std::string> connect);
396  void ThreadMessageHandler();
397  void AcceptConnection(const ListenSocket& hListenSocket);
398  void DisconnectNodes();
400  void InactivityCheck(CNode* pnode);
401  bool GenerateSelectSet(std::set<SOCKET>& recv_set, std::set<SOCKET>& send_set, std::set<SOCKET>& error_set);
402  void SocketEvents(std::set<SOCKET>& recv_set, std::set<SOCKET>& send_set, std::set<SOCKET>& error_set);
403  void SocketHandler();
404  void ThreadSocketHandler();
405  void ThreadDNSAddressSeed();
406 
407  void WakeMessageHandler();
408 
409  uint64_t CalculateKeyedNetGroup(const CAddress& ad);
410 
411  CNode* FindNode(const CNetAddr& ip);
412  CNode* FindNode(const CSubNet& subNet);
413  CNode* FindNode(const std::string& addrName);
414  CNode* FindNode(const CService& addr);
415 
416  bool AttemptToEvictConnection(bool fPreferNewConnection);
417  CNode* ConnectNode(CAddress addrConnect, const char* pszDest, bool fCountFailure, bool manual_connection);
418  bool IsWhitelistedRange(const CNetAddr &addr);
419 
420  void DeleteNode(CNode* pnode);
421 
423 
424  size_t SocketSendData(CNode *pnode);
426  bool BannedSetIsDirty();
428  void SetBannedSetDirty(bool dirty=true);
430  void SweepBanned();
431  void DumpAddresses();
432  void DumpData();
433  void DumpBanlist();
434 
435  // Network stats
436  void RecordBytesRecv(uint64_t bytes);
437  void RecordBytesSent(uint64_t bytes);
438 
439  // Whether the node should be passed out in ForEach* callbacks
440  static bool NodeFullyConnected(const CNode* pnode);
441 
442  // Network usage totals
445  uint64_t nTotalBytesRecv GUARDED_BY(cs_totalBytesRecv) = 0;
446  uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent) = 0;
447 
448  // Whitelisted ranges. Any node connecting from these is automatically
449  // whitelisted (as well as those connecting to whitelisted binds).
450  std::vector<CSubNet> vWhitelistedRange;
451 
452  unsigned int nSendBufferMaxSize{0};
453  unsigned int nReceiveFloodSize{0};
454 
455  std::vector<ListenSocket> vhListenSocket;
456  std::atomic<bool> fNetworkActive{true};
459  bool setBannedIsDirty{false};
462  std::deque<std::string> vOneShots;
464  std::vector<std::string> vAddedNodes GUARDED_BY(cs_vAddedNodes);
466  std::vector<CNode*> vNodes;
467  std::list<CNode*> vNodesDisconnected;
469  std::atomic<NodeId> nLastNodeId;
470  unsigned int nPrevNodeCount;
471 
474 
477 
478  std::unique_ptr<CSemaphore> semOutbound;
479  std::unique_ptr<CSemaphore> semAddnode;
481  int nMaxOutbound{0};
483  int nMaxFeeler{0};
484  std::atomic<int> nBestHeight;
487 
489  const uint64_t nSeed0{0}, nSeed1{0};
490 
492  bool fMsgProcWake{false};
493 
494  std::condition_variable condMsgProc;
495  std::mutex mutexMsgProc;
496  std::atomic<bool> flagInterruptMsgProc;
497 
499 
500 #ifdef USE_WAKEUP_PIPE
502  int wakeupPipe[2]{-1, -1};
503 #endif
504  std::atomic<bool> wakeupSelectNeeded{false};
505 
506  std::thread threadDNSAddressSeed;
507  std::thread threadSocketHandler;
510  std::thread threadMessageHandler;
511 
512  std::unique_ptr<TierTwoConnMan> m_tiertwo_conn_man;
513 };
514 extern std::unique_ptr<CConnman> g_connman;
515 void Discover();
516 uint16_t GetListenPort();
517 bool BindListenPort(const CService& bindAddr, std::string& strError, bool fWhitelisted = false);
519 
520 struct CombinerAll {
521  typedef bool result_type;
522 
523  template <typename I>
524  bool operator()(I first, I last) const
525  {
526  while (first != last) {
527  if (!(*first)) return false;
528  ++first;
529  }
530  return true;
531  }
532 };
533 
534 enum {
535  LOCAL_NONE, // unknown
536  LOCAL_IF, // address a local interface listens on
537  LOCAL_BIND, // address explicit bound to
538  LOCAL_MAPPED, // address reported by UPnP or NAT-PMP
539  LOCAL_MANUAL, // address explicitly specified (-externalip=)
540 
541  LOCAL_MAX
542 };
543 
544 bool IsPeerAddrLocalGood(CNode* pnode);
545 void AdvertiseLocal(CNode* pnode);
546 
551 void SetReachable(enum Network net, bool reachable);
553 bool IsReachable(enum Network net);
555 bool IsReachable(const CNetAddr& addr);
556 
557 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
558 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
559 bool RemoveLocal(const CService& addr);
560 bool SeenLocal(const CService& addr);
561 bool IsLocal(const CService& addr);
562 bool GetLocal(CService& addr, const CNetAddr* paddrPeer = nullptr);
563 CAddress GetLocalAddress(const CNetAddr* paddrPeer, ServiceFlags nLocalServices);
564 
565 bool validateMasternodeIP(const std::string& addrStr); // valid, reachable and routable address
566 
567 
568 extern bool fDiscover;
569 extern bool fListen;
570 
572 
574 extern std::string strSubVersion;
575 
577  int nScore;
578  int nPort;
579 };
580 
582 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
583 typedef std::map<std::string, uint64_t> mapMsgCmdSize; //command, total bytes
584 
586 {
587 public:
590  int64_t nLastSend;
591  int64_t nLastRecv;
592  int64_t nTimeConnected;
593  int64_t nTimeOffset;
594  std::string addrName;
595  int nVersion;
596  std::string cleanSubVer;
597  bool fInbound;
598  bool fAddnode;
600  uint64_t nSendBytes;
602  uint64_t nRecvBytes;
605  double dPingTime;
606  double dPingWait;
607  std::string addrLocal;
608  uint32_t m_mapped_as;
609  // In case this is a MN-only connection.
611  // If 'true' this node will be disconnected after MNAUTH
613  // If 'true', we identified it as an intra-quorum relay connection
615  // In case this is a verified MN, this value is the proTx of the MN
617  // In case this is a verified MN, this value is the hashed operator pubkey of the MN
619 };
620 
621 
623 {
624 private:
625  mutable CHash256 hasher;
627 public:
628  bool in_data; // parsing header (false) or data (true)
629 
630  CDataStream hdrbuf; // partially received header
631  CMessageHeader hdr; // complete header
632  unsigned int nHdrPos;
633 
634  CDataStream vRecv; // received message data
635  unsigned int nDataPos;
636 
637  int64_t nTime; // time (in microseconds) of message receipt.
638 
639  CNetMessage(const CMessageHeader::MessageStartChars& pchMessageStartIn, int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), hdr(pchMessageStartIn), vRecv(nTypeIn, nVersionIn) {
640  hdrbuf.resize(24);
641  in_data = false;
642  nHdrPos = 0;
643  nDataPos = 0;
644  nTime = 0;
645  }
646 
647  bool complete() const
648  {
649  if (!in_data)
650  return false;
651  return (hdr.nMessageSize == nDataPos);
652  }
653 
654  const uint256& GetMessageHash() const;
655 
656  void SetVersion(int nVersionIn)
657  {
658  hdrbuf.SetVersion(nVersionIn);
659  vRecv.SetVersion(nVersionIn);
660  }
661 
662  int readHeader(const char* pch, unsigned int nBytes);
663  int readData(const char* pch, unsigned int nBytes);
664 };
665 
666 
668 class CNode
669 {
670  friend class CConnman;
671 public:
672  // socket
673  std::atomic<ServiceFlags> nServices;
676  size_t nSendSize; // total size of all vSendMsg entries
677  size_t nSendOffset; // offset inside the first vSendMsg already sent
678  uint64_t nSendBytes;
679  std::deque<std::vector<unsigned char>> vSendMsg;
683 
685  std::list<CNetMessage> vProcessMsg;
687 
689 
690  std::deque<CInv> vRecvGetData;
691  uint64_t nRecvBytes;
692  std::atomic<int> nRecvVersion;
693 
694  std::atomic<int64_t> nLastSend;
695  std::atomic<int64_t> nLastRecv;
696  const int64_t nTimeConnected;
697  std::atomic<int64_t> nTimeOffset;
698  const CAddress addr;
699  std::atomic<int> nVersion;
700  // strSubVer is whatever byte array we read from the wire. However, this field is intended
701  // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
702  // store the sanitized version in cleanSubVer. The original should be used when dealing with
703  // the network or wire types and the cleaned string used when displayed or logged.
704  std::string strSubVer, cleanSubVer;
705  RecursiveMutex cs_SubVer; // used for both cleanSubVer and strSubVer
706  bool fWhitelisted; // This peer can bypass DoS banning.
707  bool fFeeler; // If true this node is being used as a short lived feeler.
708  bool fOneShot;
709  bool fAddnode;
710  std::atomic<bool> m_masternode_connection{false}; // If true this node is only used for quorum related messages.
711  std::atomic<bool> m_masternode_probe_connection{false}; // If true this will be disconnected right after the verack.
712  std::atomic<bool> m_masternode_iqr_connection{false}; // If 'true', we identified it as an intra-quorum relay connection.
713  std::atomic<int64_t> m_last_wants_recsigs_recv{0}; // the last time that a recsigs msg was received, used to avoid spam.
714  bool fClient;
715  const bool fInbound;
720  std::atomic_bool m_wants_addrv2{false};
721  std::atomic_bool fSuccessfullyConnected;
722  std::atomic_bool fDisconnect;
723  // We use fRelayTxes for two purposes -
724  // a) it allows us to not relay tx invs before receiving the peer's version message
725  // b) the peer may tell us in their version message that we should not relay tx invs
726  // until they have initialized their bloom filter.
727  bool fRelayTxes; //protected by cs_filter
730  std::unique_ptr<CBloomFilter> pfilter;
731  std::atomic<int> nRefCount;
732 
733  const uint64_t nKeyedNetGroup;
734  std::atomic_bool fPauseRecv;
735  std::atomic_bool fPauseSend;
736 
737  // If true, we will announce/send him plain recovered sigs (usually true for full nodes)
738  std::atomic<bool> m_wants_recsigs{false};
739  // True when the first message after the verack is received
740  std::atomic<bool> fFirstMessageReceived{false};
741  // True only if the first message received after verack is a mnauth
742  std::atomic<bool> fFirstMessageIsMNAUTH{false};
743 protected:
746 
747 public:
749  std::atomic<int> nStartingHeight;
750 
751  // flood relay
752  std::vector<CAddress> vAddrToSend;
754  bool fGetAddr;
755  std::set<uint256> setKnown;
756  std::chrono::microseconds m_next_addr_send GUARDED_BY(cs_sendProcessing){0};
757  std::chrono::microseconds m_next_local_addr_send GUARDED_BY(cs_sendProcessing){0};
760  double m_addr_token_bucket{10.0};
762  std::chrono::microseconds m_addr_token_timestamp{GetTime<std::chrono::microseconds>()};
763 
764  // inventory based relay
766  // Set of transaction ids we still have to announce.
767  // They are sorted by the mempool before relay, so the order is not important.
768  std::set<uint256> setInventoryTxToSend;
769  // List of block ids we still have announce.
770  // There is no final sorting before sending, as they are always sent immediately
771  // and in the order requested.
772  std::vector<uint256> vInventoryBlockToSend;
773  // Set of tier two messages ids we still have to announce.
774  std::vector<CInv> vInventoryTierTwoToSend;
776  std::multimap<int64_t, CInv> mapAskFor;
777  std::set<uint256> setAskFor;
778  std::vector<uint256> vBlockRequested;
779  std::chrono::microseconds nNextInvSend{0};
780  // Used for BIP35 mempool sending, also protected by cs_inventory
782 
783  // Last time a "MEMPOOL" request was serviced.
784  std::atomic<int64_t> timeLastMempoolReq{0};
785 
786  // Ping time measurement:
787  // The pong reply we're expecting, or 0 if no pong expected.
788  std::atomic<uint64_t> nPingNonceSent;
789  // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
790  std::atomic<int64_t> nPingUsecStart;
791  // Last measured round-trip time.
792  std::atomic<int64_t> nPingUsecTime;
793  // Best measured round-trip time.
794  std::atomic<int64_t> nMinPingUsecTime;
795  // Whether a ping is requested.
796  std::atomic<bool> fPingQueued;
797 
798  // Challenge sent in VERSION to be answered with MNAUTH (only happens between MNs)
799  mutable Mutex cs_mnauth;
802  uint256 verifiedProRegTxHash; // MN provider register tx hash
803  uint256 verifiedPubKeyHash; // MN operator pubkey hash
804 
805  CNode(NodeId id, ServiceFlags nLocalServicesIn, int nMyStartingHeightIn, SOCKET hSocketIn, const CAddress& addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const std::string& addrNameIn = "", bool fInboundIn = false);
806  ~CNode();
807  CNode(const CNode&) = delete;
808  CNode& operator=(const CNode&) = delete;
809 
810 private:
811  const NodeId id;
812  const uint64_t nLocalHostNonce;
813  // Services offered to this peer
815  const int nMyStartingHeight;
817  std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
818 
820  std::string addrName;
821 
824 public:
825  NodeId GetId() const
826  {
827  return id;
828  }
829 
830  uint64_t GetLocalNonce() const {
831  return nLocalHostNonce;
832  }
833 
834  int GetMyStartingHeight() const {
835  return nMyStartingHeight;
836  }
837 
839  {
840  assert(nRefCount >= 0);
841  return nRefCount;
842  }
843 
844  unsigned int GetTotalRecvSize()
845  {
846  unsigned int total = 0;
847  for (const CNetMessage& msg : vRecvMsg)
848  total += msg.vRecv.size() + 24;
849  return total;
850  }
851 
852  bool ReceiveMsgBytes(const char* pch, unsigned int nBytes, bool& complete);
853 
854  void SetRecvVersion(int nVersionIn)
855  {
856  nRecvVersion = nVersionIn;
857  }
859  {
860  return nRecvVersion;
861  }
862  void SetSendVersion(int nVersionIn);
863  int GetSendVersion() const;
864 
865  CService GetAddrLocal() const;
867  void SetAddrLocal(const CService& addrLocalIn);
868 
870  {
871  nRefCount++;
872  return this;
873  }
874 
875  void Release()
876  {
877  nRefCount--;
878  }
879 
880 
881  void AddAddressKnown(const CAddress& _addr)
882  {
883  addrKnown.insert(_addr.GetKey());
884  }
885 
886  void PushAddress(const CAddress& _addr, FastRandomContext &insecure_rand)
887  {
888  // Whether the peer supports the address in `_addr`. For example,
889  // nodes that do not implement BIP155 cannot receive Tor v3 addresses
890  // because they require ADDRv2 (BIP155) encoding.
891  const bool addr_format_supported = m_wants_addrv2 || _addr.IsAddrV1Compatible();
892 
893  // Known checking here is only to save space from duplicates.
894  // SendMessages will filter it again for knowns that were added
895  // after addresses were pushed.
896  if (_addr.IsValid() && !addrKnown.contains(_addr.GetKey()) && addr_format_supported) {
897  if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
898  vAddrToSend[insecure_rand.randrange(vAddrToSend.size())] = _addr;
899  } else {
900  vAddrToSend.push_back(_addr);
901  }
902  }
903  }
904 
905 
906  void AddInventoryKnown(const CInv& inv)
907  {
908  {
911  }
912  }
913 
914  void PushInventory(const CInv& inv)
915  {
917  if (inv.type == MSG_TX) {
918  if (!filterInventoryKnown.contains(inv.hash)) {
919  setInventoryTxToSend.insert(inv.hash);
920  }
921  } else if (inv.type == MSG_BLOCK) {
922  vInventoryBlockToSend.push_back(inv.hash);
923  } else {
924  vInventoryTierTwoToSend.emplace_back(inv);
925  }
926  }
927 
928  void AskFor(const CInv& inv, int64_t doubleRequestDelay = 2 * 60 * 1000000);
929  // inv response received, clear it from the waiting inv set.
930  void AskForInvReceived(const uint256& invHash);
931 
932  void CloseSocketDisconnect();
933  bool DisconnectOldProtocol(int nVersionIn, int nVersionRequired);
934 
935  void copyStats(CNodeStats& stats, const std::vector<bool>& m_asmap);
936 
938  {
939  return nLocalServices;
940  }
941 
942  std::string GetAddrName() const;
944  void MaybeSetAddrName(const std::string& addrNameIn);
945 
947 };
948 
950 {
951 public:
952  static void callCleanup();
953 };
954 
959 {
960 public:
961  virtual bool ProcessMessages(CNode* pnode, std::atomic<bool>& interrupt) = 0;
962  virtual bool SendMessages(CNode* pnode, std::atomic<bool>& interrupt) EXCLUSIVE_LOCKS_REQUIRED(pnode->cs_sendProcessing) = 0;
963  virtual void InitializeNode(CNode* pnode) = 0;
964  virtual void FinalizeNode(NodeId id, bool& update_connection_time) = 0;
965 };
966 
968 int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds);
969 
971 inline std::chrono::microseconds PoissonNextSend(std::chrono::microseconds now, std::chrono::seconds average_interval)
972 {
973  return std::chrono::microseconds{PoissonNextSend(now.count(), average_interval.count())};
974 }
975 
976 #endif // PIVX_NET_H
CService ip(uint32_t i)
Definition: DoS_tests.cpp:39
BanReason
Definition: addrdb.h:22
std::map< CSubNet, CBanEntry > banmap_t
Definition: addrdb.h:71
Stochastical (IP) address manager.
Definition: addrman.h:178
std::vector< bool > m_asmap
Definition: addrman.h:317
A CService with information about it as peer.
Definition: protocol.h:338
void SetVersion(int n)
Definition: streams.h:259
void resize(size_type n, value_type c=0)
Definition: streams.h:167
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:139
Signals for UI communication.
Definition: guiinterface.h:32
Definition: net.h:145
std::condition_variable condMsgProc
Definition: net.h:494
void SweepBanned()
clean unused entries (if bantime has expired)
Definition: net.cpp:586
std::thread threadMessageHandler
Definition: net.h:510
void ThreadOpenAddedConnections()
Definition: net.cpp:1910
int GetBestHeight() const
Definition: net.cpp:2631
void ReleaseNodeVector(const std::vector< CNode * > &vecNodes)
Definition: net.cpp:2869
void SocketHandler()
Definition: net.cpp:1438
void ProcessOneShot()
Definition: net.cpp:1684
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:2799
void DeleteNode(CNode *pnode)
Definition: net.cpp:2448
bool setBannedIsDirty
Definition: net.h:459
bool AddNewAddresses(const std::vector< CAddress > &vAddr, const CAddress &addrFrom, int64_t nTimePenalty=0)
Definition: net.cpp:2480
std::unique_ptr< TierTwoConnMan > m_tiertwo_conn_man
Definition: net.h:512
bool GetNetworkActive() const
Definition: net.h:200
std::mutex mutexMsgProc
Definition: net.h:495
void ForEachNodeThen(Callable &&pre, CallableAfter &&post) const
Definition: net.h:288
RecursiveMutex cs_vNodes
Definition: net.h:468
ServiceFlags nLocalServices
Services this instance offers.
Definition: net.h:473
size_t GetNodeCount(NumConnections num)
Definition: net.cpp:2518
void Stop()
Definition: net.cpp:2400
CAddrMan addrman
Definition: net.h:461
std::atomic< bool > flagInterruptMsgProc
Definition: net.h:496
unsigned int GetReceiveFloodSize() const
Definition: net.cpp:2636
std::list< CNode * > vNodesDisconnected
Definition: net.h:467
uint64_t GetTotalBytesRecv()
Definition: net.cpp:2609
void SetBestHeight(int height)
Definition: net.cpp:2626
bool ForEachNodeInRandomOrderContinueIf(Callable &&func)
Definition: net.h:242
void ForEachNodeThen(Callable &&pre, CallableAfter &&post)
Definition: net.h:277
void SocketEvents(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set)
Definition: net.cpp:1362
void AddNewAddress(const CAddress &addr, const CAddress &addrFrom, int64_t nTimePenalty=0)
Definition: net.cpp:2475
NodeId GetNewNodeId()
Definition: net.cpp:2173
std::vector< std::string > vAddedNodes GUARDED_BY(cs_vAddedNodes)
CThreadInterrupt interruptNet
Definition: net.h:498
std::unique_ptr< CSemaphore > semAddnode
Definition: net.h:479
std::atomic< NodeId > nLastNodeId
Definition: net.h:469
void SetServices(const CService &addr, ServiceFlags nServices)
Definition: net.cpp:2465
void RecordBytesSent(uint64_t bytes)
Definition: net.cpp:2603
void Interrupt()
Definition: net.cpp:2375
std::thread threadDNSAddressSeed
Definition: net.h:506
bool Unban(const CNetAddr &ip)
Definition: net.cpp:551
std::vector< CAddress > GetAddresses(size_t max_addresses, size_t max_pct, Optional< Network > network)
Return all or many randomly selected addresses, optionally by network.
Definition: net.cpp:2485
std::deque< std::string > vOneShots
Definition: net.h:462
const uint64_t nSeed1
Definition: net.h:489
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound=nullptr, const char *strDest=nullptr, bool fOneShot=false, bool fFeeler=false, bool fAddnode=false, bool masternode_connection=false, bool masternode_probe_connection=false)
Definition: net.cpp:1937
unsigned int nPrevNodeCount
Definition: net.h:470
void NotifyNumConnectionsChanged()
Definition: net.cpp:1223
void SetBannedSetDirty(bool dirty=true)
set the "dirty" flag for the banlist
Definition: net.cpp:621
ServiceFlags GetLocalServices() const
Definition: net.cpp:2621
bool DisconnectNode(const std::string &node)
Definition: net.cpp:2545
size_t SocketSendData(CNode *pnode)
Definition: net.cpp:857
ServiceFlags nRelevantServices
Services this instance cares about.
Definition: net.h:476
std::vector< CNode * > CopyNodeVector()
Definition: net.cpp:2864
std::vector< ListenSocket > vhListenSocket
Definition: net.h:455
void ThreadOpenConnections(const std::vector< std::string > connect)
Definition: net.cpp:1701
void ClearBanned()
Definition: net.cpp:473
void DumpBanlist()
Definition: net.cpp:433
size_t GetMaxOutboundNodeCount()
Definition: net.cpp:2513
CClientUIInterface * clientInterface
Definition: net.h:485
void GetBanned(banmap_t &banmap)
Definition: net.cpp:571
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:478
void ThreadSocketHandler()
Definition: net.cpp:1553
RecursiveMutex cs_totalBytesSent
Definition: net.h:444
std::thread threadOpenConnections
Definition: net.h:509
void ForEachNode(Callable &&func) const
Definition: net.h:267
NumConnections
Definition: net.h:148
@ CONNECTIONS_IN
Definition: net.h:150
@ CONNECTIONS_NONE
Definition: net.h:149
@ CONNECTIONS_ALL
Definition: net.h:152
@ CONNECTIONS_OUT
Definition: net.h:151
RecursiveMutex cs_vOneShots
Definition: net.h:463
bool fMsgProcWake
flag for waking the message processor.
Definition: net.h:492
CNode * FindNode(const CNetAddr &ip)
Definition: net.cpp:284
void Init(const Options &connOptions)
Definition: net.h:177
constexpr static const CAllNodes AllNodes
Definition: net.h:222
unsigned int GetSendBufferSize() const
Definition: net.cpp:2637
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg, bool allowOptimisticSend=DEFAULT_ALLOW_OPTIMISTIC_SEND)
Definition: net.cpp:2758
void MarkAddressGood(const CAddress &addr)
Definition: net.cpp:2470
void RelayInv(CInv &inv, int minProtoVersion=ActiveProtocol())
Definition: net.cpp:2567
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition: net.h:489
unsigned int nReceiveFloodSize
Definition: net.h:453
std::atomic< bool > wakeupSelectNeeded
Definition: net.h:504
RecursiveMutex cs_totalBytesRecv
Definition: net.h:443
static bool NodeFullyConnected(const CNode *pnode)
Definition: net.cpp:2753
int nMaxConnections
Definition: net.h:480
void WakeMessageHandler()
Definition: net.cpp:1562
void SetNetworkActive(bool active)
Definition: net.cpp:2144
void SetAsmap(std::vector< bool > asmap)
Definition: net.h:373
bool IsBanned(CNetAddr ip)
Definition: net.cpp:485
bool AttemptToEvictConnection(bool fPreferNewConnection)
Try to find a connection to evict when the node is full.
Definition: net.cpp:972
bool Start(CScheduler &scheduler, const Options &options)
Definition: net.cpp:2208
bool GenerateSelectSet(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set)
Definition: net.cpp:1260
bool Bind(const CService &addr, unsigned int flags)
Definition: net.cpp:2178
bool IsNodeConnected(const CAddress &addr)
Definition: net.cpp:2825
void ThreadDNSAddressSeed()
Definition: net.cpp:1601
int wakeupPipe[2]
a pipe which is added to select() calls to wakeup before the timeout
Definition: net.h:502
std::vector< CSubNet > vWhitelistedRange
Definition: net.h:450
void ThreadMessageHandler()
Definition: net.cpp:1987
bool fAddressesInitialized
Definition: net.h:460
uint64_t GetTotalBytesSent()
Definition: net.cpp:2615
void WakeSelect()
Interrupt the select/poll system call.
Definition: net.cpp:1571
~CConnman()
Definition: net.cpp:2459
RecursiveMutex cs_vAddedNodes
Definition: net.h:465
std::thread threadOpenAddedConnections
Definition: net.h:508
CSipHasher GetDeterministicRandomizer(uint64_t id)
Get a unique deterministic randomizer.
Definition: net.cpp:2877
int nMaxOutbound
Definition: net.h:481
void Ban(const CNetAddr &netAddr, const BanReason &reason, int64_t bantimeoffset=0, bool sinceUnixEpoch=false)
Definition: net.cpp:512
bool BannedSetIsDirty()
check is the banlist has unwritten changes
Definition: net.cpp:615
void InactivityCheck(CNode *pnode)
Definition: net.cpp:1237
std::atomic< int > nBestHeight
Definition: net.h:484
bool CheckIncomingNonce(uint64_t nonce)
Definition: net.cpp:334
banmap_t setBanned
Definition: net.h:457
uint64_t nTotalBytesRecv GUARDED_BY(cs_totalBytesRecv)=0
int nMaxAddnode
Definition: net.h:482
bool BindListenPort(const CService &bindAddr, std::string &strError, bool fWhitelisted=false)
Definition: net.cpp:2034
TierTwoConnMan * GetTierTwoConnMan()
Unique tier two connections manager.
Definition: net.h:375
void RecordBytesRecv(uint64_t bytes)
Definition: net.cpp:2597
void DumpData()
Definition: net.cpp:1678
std::vector< AddedNodeInfo > GetAddedNodeInfo()
Definition: net.cpp:1856
void GetNodeStats(std::vector< CNodeStats > &vstats)
Definition: net.cpp:2534
constexpr static const CFullyConnectedOnly FullyConnectedOnly
Definition: net.h:221
bool InitBinds(const std::vector< CService > &binds, const std::vector< CService > &whiteBinds)
Definition: net.cpp:2191
std::vector< CNode * > vNodes
Definition: net.h:466
unsigned int nSendBufferMaxSize
Definition: net.h:452
void RemoveAskFor(const uint256 &invHash, int invType)
Definition: net.cpp:2579
NetEventsInterface * m_msgproc
Definition: net.h:486
void UpdateQuorumRelayMemberIfNeeded(CNode *pnode)
Update the node to be a iqr member if needed.
Definition: net.cpp:2589
void SetBanned(const banmap_t &banmap)
Definition: net.cpp:579
std::atomic< bool > fNetworkActive
Definition: net.h:456
void DisconnectNodes()
Definition: net.cpp:1164
RecursiveMutex cs_setBanned
Definition: net.h:458
void ForEachNode(Callable &&func)
Definition: net.h:257
CConnman(uint64_t seed0, uint64_t seed1)
Definition: net.cpp:2157
bool ForEachNodeContinueIf(Callable &&func)
Definition: net.h:230
void DumpAddresses()
Definition: net.cpp:1667
uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent)=0
bool AddNode(const std::string &node)
Definition: net.cpp:2490
int nMaxFeeler
Definition: net.h:483
std::thread threadSocketHandler
Definition: net.h:507
uint64_t CalculateKeyedNetGroup(const CAddress &ad)
Definition: net.cpp:2882
bool RemoveAddedNode(const std::string &node)
Definition: net.cpp:2501
void AddOneShot(const std::string &strDest)
Definition: net.cpp:98
CNode * ConnectNode(const CAddress &addrConnect)
Definition: net.cpp:2830
bool IsWhitelistedRange(const CNetAddr &addr)
Definition: net.cpp:628
void AcceptConnection(const ListenSocket &hListenSocket)
Definition: net.cpp:1074
static void callCleanup()
Definition: net.cpp:2367
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
Definition: hash.h:38
inv message data
Definition: protocol.h:466
int type
Definition: protocol.h:479
uint256 hash
Definition: protocol.h:480
Message header.
Definition: protocol.h:31
unsigned char MessageStartChars[MESSAGE_START_SIZE]
Definition: protocol.h:40
uint32_t nMessageSize
Definition: protocol.h:56
Network address.
Definition: netaddress.h:120
bool IsValid() const
Definition: netaddress.cpp:418
bool IsAddrV1Compatible() const
Check if the current object can be serialized in pre-ADDRv2/BIP155 format.
Definition: netaddress.cpp:469
CHash256 hasher
Definition: net.h:625
CNetMessage(const CMessageHeader::MessageStartChars &pchMessageStartIn, int nTypeIn, int nVersionIn)
Definition: net.h:639
CDataStream vRecv
Definition: net.h:634
unsigned int nHdrPos
Definition: net.h:632
int readHeader(const char *pch, unsigned int nBytes)
Definition: net.cpp:801
unsigned int nDataPos
Definition: net.h:635
const uint256 & GetMessageHash() const
Definition: net.cpp:848
void SetVersion(int nVersionIn)
Definition: net.h:656
CDataStream hdrbuf
Definition: net.h:630
bool in_data
Definition: net.h:628
uint256 data_hash
Definition: net.h:626
int64_t nTime
Definition: net.h:637
int readData(const char *pch, unsigned int nBytes)
Definition: net.cpp:831
bool complete() const
Definition: net.h:647
CMessageHeader hdr
Definition: net.h:631
Information about a peer.
Definition: net.h:669
RecursiveMutex cs_vProcessMsg
Definition: net.h:684
std::atomic< int64_t > nLastSend
Definition: net.h:694
bool fAddnode
Definition: net.h:709
std::string cleanSubVer
Definition: net.h:704
size_t nSendOffset
Definition: net.h:677
CRollingBloomFilter filterInventoryKnown
Definition: net.h:765
std::atomic< int > nVersion
Definition: net.h:699
void SetSendVersion(int nVersionIn)
Definition: net.cpp:775
std::atomic< bool > m_masternode_connection
Definition: net.h:710
std::vector< uint256 > vInventoryBlockToSend
Definition: net.h:772
std::deque< std::vector< unsigned char > > vSendMsg
Definition: net.h:679
std::atomic_bool fPauseRecv
Definition: net.h:734
NodeId GetId() const
Definition: net.h:825
uint256 hashContinue
Definition: net.h:748
std::atomic< int64_t > nTimeOffset
Definition: net.h:697
CService addrLocal
Definition: net.h:822
RecursiveMutex cs_sendProcessing
Definition: net.h:688
void PushAddress(const CAddress &_addr, FastRandomContext &insecure_rand)
Definition: net.h:886
RecursiveMutex cs_inventory
Definition: net.h:775
std::atomic< bool > fPingQueued
Definition: net.h:796
int GetSendVersion() const
Definition: net.cpp:789
bool fFeeler
Definition: net.h:707
bool fOneShot
Definition: net.h:708
unsigned int GetTotalRecvSize()
Definition: net.h:844
std::list< CNetMessage > vRecvMsg
Definition: net.h:817
mapMsgCmdSize mapRecvBytesPerMsgCmd
Definition: net.h:745
size_t nProcessQueueSize
Definition: net.h:686
std::string addrName
Definition: net.h:820
void SetAddrLocal(const CService &addrLocalIn)
May not be called more than once.
Definition: net.cpp:654
uint64_t nSendBytes
Definition: net.h:678
void AskForInvReceived(const uint256 &invHash)
Definition: net.cpp:2741
std::atomic_bool fSuccessfullyConnected
Definition: net.h:721
ServiceFlags nServicesExpected
Definition: net.h:674
bool DisconnectOldProtocol(int nVersionIn, int nVersionRequired)
Definition: net.cpp:463
uint64_t GetLocalNonce() const
Definition: net.h:830
size_t nSendSize
Definition: net.h:676
std::atomic< ServiceFlags > nServices
Definition: net.h:673
bool fGetAddr
Definition: net.h:754
CRollingBloomFilter addrKnown
Definition: net.h:753
uint256 verifiedProRegTxHash
Definition: net.h:802
RecursiveMutex cs_SubVer
Definition: net.h:705
const CAddress addr
Definition: net.h:698
Mutex cs_mnauth
Definition: net.h:799
RecursiveMutex cs_vSend
Definition: net.h:680
RecursiveMutex cs_addrLocal
Definition: net.h:823
CSemaphoreGrant grantOutbound
Definition: net.h:728
const int64_t nTimeConnected
Definition: net.h:696
std::string GetAddrName() const
Definition: net.cpp:637
uint256 verifiedPubKeyHash
Definition: net.h:803
mapMsgCmdSize mapSendBytesPerMsgCmd
Definition: net.h:744
std::atomic< bool > fFirstMessageIsMNAUTH
Definition: net.h:742
std::atomic< bool > m_wants_recsigs
Definition: net.h:738
RecursiveMutex cs_vRecv
Definition: net.h:682
const uint64_t nKeyedNetGroup
Definition: net.h:733
std::atomic< int > nRefCount
Definition: net.h:731
std::atomic< int64_t > m_last_wants_recsigs_recv
Definition: net.h:713
void AskFor(const CInv &inv, int64_t doubleRequestDelay=2 *60 *1000000)
Definition: net.cpp:2707
RecursiveMutex cs_addrName
Definition: net.h:819
int GetMyStartingHeight() const
Definition: net.h:834
void CloseSocketDisconnect()
Definition: net.cpp:453
uint256 sentMNAuthChallenge
Definition: net.h:800
std::atomic< int > nStartingHeight
Definition: net.h:749
bool fClient
Definition: net.h:714
int GetRefCount()
Definition: net.h:838
std::atomic_bool fPauseSend
Definition: net.h:735
std::atomic< bool > fFirstMessageReceived
Definition: net.h:740
std::multimap< int64_t, CInv > mapAskFor
Definition: net.h:776
std::unique_ptr< CBloomFilter > pfilter
Definition: net.h:730
SOCKET hSocket
Definition: net.h:675
void PushInventory(const CInv &inv)
Definition: net.h:914
const ServiceFlags nLocalServices
Definition: net.h:814
std::chrono::microseconds m_next_addr_send GUARDED_BY(cs_sendProcessing)
Definition: net.h:756
bool ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool &complete)
Definition: net.cpp:724
int GetRecvVersion()
Definition: net.h:858
void copyStats(CNodeStats &stats, const std::vector< bool > &m_asmap)
Definition: net.cpp:665
void MaybeSetAddrName(const std::string &addrNameIn)
Sets the addrName only if it was not previously set.
Definition: net.cpp:642
uint64_t nRecvBytes
Definition: net.h:691
std::atomic< int64_t > timeLastMempoolReq
Definition: net.h:784
void AddAddressKnown(const CAddress &_addr)
Definition: net.h:881
std::atomic< int64_t > nLastRecv
Definition: net.h:695
void SetRecvVersion(int nVersionIn)
Definition: net.h:854
bool CanRelay() const
Definition: net.h:946
std::deque< CInv > vRecvGetData
Definition: net.h:690
uint256 receivedMNAuthChallenge
Definition: net.h:801
std::atomic< int64_t > nMinPingUsecTime
Definition: net.h:794
std::atomic< uint64_t > nPingNonceSent
Definition: net.h:788
RecursiveMutex cs_hSocket
Definition: net.h:681
std::vector< CAddress > vAddrToSend
Definition: net.h:752
std::set< uint256 > setAskFor
Definition: net.h:777
const int nMyStartingHeight
Definition: net.h:815
const uint64_t nLocalHostNonce
Definition: net.h:812
std::atomic< int64_t > nPingUsecStart
Definition: net.h:790
std::chrono::microseconds nNextInvSend
Definition: net.h:779
ServiceFlags GetLocalServices() const
Definition: net.h:937
CNode(NodeId id, ServiceFlags nLocalServicesIn, int nMyStartingHeightIn, SOCKET hSocketIn, const CAddress &addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const std::string &addrNameIn="", bool fInboundIn=false)
Definition: net.cpp:2639
std::set< uint256 > setKnown
Definition: net.h:755
bool fRelayTxes
Definition: net.h:727
CNode(const CNode &)=delete
std::atomic< int64_t > nPingUsecTime
Definition: net.h:792
const NodeId id
Definition: net.h:811
std::vector< uint256 > vBlockRequested
Definition: net.h:778
int nSendVersion
Definition: net.h:816
void AddInventoryKnown(const CInv &inv)
Definition: net.h:906
std::atomic< bool > m_masternode_probe_connection
Definition: net.h:711
bool fSendMempool
Definition: net.h:781
~CNode()
Definition: net.cpp:2702
std::list< CNetMessage > vProcessMsg
Definition: net.h:685
bool fWhitelisted
Definition: net.h:706
RecursiveMutex cs_filter
Definition: net.h:729
std::atomic_bool m_wants_addrv2
Whether the peer has signaled support for receiving ADDRv2 (BIP155) messages, implying a preference t...
Definition: net.h:720
std::chrono::microseconds m_next_local_addr_send GUARDED_BY(cs_sendProcessing)
Definition: net.h:757
std::atomic< bool > m_masternode_iqr_connection
Definition: net.h:712
const bool fInbound
Definition: net.h:715
std::atomic_bool fDisconnect
Definition: net.h:722
double m_addr_token_bucket
Number of addresses that can be processed from this peer.
Definition: net.h:760
CService GetAddrLocal() const
Definition: net.cpp:649
std::vector< CInv > vInventoryTierTwoToSend
Definition: net.h:774
std::set< uint256 > setInventoryTxToSend
Definition: net.h:768
std::atomic< int > nRecvVersion
Definition: net.h:692
void Release()
Definition: net.h:875
CNode & operator=(const CNode &)=delete
std::string strSubVer
Definition: net.h:704
CNode * AddRef()
Definition: net.h:869
std::chrono::microseconds m_addr_token_timestamp
When m_addr_token_bucket was last updated.
Definition: net.h:762
std::string addrLocal
Definition: net.h:607
double dPingWait
Definition: net.h:606
uint64_t nRecvBytes
Definition: net.h:602
bool m_masternode_probe_connection
Definition: net.h:612
mapMsgCmdSize mapSendBytesPerMsgCmd
Definition: net.h:601
std::string addrName
Definition: net.h:594
uint32_t m_mapped_as
Definition: net.h:608
bool fInbound
Definition: net.h:597
bool fWhitelisted
Definition: net.h:604
uint64_t nSendBytes
Definition: net.h:600
int64_t nTimeConnected
Definition: net.h:592
double dPingTime
Definition: net.h:605
bool fAddnode
Definition: net.h:598
int64_t nLastRecv
Definition: net.h:591
bool m_masternode_iqr_connection
Definition: net.h:614
ServiceFlags nServices
Definition: net.h:589
int nStartingHeight
Definition: net.h:599
int64_t nTimeOffset
Definition: net.h:593
bool m_masternode_connection
Definition: net.h:610
uint256 verifiedPubKeyHash
Definition: net.h:618
mapMsgCmdSize mapRecvBytesPerMsgCmd
Definition: net.h:603
int nVersion
Definition: net.h:595
NodeId nodeid
Definition: net.h:588
std::string cleanSubVer
Definition: net.h:596
int64_t nLastSend
Definition: net.h:590
uint256 verifiedProRegTxHash
Definition: net.h:616
RollingBloomFilter is a probabilistic "keep track of most recently inserted" set.
Definition: bloom.h:111
void insert(const std::vector< unsigned char > &vKey)
Definition: bloom.cpp:274
bool contains(const std::vector< unsigned char > &vKey) const
Definition: bloom.cpp:311
RAII-style semaphore lock.
Definition: sync.h:287
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:484
std::vector< unsigned char > GetKey() const
Definition: netaddress.cpp:932
SipHash-2-4.
Definition: siphash.h:14
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:244
Fast randomness source.
Definition: random.h:107
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
Definition: random.h:174
Interface for message handling.
Definition: net.h:959
virtual void InitializeNode(CNode *pnode)=0
virtual bool SendMessages(CNode *pnode, std::atomic< bool > &interrupt) EXCLUSIVE_LOCKS_REQUIRED(pnode -> cs_sendProcessing)=0
virtual bool ProcessMessages(CNode *pnode, std::atomic< bool > &interrupt)=0
virtual void FinalizeNode(NodeId id, bool &update_connection_time)=0
STL-like map container that only keeps the N elements with the highest value.
Definition: limitedmap.h:15
256-bit opaque blob.
Definition: uint256.h:138
NumConnections
Definition: clientmodel.h:41
u_int SOCKET
Definition: compat.h:53
@ LOCK
Definition: lockunlock.h:16
unsigned int nonce
Definition: miner_tests.cpp:28
CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
Definition: net.cpp:158
bool RemoveLocal(const CService &addr)
Definition: net.cpp:237
bool IsPeerAddrLocalGood(CNode *pnode)
Definition: net.cpp:178
std::map< CNetAddr, LocalServiceInfo > mapLocalHost
Definition: net.cpp:92
uint16_t GetListenPort()
Definition: net.cpp:104
void AdvertiseLocal(CNode *pnode)
Definition: net.cpp:186
std::unique_ptr< CConnman > g_connman
Definition: init.cpp:90
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:278
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
Definition: net.cpp:206
bool fDiscover
Definition: net.cpp:89
bool fListen
Definition: net.cpp:90
RecursiveMutex cs_mapLocalHost
Definition: net.cpp:91
int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds)
Return a timestamp in the future (in microseconds) for exponentially distributed events.
Definition: net.cpp:2846
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:94
@ LOCAL_NONE
Definition: net.h:535
@ LOCAL_MAPPED
Definition: net.h:538
@ LOCAL_MANUAL
Definition: net.h:539
@ LOCAL_MAX
Definition: net.h:541
@ LOCAL_BIND
Definition: net.h:537
@ LOCAL_IF
Definition: net.h:536
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:245
bool BindListenPort(const CService &bindAddr, std::string &strError, bool fWhitelisted=false)
int NodeId
Definition: net.h:109
bool validateMasternodeIP(const std::string &addrStr)
Definition: net.cpp:2836
std::map< std::string, uint64_t > mapMsgCmdSize
Definition: net.h:583
bool GetLocal(CService &addr, const CNetAddr *paddrPeer=nullptr)
Definition: net.cpp:110
#define DEFAULT_ALLOW_OPTIMISTIC_SEND
Definition: net.h:49
void CheckOffsetDisconnectedPeers(const CNetAddr &ip)
Definition: net.cpp:908
void Discover()
Definition: net.cpp:2101
limitedmap< CInv, int64_t > mapAlreadyAskedFor
bool IsReachable(enum Network net)
Definition: net.cpp:253
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:265
Network
A network type.
Definition: netaddress.h:44
boost::optional< T > Optional
Substitute for C++17 std::optional.
Definition: optional.h:12
int flags
Definition: pivx-tx.cpp:400
@ MSG_TX
Definition: protocol.h:436
@ MSG_BLOCK
Definition: protocol.h:437
ServiceFlags
nServices flags
Definition: protocol.h:312
@ NODE_NONE
Definition: protocol.h:314
@ NODE_NETWORK
Definition: protocol.h:318
bool fInbound
Definition: net.h:116
CService resolvedAddress
Definition: net.h:114
AddedNodeInfo(const std::string &_strAddedNode, const CService &_resolvedAddress, bool _fConnected, bool _fInbound)
Definition: net.h:118
bool fConnected
Definition: net.h:115
std::string strAddedNode
Definition: net.h:113
bool operator()(const CNode *) const
Definition: net.h:219
bool operator()(const CNode *pnode) const
Definition: net.h:214
ListenSocket(SOCKET socket_, bool whitelisted_)
Definition: net.h:386
std::vector< CSubNet > vWhitelistedRange
Definition: net.h:170
unsigned int nReceiveFloodSize
Definition: net.h:167
CClientUIInterface * uiInterface
Definition: net.h:164
int nMaxOutbound
Definition: net.h:160
int nBestHeight
Definition: net.h:163
int nMaxFeeler
Definition: net.h:162
std::vector< std::string > m_specified_outgoing
Definition: net.h:173
NetEventsInterface * m_msgproc
Definition: net.h:165
int nMaxConnections
Definition: net.h:159
ServiceFlags nLocalServices
Definition: net.h:157
std::vector< bool > m_asmap
Definition: net.h:168
std::vector< std::string > m_added_nodes
Definition: net.h:174
std::vector< CService > vWhiteBinds
Definition: net.h:171
std::vector< CService > vBinds
Definition: net.h:171
ServiceFlags nRelevantServices
Definition: net.h:158
unsigned int nSendBufferMaxSize
Definition: net.h:166
std::vector< std::string > vSeedNodes
Definition: net.h:169
bool m_use_addrman_outgoing
Definition: net.h:172
int nMaxAddnode
Definition: net.h:161
CSerializedNetMsg(const CSerializedNetMsg &msg)=delete
std::string command
Definition: net.h:140
CSerializedNetMsg & operator=(const CSerializedNetMsg &)=delete
CSerializedNetMsg()=default
CSerializedNetMsg(CSerializedNetMsg &&)=default
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
std::vector< unsigned char > data
Definition: net.h:139
bool operator()(I first, I last) const
Definition: net.h:524
bool result_type
Definition: net.h:521
int nScore
Definition: net.h:577
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:50
int ActiveProtocol()
See whether the protocol update is enforced for connected nodes.
CScheduler scheduler