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