Raven Core  3.0.0
P2P Digital Currency
net.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Copyright (c) 2017-2019 The Raven Core developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #ifndef RAVEN_NET_H
8 #define RAVEN_NET_H
9 
10 #include "addrdb.h"
11 #include "addrman.h"
12 #include "amount.h"
13 #include "bloom.h"
14 #include "compat.h"
15 #include "hash.h"
16 #include "limitedmap.h"
17 #include "netaddress.h"
18 #include "policy/feerate.h"
19 #include "protocol.h"
20 #include "random.h"
21 #include "streams.h"
22 #include "sync.h"
23 #include "uint256.h"
24 #include "threadinterrupt.h"
25 
26 #include <atomic>
27 #include <deque>
28 #include <stdint.h>
29 #include <thread>
30 #include <memory>
31 #include <condition_variable>
32 
33 #ifndef WIN32
34 #include <arpa/inet.h>
35 #endif
36 
37 
38 class CScheduler;
39 class CNode;
40 
41 namespace boost {
42  class thread_group;
43 } // namespace boost
44 
46 static const int PING_INTERVAL = 2 * 60;
48 static const int TIMEOUT_INTERVAL = 20 * 60;
50 static const int FEELER_INTERVAL = 120;
52 static const unsigned int MAX_INV_SZ = 50000;
54 static const unsigned int MAX_ASSET_INV_SZ = 1024;
56 static const unsigned int MAX_ADDR_TO_SEND = 1000;
58 static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
60 static const unsigned int MAX_SUBVERSION_LENGTH = 256;
62 static const int MAX_OUTBOUND_CONNECTIONS = 8;
64 static const int MAX_ADDNODE_CONNECTIONS = 8;
66 static const bool DEFAULT_LISTEN = true;
68 #ifdef USE_UPNP
69 static const bool DEFAULT_UPNP = USE_UPNP;
70 #else
71 static const bool DEFAULT_UPNP = false;
72 #endif
73 
74 static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ;
76 static const size_t SETASKFOR_MAX_SZ = 2 * MAX_INV_SZ;
78 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
80 static const uint64_t DEFAULT_MAX_UPLOAD_TARGET = 0;
82 static const uint64_t MAX_UPLOAD_TIMEFRAME = 60 * 60 * 24;
84 static const bool DEFAULT_BLOCKSONLY = false;
85 
86 static const bool DEFAULT_FORCEDNSSEED = true;
87 static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
88 static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
89 
90 // NOTE: When adjusting this, update rpcnet:setban's help ("24h")
91 static const unsigned int DEFAULT_MISBEHAVING_BANTIME = 60 * 60 * 24; // Default 24-hour ban
92 
93 typedef int64_t NodeId;
94 
96 {
97  std::string strAddedNode;
99  bool fConnected;
100  bool fInbound;
101 };
102 
103 class CNodeStats;
104 class CClientUIInterface;
105 
107 {
108  CSerializedNetMsg() = default;
110  CSerializedNetMsg& operator=(CSerializedNetMsg&&) = default;
111  // No copying, only moves.
112  CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
113  CSerializedNetMsg& operator=(const CSerializedNetMsg&) = delete;
114 
115  std::vector<unsigned char> data;
116  std::string command;
117 };
118 
119 class NetEventsInterface;
120 class CConnman
121 {
122 public:
123 
126  CONNECTIONS_IN = (1U << 0),
127  CONNECTIONS_OUT = (1U << 1),
129  };
130 
131  struct Options
132  {
133  ServiceFlags nLocalServices = NODE_NONE;
134  int nMaxConnections = 0;
135  int nMaxOutbound = 0;
136  int nMaxAddnode = 0;
137  int nMaxFeeler = 0;
138  int nBestHeight = 0;
140  NetEventsInterface* m_msgproc = nullptr;
141  unsigned int nSendBufferMaxSize = 0;
142  unsigned int nReceiveFloodSize = 0;
143  uint64_t nMaxOutboundTimeframe = 0;
144  uint64_t nMaxOutboundLimit = 0;
145  std::vector<std::string> vSeedNodes;
146  std::vector<CSubNet> vWhitelistedRange;
147  std::vector<CService> vBinds, vWhiteBinds;
148  bool m_use_addrman_outgoing = true;
149  std::vector<std::string> m_specified_outgoing;
150  std::vector<std::string> m_added_nodes;
151  };
152 
153  void Init(const Options& connOptions) {
154  nLocalServices = connOptions.nLocalServices;
155  nMaxConnections = connOptions.nMaxConnections;
156  nMaxOutbound = std::min(connOptions.nMaxOutbound, connOptions.nMaxConnections);
157  nMaxAddnode = connOptions.nMaxAddnode;
158  nMaxFeeler = connOptions.nMaxFeeler;
159  nBestHeight = connOptions.nBestHeight;
160  clientInterface = connOptions.uiInterface;
161  m_msgproc = connOptions.m_msgproc;
162  nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
163  nReceiveFloodSize = connOptions.nReceiveFloodSize;
164  nMaxOutboundTimeframe = connOptions.nMaxOutboundTimeframe;
165  nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
166  vWhitelistedRange = connOptions.vWhitelistedRange;
167  vAddedNodes = connOptions.m_added_nodes;
168  }
169 
170  CConnman(uint64_t seed0, uint64_t seed1);
171  ~CConnman();
172  bool Start(CScheduler& scheduler, const Options& options);
173  void Stop();
174  void Interrupt();
175  bool GetNetworkActive() const { return fNetworkActive; };
176  void SetNetworkActive(bool active);
177  bool OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound = nullptr, const char *strDest = nullptr, bool fOneShot = false, bool fFeeler = false, bool manual_connection = false);
178  bool CheckIncomingNonce(uint64_t nonce);
179 
180  bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
181 
182  void PushMessage(CNode* pnode, CSerializedNetMsg&& msg);
183 
184  template<typename Callable>
185  void ForEachNode(Callable&& func)
186  {
187  LOCK(cs_vNodes);
188  for (auto&& node : vNodes) {
189  if (NodeFullyConnected(node))
190  func(node);
191  }
192  };
193 
194  template<typename Callable>
195  void ForEachNode(Callable&& func) const
196  {
197  LOCK(cs_vNodes);
198  for (auto&& node : vNodes) {
199  if (NodeFullyConnected(node))
200  func(node);
201  }
202  };
203 
204  template<typename Callable, typename CallableAfter>
205  void ForEachNodeThen(Callable&& pre, CallableAfter&& post)
206  {
207  LOCK(cs_vNodes);
208  for (auto&& node : vNodes) {
209  if (NodeFullyConnected(node))
210  pre(node);
211  }
212  post();
213  };
214 
215  template<typename Callable, typename CallableAfter>
216  void ForEachNodeThen(Callable&& pre, CallableAfter&& post) const
217  {
218  LOCK(cs_vNodes);
219  for (auto&& node : vNodes) {
220  if (NodeFullyConnected(node))
221  pre(node);
222  }
223  post();
224  };
225 
226  // Addrman functions
227  size_t GetAddressCount() const;
228  void SetServices(const CService &addr, ServiceFlags nServices);
229  void MarkAddressGood(const CAddress& addr);
230  void AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
231  std::vector<CAddress> GetAddresses();
232 
233  // Denial-of-service detection/prevention
234  // The idea is to detect peers that are behaving
235  // badly and disconnect/ban them, but do it in a
236  // one-coding-mistake-won't-shatter-the-entire-network
237  // way.
238  // IMPORTANT: There should be nothing I can give a
239  // node that it will forward on that will make that
240  // node's peers drop it. If there is, an attacker
241  // can isolate a node and/or try to split the network.
242  // Dropping a node for sending stuff that is invalid
243  // now but might be valid in a later version is also
244  // dangerous, because it can cause a network split
245  // between nodes running old code and nodes running
246  // new code.
247  void Ban(const CNetAddr& netAddr, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
248  void Ban(const CSubNet& subNet, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
249  void ClearBanned(); // needed for unit testing
250  bool IsBanned(CNetAddr ip);
251  bool IsBanned(CSubNet subnet);
252  bool Unban(const CNetAddr &ip);
253  bool Unban(const CSubNet &ip);
254  void GetBanned(banmap_t &banmap);
255  void SetBanned(const banmap_t &banmap);
256 
257  // This allows temporarily exceeding nMaxOutbound, with the goal of finding
258  // a peer that is better than all our current peers.
259  void SetTryNewOutboundPeer(bool flag);
260  bool GetTryNewOutboundPeer();
261 
262  // Return the number of outbound peers we have in excess of our target (eg,
263  // if we previously called SetTryNewOutboundPeer(true), and have since set
264  // to false, we may have extra peers that we wish to disconnect). This may
265  // return a value less than (num_outbound_connections - num_outbound_slots)
266  // in cases where some outbound connections are not yet fully connected, or
267  // not yet fully disconnected.
268  int GetExtraOutboundCount();
269 
270  bool AddNode(const std::string& node);
271  bool RemoveAddedNode(const std::string& node);
272  std::vector<AddedNodeInfo> GetAddedNodeInfo();
273 
274  size_t GetNodeCount(NumConnections num);
275  void GetNodeStats(std::vector<CNodeStats>& vstats);
276  bool DisconnectNode(const std::string& node);
277  bool DisconnectNode(NodeId id);
278 
279  ServiceFlags GetLocalServices() const;
280 
282  void SetMaxOutboundTarget(uint64_t limit);
283  uint64_t GetMaxOutboundTarget();
284 
286  void SetMaxOutboundTimeframe(uint64_t timeframe);
287  uint64_t GetMaxOutboundTimeframe();
288 
290  // if param historicalBlockServingLimit is set true, the function will
291  // response true if the limit for serving historical blocks has been reached
292  bool OutboundTargetReached(bool historicalBlockServingLimit);
293 
295  // in case of no limit, it will always response 0
296  uint64_t GetOutboundTargetBytesLeft();
297 
299  // in case of no limit, it will always response 0
300  uint64_t GetMaxOutboundTimeLeftInCycle();
301 
302  uint64_t GetTotalBytesRecv();
303  uint64_t GetTotalBytesSent();
304 
305  void SetBestHeight(int height);
306  int GetBestHeight() const;
307 
309  CSipHasher GetDeterministicRandomizer(uint64_t id) const;
310 
311  unsigned int GetReceiveFloodSize() const;
312 
313  void WakeMessageHandler();
314 private:
315  struct ListenSocket {
318 
319  ListenSocket(SOCKET socket_, bool whitelisted_) : socket(socket_), whitelisted(whitelisted_) {}
320  };
321 
322  bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
323  bool Bind(const CService &addr, unsigned int flags);
324  bool InitBinds(const std::vector<CService>& binds, const std::vector<CService>& whiteBinds);
325  void ThreadOpenAddedConnections();
326  void AddOneShot(const std::string& strDest);
327  void ProcessOneShot();
328  void ThreadOpenConnections();
329  void ThreadMessageHandler();
330  void AcceptConnection(const ListenSocket& hListenSocket);
331  void ThreadSocketHandler();
332  void ThreadDNSAddressSeed();
333 
334  uint64_t CalculateKeyedNetGroup(const CAddress& ad) const;
335 
336  CNode* FindNode(const CNetAddr& ip);
337  CNode* FindNode(const CSubNet& subNet);
338  CNode* FindNode(const std::string& addrName);
339  CNode* FindNode(const CService& addr);
340 
341  bool AttemptToEvictConnection();
342  CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure);
343  bool IsWhitelistedRange(const CNetAddr &addr);
344 
345  void DeleteNode(CNode* pnode);
346 
347  NodeId GetNewNodeId();
348 
349  size_t SocketSendData(CNode *pnode) const;
351  bool BannedSetIsDirty();
353  void SetBannedSetDirty(bool dirty=true);
355  void SweepBanned();
356  void DumpAddresses();
357  void DumpData();
358  void DumpBanlist();
359 
360  // Network stats
361  void RecordBytesRecv(uint64_t bytes);
362  void RecordBytesSent(uint64_t bytes);
363 
364  // Whether the node should be passed out in ForEach* callbacks
365  static bool NodeFullyConnected(const CNode* pnode);
366 
367  // Network usage totals
370  uint64_t nTotalBytesRecv;
371  uint64_t nTotalBytesSent;
372 
373  // outbound limit & stats
378 
379  // Whitelisted ranges. Any node connecting from these is automatically
380  // whitelisted (as well as those connecting to whitelisted binds).
381  std::vector<CSubNet> vWhitelistedRange;
382 
383  unsigned int nSendBufferMaxSize;
384  unsigned int nReceiveFloodSize;
385 
386  std::vector<ListenSocket> vhListenSocket;
387  std::atomic<bool> fNetworkActive;
393  std::deque<std::string> vOneShots;
395  std::vector<std::string> vAddedNodes;
397  std::vector<CNode*> vNodes;
398  std::list<CNode*> vNodesDisconnected;
400  std::atomic<NodeId> nLastNodeId;
401 
404 
411  std::atomic<int> nBestHeight;
414 
416  const uint64_t nSeed0, nSeed1;
417 
420 
421  std::condition_variable condMsgProc;
422  std::mutex mutexMsgProc;
423  std::atomic<bool> flagInterruptMsgProc;
424 
426 
427  std::thread threadDNSAddressSeed;
428  std::thread threadSocketHandler;
431  std::thread threadMessageHandler;
432 
436  std::atomic_bool m_try_another_outbound_peer;
437 };
438 extern std::unique_ptr<CConnman> g_connman;
439 void Discover(boost::thread_group& threadGroup);
440 void MapPort(bool fUseUPnP);
441 unsigned short GetListenPort();
442 bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
443 
445 {
446  typedef bool result_type;
447 
448  template<typename I>
449  bool operator()(I first, I last) const
450  {
451  while (first != last) {
452  if (!(*first)) return false;
453  ++first;
454  }
455  return true;
456  }
457 };
458 
463 {
464 public:
465  virtual bool ProcessMessages(CNode* pnode, std::atomic<bool>& interrupt) = 0;
466  virtual bool SendMessages(CNode* pnode, std::atomic<bool>& interrupt) = 0;
467  virtual void InitializeNode(CNode* pnode) = 0;
468  virtual void FinalizeNode(NodeId id, bool& update_connection_time) = 0;
469 };
470 
471 enum
472 {
473  LOCAL_NONE, // unknown
474  LOCAL_IF, // address a local interface listens on
475  LOCAL_BIND, // address explicit bound to
476  LOCAL_UPNP, // address reported by UPnP
477  LOCAL_MANUAL, // address explicitly specified (-externalip=)
478 
480 };
481 
482 bool IsPeerAddrLocalGood(CNode *pnode);
483 void AdvertiseLocal(CNode *pnode);
484 void SetLimited(enum Network net, bool fLimited = true);
485 bool IsLimited(enum Network net);
486 bool IsLimited(const CNetAddr& addr);
487 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
488 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
489 bool RemoveLocal(const CService& addr);
490 bool SeenLocal(const CService& addr);
491 bool IsLocal(const CService& addr);
492 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr);
493 bool IsReachable(enum Network net);
494 bool IsReachable(const CNetAddr &addr);
495 CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices);
496 
497 
498 extern bool fDiscover;
499 extern bool fListen;
500 extern bool fRelayTxes;
501 
503 
505 extern std::string strSubVersion;
506 
508  int nScore;
509  int nPort;
510 };
511 
513 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
514 typedef std::map<std::string, uint64_t> mapMsgCmdSize; //command, total bytes
515 
517 {
518 public:
522  int64_t nLastSend;
523  int64_t nLastRecv;
524  int64_t nTimeConnected;
525  int64_t nTimeOffset;
526  std::string addrName;
527  int nVersion;
528  std::string cleanSubVer;
529  bool fInbound;
532  uint64_t nSendBytes;
533  mapMsgCmdSize mapSendBytesPerMsgCmd;
534  uint64_t nRecvBytes;
535  mapMsgCmdSize mapRecvBytesPerMsgCmd;
537  double dPingTime;
538  double dPingWait;
539  double dMinPing;
540  // Our address, as reported by the peer
541  std::string addrLocal;
542  // Address of this peer
544  // Bind address of our side of the connection
546 };
547 
548 
549 
550 
551 class CNetMessage {
552 private:
553  mutable CHash256 hasher;
555 public:
556  bool in_data; // parsing header (false) or data (true)
557 
558  CDataStream hdrbuf; // partially received header
559  CMessageHeader hdr; // complete header
560  unsigned int nHdrPos;
561 
562  CDataStream vRecv; // received message data
563  unsigned int nDataPos;
564 
565  int64_t nTime; // time (in microseconds) of message receipt.
566 
567  CNetMessage(const CMessageHeader::MessageStartChars& pchMessageStartIn, int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), hdr(pchMessageStartIn), vRecv(nTypeIn, nVersionIn) {
568  hdrbuf.resize(24);
569  in_data = false;
570  nHdrPos = 0;
571  nDataPos = 0;
572  nTime = 0;
573  }
574 
575  bool complete() const
576  {
577  if (!in_data)
578  return false;
579  return (hdr.nMessageSize == nDataPos);
580  }
581 
582  const uint256& GetMessageHash() const;
583 
584  void SetVersion(int nVersionIn)
585  {
586  hdrbuf.SetVersion(nVersionIn);
587  vRecv.SetVersion(nVersionIn);
588  }
589 
590  int readHeader(const char *pch, unsigned int nBytes);
591  int readData(const char *pch, unsigned int nBytes);
592 };
593 
594 
596 class CNode
597 {
598  friend class CConnman;
599 public:
600  // socket
601  std::atomic<ServiceFlags> nServices;
603  size_t nSendSize; // total size of all vSendMsg entries
604  size_t nSendOffset; // offset inside the first vSendMsg already sent
605  uint64_t nSendBytes;
606  std::deque<std::vector<unsigned char>> vSendMsg;
610 
612  std::list<CNetMessage> vProcessMsg;
614 
616 
617  std::deque<CInv> vRecvGetData;
618  std::deque<CInvAsset> vRecvAssetGetData;
619  uint64_t nRecvBytes;
620  std::atomic<int> nRecvVersion;
621 
622  std::atomic<int64_t> nLastSend;
623  std::atomic<int64_t> nLastRecv;
624  const int64_t nTimeConnected;
625  std::atomic<int64_t> nTimeOffset;
626  // Address of this peer
627  const CAddress addr;
628  // Bind address of our side of the connection
630  std::atomic<int> nVersion;
631  // strSubVer is whatever byte array we read from the wire. However, this field is intended
632  // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
633  // store the sanitized version in cleanSubVer. The original should be used when dealing with
634  // the network or wire types and the cleaned string used when displayed or logged.
635  std::string strSubVer, cleanSubVer;
636  CCriticalSection cs_SubVer; // used for both cleanSubVer and strSubVer
637  bool fWhitelisted; // This peer can bypass DoS banning.
638  bool fFeeler; // If true this node is being used as a short lived feeler.
639  bool fOneShot;
641  bool fClient;
642  const bool fInbound;
643  std::atomic_bool fSuccessfullyConnected;
644  std::atomic_bool fDisconnect;
645  // We use fRelayTxes for two purposes -
646  // a) it allows us to not relay tx invs before receiving the peer's version message
647  // b) the peer may tell us in its version message that we should not relay tx invs
648  // unless it loads a bloom filter.
649  bool fRelayTxes; //protected by cs_filter
650  bool fSentAddr;
654  std::atomic<int> nRefCount;
655 
656  const uint64_t nKeyedNetGroup;
657  std::atomic_bool fPauseRecv;
658  std::atomic_bool fPauseSend;
659 protected:
660 
661  mapMsgCmdSize mapSendBytesPerMsgCmd;
662  mapMsgCmdSize mapRecvBytesPerMsgCmd;
663 
664 public:
666  std::atomic<int> nStartingHeight;
667 
668  // flood relay
669  std::vector<CAddress> vAddrToSend;
671  bool fGetAddr;
672  std::set<uint256> setKnown;
673  int64_t nNextAddrSend;
675 
677  std::set<std::string> setInventoryAssetsSend;
678 
679  // inventory based relay
681  // Set of transaction ids we still have to announce.
682  // They are sorted by the mempool before relay, so the order is not important.
683  std::set<uint256> setInventoryTxToSend;
684  // List of block ids we still have announce.
685  // There is no final sorting before sending, as they are always sent immediately
686  // and in the order requested.
687  std::vector<uint256> vInventoryBlockToSend;
689  std::set<uint256> setAskFor;
690  std::multimap<int64_t, CInv> mapAskFor;
691  int64_t nNextInvSend;
692  // Used for headers announcements - unfiltered blocks to relay
693  // Also protected by cs_inventory
694  std::vector<uint256> vBlockHashesToAnnounce;
695  // Used for BIP35 mempool sending, also protected by cs_inventory
697 
698  // Last time a "MEMPOOL" request was serviced.
699  std::atomic<int64_t> timeLastMempoolReq;
700 
701  // Block and TXN accept times
702  std::atomic<int64_t> nLastBlockTime;
703  std::atomic<int64_t> nLastTXTime;
704 
705  // Ping time measurement:
706  // The pong reply we're expecting, or 0 if no pong expected.
707  std::atomic<uint64_t> nPingNonceSent;
708  // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
709  std::atomic<int64_t> nPingUsecStart;
710  // Last measured round-trip time.
711  std::atomic<int64_t> nPingUsecTime;
712  // Best measured round-trip time.
713  std::atomic<int64_t> nMinPingUsecTime;
714  // Whether a ping is requested.
715  std::atomic<bool> fPingQueued;
716  // Minimum fee rate with which to filter inv's to this node
721 
722  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);
723  ~CNode();
724  CNode(const CNode&) = delete;
725  CNode& operator=(const CNode&) = delete;
726 
727 private:
728  const NodeId id;
729  const uint64_t nLocalHostNonce;
730  // Services offered to this peer
732  const int nMyStartingHeight;
734  std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
735 
737  std::string addrName;
738 
739  // Our address, as reported by the peer
742 public:
743 
744  NodeId GetId() const {
745  return id;
746  }
747 
748  uint64_t GetLocalNonce() const {
749  return nLocalHostNonce;
750  }
751 
752  int GetMyStartingHeight() const {
753  return nMyStartingHeight;
754  }
755 
756  int GetRefCount() const
757  {
758  assert(nRefCount >= 0);
759  return nRefCount;
760  }
761 
762  bool ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool& complete);
763 
764  void SetRecvVersion(int nVersionIn)
765  {
766  nRecvVersion = nVersionIn;
767  }
768  int GetRecvVersion() const
769  {
770  return nRecvVersion;
771  }
772  void SetSendVersion(int nVersionIn);
773  int GetSendVersion() const;
774 
775  CService GetAddrLocal() const;
777  void SetAddrLocal(const CService& addrLocalIn);
778 
780  {
781  nRefCount++;
782  return this;
783  }
784 
785  void Release()
786  {
787  nRefCount--;
788  }
789 
790 
791 
792  void AddAddressKnown(const CAddress& _addr)
793  {
794  addrKnown.insert(_addr.GetKey());
795  }
796 
797  void PushAddress(const CAddress& _addr, FastRandomContext &insecure_rand)
798  {
799  // Known checking here is only to save space from duplicates.
800  // SendMessages will filter it again for knowns that were added
801  // after addresses were pushed.
802  if (_addr.IsValid() && !addrKnown.contains(_addr.GetKey())) {
803  if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
804  vAddrToSend[insecure_rand.randrange(vAddrToSend.size())] = _addr;
805  } else {
806  vAddrToSend.push_back(_addr);
807  }
808  }
809  }
810 
811 
812  void AddInventoryKnown(const CInv& inv)
813  {
814  {
815  LOCK(cs_inventory);
816  filterInventoryKnown.insert(inv.hash);
817  }
818  }
819 
820  void PushInventory(const CInv& inv)
821  {
822  LOCK(cs_inventory);
823  if (inv.type == MSG_TX) {
824  if (!filterInventoryKnown.contains(inv.hash)) {
825  setInventoryTxToSend.insert(inv.hash);
826  }
827  } else if (inv.type == MSG_BLOCK) {
828  vInventoryBlockToSend.push_back(inv.hash);
829  }
830  }
831 
832  void PushAssetInventory(const std::string& name)
833  {
834  LOCK(cs_inventory);
835  setInventoryAssetsSend.insert(name);
836  }
837 
838  void PushBlockHash(const uint256 &hash)
839  {
840  LOCK(cs_inventory);
841  vBlockHashesToAnnounce.push_back(hash);
842  }
843 
844  void AskFor(const CInv& inv);
845 
846  void CloseSocketDisconnect();
847 
848  void copyStats(CNodeStats &stats);
849 
851  {
852  return nLocalServices;
853  }
854 
855  std::string GetAddrName() const;
857  void MaybeSetAddrName(const std::string& addrNameIn);
858 };
859 
861 {
862 public:
863  static void callCleanup();
864 };
865 
866 
867 
868 
870 int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds);
871 
872 #endif // RAVEN_NET_H
std::atomic< bool > flagInterruptMsgProc
Definition: net.h:423
std::unique_ptr< CConnman > g_connman
Definition: init.cpp:81
int nMaxFeeler
Definition: net.h:410
std::vector< CSubNet > vWhitelistedRange
Definition: net.h:146
std::atomic< uint64_t > nPingNonceSent
Definition: net.h:707
uint256 data_hash
Definition: net.h:554
bool IsReachable(enum Network net)
check whether a given network is one we can probably connect to
Definition: net.cpp:290
CCriticalSection cs_addrName
Definition: net.h:736
int nStartingHeight
Definition: net.h:531
std::atomic_bool fPauseSend
Definition: net.h:658
int64_t nextSendTimeFeeFilter
Definition: net.h:720
mapMsgCmdSize mapRecvBytesPerMsgCmd
Definition: net.h:535
std::atomic< bool > fNetworkActive
Definition: net.h:387
bool fMsgProcWake
flag for waking the message processor.
Definition: net.h:419
ServiceFlags
nServices flags
Definition: protocol.h:271
CCriticalSection cs_filter
Definition: net.h:652
BanReason
Definition: addrdb.h:20
int64_t nTimeOffset
Definition: net.h:525
uint64_t nMaxOutboundTimeframe
Definition: net.h:377
std::string addrName
Definition: net.h:737
bool fListen
Definition: net.cpp:88
STL-like map container that only keeps the N elements with the highest value.
Definition: limitedmap.h:14
Definition: init.h:16
std::atomic< int > nBestHeight
Definition: net.h:411
int flags
Definition: raven-tx.cpp:500
CSemaphore * semAddnode
Definition: net.h:406
std::list< CNetMessage > vProcessMsg
Definition: net.h:612
const uint64_t nKeyedNetGroup
Definition: net.h:656
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:270
int GetRecvVersion() const
Definition: net.h:768
mapMsgCmdSize mapSendBytesPerMsgCmd
Definition: net.h:661
void insert(const std::vector< unsigned char > &vKey)
Definition: bloom.cpp:249
std::vector< unsigned char > data
Definition: net.h:115
inv message data
Definition: protocol.h:397
bool fRelayTxes
Definition: net.cpp:89
unsigned int nReceiveFloodSize
Definition: net.h:142
mapMsgCmdSize mapSendBytesPerMsgCmd
Definition: net.h:533
CClientUIInterface * uiInterface
Definition: net.h:139
void resize(size_type n, value_type c=0)
Definition: streams.h:240
std::vector< uint256 > vInventoryBlockToSend
Definition: net.h:687
CCriticalSection cs_hSocket
Definition: net.h:608
BloomFilter is a probabilistic filter which SPV clients provide so that we can filter the transaction...
Definition: bloom.h:45
uint64_t randrange(uint64_t range)
Generate a random integer in the range [0..range).
Definition: random.h:104
ServiceFlags nServices
Definition: net.h:520
bool fSendMempool
Definition: net.h:696
CCriticalSection cs_SubVer
Definition: net.h:636
std::mutex mutexMsgProc
Definition: net.h:422
CCriticalSection cs_addrLocal
Definition: net.h:741
unsigned int nHdrPos
Definition: net.h:560
int nMaxAddnode
Definition: net.h:409
RAII-style semaphore lock.
Definition: sync.h:231
std::string cleanSubVer
Definition: net.h:528
Interface for message handling.
Definition: net.h:462
void SetVersion(int nVersionIn)
Definition: net.h:584
uint64_t nMaxOutboundLimit
Definition: net.h:376
RollingBloomFilter is a probabilistic "keep track of most recently inserted" set. ...
Definition: bloom.h:120
NetEventsInterface * m_msgproc
Definition: net.h:413
std::atomic< int64_t > nPingUsecStart
Definition: net.h:709
CCriticalSection cs_vNodes
Definition: net.h:399
int nMaxConnections
Definition: net.h:134
int64_t nTimeConnected
Definition: net.h:524
CCriticalSection cs_feeFilter
Definition: net.h:718
void AdvertiseLocal(CNode *pnode)
Definition: net.cpp:187
void MapPort(bool fUseUPnP)
Definition: net.cpp:1572
uint64_t nTotalBytesSent
Definition: net.h:371
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:147
CCriticalSection cs_vAddedNodes
Definition: net.h:396
uint32_t nMessageSize
Definition: protocol.h:62
A hasher class for Raven&#39;s 256-bit hash (double SHA-256).
Definition: hash.h:76
ListenSocket(SOCKET socket_, bool whitelisted_)
Definition: net.h:319
CCriticalSection cs_inventory
Definition: net.h:688
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:2924
uint64_t GetLocalNonce() const
Definition: net.h:748
std::map< CNetAddr, LocalServiceInfo > mapLocalHost
Definition: net.cpp:91
CDataStream hdrbuf
Definition: net.h:558
std::set< uint256 > setInventoryTxToSend
Definition: net.h:683
std::vector< CAddress > vAddrToSend
Definition: net.h:669
std::vector< CService > vWhiteBinds
Definition: net.h:147
std::atomic< int > nStartingHeight
Definition: net.h:666
void PushAddress(const CAddress &_addr, FastRandomContext &insecure_rand)
Definition: net.h:797
void PushAssetInventory(const std::string &name)
Definition: net.h:832
void SetRecvVersion(int nVersionIn)
Definition: net.h:764
bool in_data
Definition: net.h:556
std::atomic< int64_t > timeLastMempoolReq
Definition: net.h:699
CAmount minFeeFilter
Definition: net.h:717
Signals for UI communication.
Definition: ui_interface.h:28
std::list< CNetMessage > vRecvMsg
Definition: net.h:734
CNetMessage(const CMessageHeader::MessageStartChars &pchMessageStartIn, int nTypeIn, int nVersionIn)
Definition: net.h:567
void PushInventory(const CInv &inv)
Definition: net.h:820
CAddrMan addrman
Definition: net.h:392
std::atomic< ServiceFlags > nServices
Definition: net.h:601
int nSendVersion
Definition: net.h:733
int64_t nNextLocalAddrSend
Definition: net.h:674
std::deque< CInv > vRecvGetData
Definition: net.h:617
bool fConnected
Definition: net.h:99
int GetRefCount() const
Definition: net.h:756
ServiceFlags nLocalServices
Services this instance offers.
Definition: net.h:403
CDataStream vRecv
Definition: net.h:562
bool contains(const std::vector< unsigned char > &vKey) const
Definition: bloom.cpp:285
bool IsValid() const
Definition: netaddress.cpp:198
std::set< uint256 > setKnown
Definition: net.h:672
bool operator()(I first, I last) const
Definition: net.h:449
bool m_manual_connection
Definition: net.h:530
Stochastical (IP) address manager.
Definition: addrman.h:183
int64_t CAmount
Amount in corbies (Can be negative)
Definition: amount.h:13
std::atomic< int64_t > nLastSend
Definition: net.h:622
bool fSentAddr
Definition: net.h:650
CHash256 hasher
Definition: net.h:553
std::atomic< int64_t > nPingUsecTime
Definition: net.h:711
std::atomic< int64_t > nMinPingUsecTime
Definition: net.h:713
int GetMyStartingHeight() const
Definition: net.h:752
ServiceFlags GetLocalServices() const
Definition: net.h:850
int nVersion
Definition: net.h:527
std::map< CSubNet, CBanEntry > banmap_t
Definition: addrdb.h:78
bool fClient
Definition: net.h:641
std::string strSubVer
Definition: net.h:635
uint64_t nMaxOutboundCycleStartTime
Definition: net.h:375
void Release()
Definition: net.h:785
bool GetLocal(CService &addr, const CNetAddr *paddrPeer=nullptr)
Definition: net.cpp:109
size_t nProcessQueueSize
Definition: net.h:613
std::condition_variable condMsgProc
Definition: net.h:421
bool result_type
Definition: net.h:446
std::atomic< int64_t > nLastRecv
Definition: net.h:623
#define USE_UPNP
Definition: raven-config.h:403
bool fOneShot
Definition: net.h:639
bool BindListenPort(const CService &bindAddr, std::string &strError, bool fWhitelisted=false)
std::thread threadOpenAddedConnections
Definition: net.h:429
#define LOCK(cs)
Definition: sync.h:176
void Interrupt(boost::thread_group &threadGroup)
Interrupt threads.
Definition: init.cpp:169
std::vector< CNode * > vNodes
Definition: net.h:397
bool IsPeerAddrLocalGood(CNode *pnode)
Definition: net.cpp:179
std::deque< std::string > vOneShots
Definition: net.h:393
NetEventsInterface * m_msgproc
Definition: net.h:140
int type
Definition: protocol.h:419
std::string strAddedNode
Definition: net.h:97
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:141
Fast randomness source.
Definition: random.h:45
const CAddress addrBind
Definition: net.h:629
std::vector< std::string > vSeedNodes
Definition: net.h:145
std::vector< std::string > m_specified_outgoing
Definition: net.h:149
CRollingBloomFilter filterInventoryKnown
Definition: net.h:680
std::thread threadMessageHandler
Definition: net.h:431
CMessageHeader hdr
Definition: net.h:559
void ForEachNodeThen(Callable &&pre, CallableAfter &&post)
Definition: net.h:205
bool m_manual_connection
Definition: net.h:640
bool fInbound
Definition: net.h:529
uint64_t nSendBytes
Definition: net.h:605
bool RemoveLocal(const CService &addr)
Definition: net.cpp:241
A CService with information about it as peer.
Definition: protocol.h:340
uint64_t nRecvBytes
Definition: net.h:534
std::vector< unsigned char > GetKey() const
Definition: netaddress.cpp:573
uint256 hash
Definition: protocol.h:420
bool fInbound
Definition: net.h:100
double dPingTime
Definition: net.h:537
std::string addrName
Definition: net.h:526
int nMaxFeeler
Definition: net.h:137
Definition: net.h:474
Network
Definition: netaddress.h:20
std::vector< uint256 > vBlockHashesToAnnounce
Definition: net.h:694
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:436
int64_t NodeId
Definition: net.h:93
Definition: net.h:120
bool GetNetworkActive() const
Definition: net.h:175
NumConnections
Definition: net.h:124
bool fGetAddr
Definition: net.h:671
CClientUIInterface * clientInterface
Definition: net.h:412
uint64_t nRecvBytes
Definition: net.h:619
NodeId GetId() const
Definition: net.h:744
uint64_t nSendBytes
Definition: net.h:532
int nMaxOutbound
Definition: net.h:135
size_t nSendOffset
Definition: net.h:604
std::atomic_bool fDisconnect
Definition: net.h:644
int nMaxConnections
Definition: net.h:407
void SetLimited(enum Network net, bool fLimited=true)
Make a particular network entirely off-limits (no automatic connects to it)
Definition: net.cpp:250
size_t nSendSize
Definition: net.h:603
void ForEachNode(Callable &&func)
Definition: net.h:185
limitedmap< uint256, int64_t > mapAlreadyAskedFor
Definition: net.h:479
CCriticalSection cs_vOneShots
Definition: net.h:394
CRollingBloomFilter addrKnown
Definition: net.h:670
CCriticalSection cs_setBanned
Definition: net.h:389
unsigned char MessageStartChars[MESSAGE_START_SIZE]
Definition: protocol.h:41
unsigned int SOCKET
Definition: compat.h:52
const CAddress addr
Definition: net.h:627
std::atomic< int > nRefCount
Definition: net.h:654
const int64_t nTimeConnected
Definition: net.h:624
int64_t nTime
Definition: net.h:565
uint64_t nMaxOutboundTimeframe
Definition: net.h:143
std::atomic< NodeId > nLastNodeId
Definition: net.h:400
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
Definition: netaddress.h:32
CCriticalSection cs_vRecv
Definition: net.h:609
std::list< CNode * > vNodesDisconnected
Definition: net.h:398
CService addrLocal
Definition: net.h:740
std::atomic< bool > fPingQueued
Definition: net.h:715
256-bit opaque blob.
Definition: uint256.h:123
void AddInventoryKnown(const CInv &inv)
Definition: net.h:812
int nScore
Definition: net.h:508
std::deque< CInvAsset > vRecvAssetGetData
Definition: net.h:618
int nMaxAddnode
Definition: net.h:136
bool fFeeler
Definition: net.h:638
void ForEachNode(Callable &&func) const
Definition: net.h:195
std::atomic< int64_t > nLastTXTime
Definition: net.h:703
bool complete() const
Definition: net.h:575
CAddress addrBind
Definition: net.h:545
const bool fInbound
Definition: net.h:642
std::vector< CSubNet > vWhitelistedRange
Definition: net.h:381
CService resolvedAddress
Definition: net.h:98
std::thread threadOpenConnections
Definition: net.h:430
CSemaphoreGrant grantOutbound
Definition: net.h:651
CSemaphore * semOutbound
Definition: net.h:405
uint256 hashContinue
Definition: net.h:665
bool fWhitelisted
Definition: net.h:637
std::map< std::string, uint64_t > mapMsgCmdSize
Definition: net.h:514
const NodeId id
Definition: net.h:728
bool setBannedIsDirty
Definition: net.h:390
unsigned int nDataPos
Definition: net.h:563
std::string addrLocal
Definition: net.h:541
bool fAddressesInitialized
Definition: net.h:391
std::vector< std::string > vAddedNodes
Definition: net.h:395
std::thread threadDNSAddressSeed
Definition: net.h:427
ServiceFlags nLocalServices
Definition: net.h:133
std::deque< std::vector< unsigned char > > vSendMsg
Definition: net.h:606
uint64_t nMaxOutboundLimit
Definition: net.h:144
void Discover(boost::thread_group &threadGroup)
Definition: net.cpp:2177
std::vector< std::string > m_added_nodes
Definition: net.h:150
CCriticalSection cs_vProcessMsg
Definition: net.h:611
mapMsgCmdSize mapRecvBytesPerMsgCmd
Definition: net.h:662
std::vector< ListenSocket > vhListenSocket
Definition: net.h:386
double dMinPing
Definition: net.h:539
CAmount lastSentFeeFilter
Definition: net.h:719
std::atomic< int64_t > nTimeOffset
Definition: net.h:625
void PushBlockHash(const uint256 &hash)
Definition: net.h:838
std::string command
Definition: net.h:116
void ForEachNodeThen(Callable &&pre, CallableAfter &&post) const
Definition: net.h:216
CCriticalSection cs_totalBytesSent
Definition: net.h:369
std::atomic_bool fSuccessfullyConnected
Definition: net.h:643
SipHash-2-4.
Definition: hash.h:313
std::set< std::string > setInventoryAssetsSend
Definition: net.h:677
SOCKET hSocket
Definition: net.h:602
std::atomic< int > nVersion
Definition: net.h:630
bool fRelayTxes
Definition: net.h:649
int nMaxOutbound
Definition: net.h:408
uint64_t nMaxOutboundTotalBytesSentInCycle
Definition: net.h:374
unsigned int nSendBufferMaxSize
Definition: net.h:383
const uint64_t nLocalHostNonce
Definition: net.h:729
unsigned int nSendBufferMaxSize
Definition: net.h:141
const ServiceFlags nLocalServices
Definition: net.h:731
banmap_t setBanned
Definition: net.h:388
CBloomFilter * pfilter
Definition: net.h:653
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:93
CClientUIInterface uiInterface
Definition: ui_interface.cpp:9
CCriticalSection cs_sendProcessing
Definition: net.h:615
Information about a peer.
Definition: net.h:596
std::thread threadSocketHandler
Definition: net.h:428
int64_t nNextInvSend
Definition: net.h:691
bool fWhitelisted
Definition: net.h:536
CCriticalSection cs_vSend
Definition: net.h:607
int64_t nNextAddrSend
Definition: net.h:673
bool fDiscover
Definition: net.cpp:87
void SetVersion(int n)
Definition: streams.h:340
void AddAddressKnown(const CAddress &_addr)
Definition: net.h:792
std::atomic_bool fPauseRecv
Definition: net.h:657
CNode * AddRef()
Definition: net.h:779
double dPingWait
Definition: net.h:538
void Init(const Options &connOptions)
Definition: net.h:153
CThreadInterrupt interruptNet
Definition: net.h:425
CCriticalSection cs_totalBytesRecv
Definition: net.h:368
CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
Definition: net.cpp:158
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
Definition: net.cpp:210
const uint64_t nSeed1
Definition: net.h:416
std::atomic< int > nRecvVersion
Definition: net.h:620
std::atomic< int64_t > nLastBlockTime
Definition: net.h:702
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:283
std::multimap< int64_t, CInv > mapAskFor
Definition: net.h:690
CCriticalSection cs_mapLocalHost
Definition: net.cpp:90
bool fRelayTxes
Definition: net.h:521
int64_t nLastSend
Definition: net.h:522
unsigned short GetListenPort()
Definition: net.cpp:103
const int nMyStartingHeight
Definition: net.h:732
bool IsLimited(enum Network net)
Definition: net.cpp:258
Wrapped boost mutex: supports recursive locking, but no waiting TODO: We should move away from using ...
Definition: sync.h:92
int nBestHeight
Definition: net.h:138
NodeId nodeid
Definition: net.h:519
int64_t nLastRecv
Definition: net.h:523
std::set< uint256 > setAskFor
Definition: net.h:689
unsigned int nReceiveFloodSize
Definition: net.h:384
CAddress addr
Definition: net.h:543
Message header.
Definition: protocol.h:28
uint64_t nTotalBytesRecv
Definition: net.h:370
bool fGetAssetData
Definition: net.h:676