Bitcoin ABC  0.22.12
P2P Digital Currency
net.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2019 The Bitcoin Core developers
3 // Copyright (c) 2017-2019 The Bitcoin 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 BITCOIN_NET_H
8 #define BITCOIN_NET_H
9 
10 #include <addrdb.h>
11 #include <addrman.h>
12 #include <amount.h>
13 #include <avalanche/delegation.h>
14 #include <bloom.h>
15 #include <chainparams.h>
16 #include <compat.h>
17 #include <crypto/siphash.h>
18 #include <hash.h>
19 #include <limitedmap.h>
20 #include <net_permissions.h>
21 #include <netaddress.h>
22 #include <protocol.h>
23 #include <random.h>
24 #include <streams.h>
25 #include <sync.h>
26 #include <threadinterrupt.h>
27 #include <uint256.h>
28 #include <validation.h> // For cs_main
29 
30 #include <atomic>
31 #include <condition_variable>
32 #include <cstdint>
33 #include <deque>
34 #include <memory>
35 #include <thread>
36 
37 #ifndef WIN32
38 #include <arpa/inet.h>
39 #endif
40 
41 class BanMan;
42 class Config;
43 class CNode;
44 class CScheduler;
45 struct bilingual_str;
46 
48 static const bool DEFAULT_WHITELISTRELAY = true;
50 static const bool DEFAULT_WHITELISTFORCERELAY = false;
51 
56 static const int PING_INTERVAL = 2 * 60;
61 static const int TIMEOUT_INTERVAL = 20 * 60;
63 static const int FEELER_INTERVAL = 120;
65 static const unsigned int MAX_INV_SZ = 50000;
66 static_assert(MAX_PROTOCOL_MESSAGE_LENGTH > MAX_INV_SZ * sizeof(CInv),
67  "Max protocol message length must be greater than largest "
68  "possible INV message");
70 static const unsigned int MAX_LOCATOR_SZ = 101;
72 static const unsigned int MAX_ADDR_TO_SEND = 1000;
74 static const unsigned int MAX_SUBVERSION_LENGTH = 256;
81 static const int MAX_ADDNODE_CONNECTIONS = 8;
83 static const int MAX_BLOCKS_ONLY_CONNECTIONS = 2;
85 static const bool DEFAULT_LISTEN = true;
87 #ifdef USE_UPNP
88 static const bool DEFAULT_UPNP = USE_UPNP;
89 #else
90 static const bool DEFAULT_UPNP = false;
91 #endif
92 
97 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 4096;
99 static const uint64_t DEFAULT_MAX_UPLOAD_TARGET = 0;
101 static const uint64_t MAX_UPLOAD_TIMEFRAME = 60 * 60 * 24;
103 static const bool DEFAULT_BLOCKSONLY = false;
105 static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
106 
107 static const bool DEFAULT_FORCEDNSSEED = false;
108 static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
109 static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
110 
111 typedef int64_t NodeId;
112 
116 static constexpr NodeId NO_NODE = -1;
117 
119  std::string strAddedNode;
122  bool fInbound;
123 };
124 
125 struct CNodeStats;
126 class CClientUIInterface;
127 
129  CSerializedNetMsg() = default;
130  CSerializedNetMsg(CSerializedNetMsg &&) = default;
131  CSerializedNetMsg &operator=(CSerializedNetMsg &&) = default;
132  // No copying, only moves.
133  CSerializedNetMsg(const CSerializedNetMsg &msg) = delete;
134  CSerializedNetMsg &operator=(const CSerializedNetMsg &) = delete;
135 
136  std::vector<uint8_t> data;
137  std::string m_type;
138 };
139 
145 enum class ConnectionType {
147  INBOUND,
152  OUTBOUND,
157  MANUAL,
159  FEELER,
164  BLOCK_RELAY,
169  ADDR_FETCH,
170 };
171 
172 namespace {
173 struct CConnmanTest;
174 }
175 
176 class NetEventsInterface;
177 class CConnman {
178 public:
180  CONNECTIONS_NONE = 0,
181  CONNECTIONS_IN = (1U << 0),
182  CONNECTIONS_OUT = (1U << 1),
183  CONNECTIONS_ALL = (CONNECTIONS_IN | CONNECTIONS_OUT),
184  };
185 
186  struct Options {
187  ServiceFlags nLocalServices = NODE_NONE;
188  int nMaxConnections = 0;
189  int m_max_outbound_full_relay = 0;
190  int m_max_outbound_block_relay = 0;
191  int nMaxAddnode = 0;
192  int nMaxFeeler = 0;
193  int nBestHeight = 0;
195  NetEventsInterface *m_msgproc = nullptr;
196  BanMan *m_banman = nullptr;
197  unsigned int nSendBufferMaxSize = 0;
198  unsigned int nReceiveFloodSize = 0;
199  uint64_t nMaxOutboundTimeframe = 0;
200  uint64_t nMaxOutboundLimit = 0;
201  int64_t m_peer_connect_timeout = DEFAULT_PEER_CONNECT_TIMEOUT;
202  std::vector<std::string> vSeedNodes;
203  std::vector<NetWhitelistPermissions> vWhitelistedRange;
204  std::vector<NetWhitebindPermissions> vWhiteBinds;
205  std::vector<CService> vBinds;
206  bool m_use_addrman_outgoing = true;
207  std::vector<std::string> m_specified_outgoing;
208  std::vector<std::string> m_added_nodes;
209  std::vector<bool> m_asmap;
210  };
211 
212  void Init(const Options &connOptions) {
213  nLocalServices = connOptions.nLocalServices;
214  nMaxConnections = connOptions.nMaxConnections;
215  m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
216  nMaxAddnode = connOptions.nMaxAddnode;
217  nMaxFeeler = connOptions.nMaxFeeler;
218  {
219  // Lock cs_main to prevent a potential race with the peer validation
220  // logic thread.
221  LOCK(::cs_main);
222  m_max_outbound_full_relay =
223  std::min(connOptions.m_max_outbound_full_relay,
224  connOptions.nMaxConnections);
225  m_max_outbound_block_relay = connOptions.m_max_outbound_block_relay;
226  m_max_outbound = m_max_outbound_full_relay +
227  m_max_outbound_block_relay + nMaxFeeler;
228  }
229  nBestHeight = connOptions.nBestHeight;
230  clientInterface = connOptions.uiInterface;
231  m_banman = connOptions.m_banman;
232  m_msgproc = connOptions.m_msgproc;
233  nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
234  nReceiveFloodSize = connOptions.nReceiveFloodSize;
235  m_peer_connect_timeout = connOptions.m_peer_connect_timeout;
236  {
237  LOCK(cs_totalBytesSent);
238  nMaxOutboundTimeframe = connOptions.nMaxOutboundTimeframe;
239  nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
240  }
241  vWhitelistedRange = connOptions.vWhitelistedRange;
242  {
243  LOCK(cs_vAddedNodes);
244  vAddedNodes = connOptions.m_added_nodes;
245  }
246  }
247 
248  CConnman(const Config &configIn, uint64_t seed0, uint64_t seed1);
249  ~CConnman();
250 
251  bool Start(CScheduler &scheduler, const Options &options);
252 
253  void StopThreads();
254  void StopNodes();
255  void Stop() {
256  StopThreads();
257  StopNodes();
258  };
259 
260  void Interrupt();
261  bool GetNetworkActive() const { return fNetworkActive; };
262  bool GetUseAddrmanOutgoing() const { return m_use_addrman_outgoing; };
263  void SetNetworkActive(bool active);
264  void
265  OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure,
266  CSemaphoreGrant *grantOutbound = nullptr,
267  const char *strDest = nullptr,
269  bool CheckIncomingNonce(uint64_t nonce);
270 
271  bool ForNode(NodeId id, std::function<bool(CNode *pnode)> func);
272 
273  void PushMessage(CNode *pnode, CSerializedNetMsg &&msg);
274 
275  template <typename Callable> void ForEachNode(Callable &&func) {
276  LOCK(cs_vNodes);
277  for (auto &&node : vNodes) {
278  if (NodeFullyConnected(node)) {
279  func(node);
280  }
281  }
282  };
283 
284  template <typename Callable> void ForEachNode(Callable &&func) const {
285  LOCK(cs_vNodes);
286  for (auto &&node : vNodes) {
287  if (NodeFullyConnected(node)) {
288  func(node);
289  }
290  }
291  };
292 
293  template <typename Callable, typename CallableAfter>
294  void ForEachNodeThen(Callable &&pre, CallableAfter &&post) {
295  LOCK(cs_vNodes);
296  for (auto &&node : vNodes) {
297  if (NodeFullyConnected(node)) {
298  pre(node);
299  }
300  }
301  post();
302  };
303 
304  template <typename Callable, typename CallableAfter>
305  void ForEachNodeThen(Callable &&pre, CallableAfter &&post) const {
306  LOCK(cs_vNodes);
307  for (auto &&node : vNodes) {
308  if (NodeFullyConnected(node)) {
309  pre(node);
310  }
311  }
312  post();
313  };
314 
315  // Addrman functions
316  void SetServices(const CService &addr, ServiceFlags nServices);
317  void MarkAddressGood(const CAddress &addr);
318  void AddNewAddresses(const std::vector<CAddress> &vAddr,
319  const CAddress &addrFrom, int64_t nTimePenalty = 0);
320  std::vector<CAddress> GetAddresses();
321 
322  // This allows temporarily exceeding m_max_outbound_full_relay, with the
323  // goal of finding a peer that is better than all our current peers.
324  void SetTryNewOutboundPeer(bool flag);
325  bool GetTryNewOutboundPeer();
326 
327  // Return the number of outbound peers we have in excess of our target (eg,
328  // if we previously called SetTryNewOutboundPeer(true), and have since set
329  // to false, we may have extra peers that we wish to disconnect). This may
330  // return a value less than (num_outbound_connections - num_outbound_slots)
331  // in cases where some outbound connections are not yet fully connected, or
332  // not yet fully disconnected.
333  int GetExtraOutboundCount();
334 
335  bool AddNode(const std::string &node);
336  bool RemoveAddedNode(const std::string &node);
337  std::vector<AddedNodeInfo> GetAddedNodeInfo();
338 
339  size_t GetNodeCount(NumConnections num);
340  void GetNodeStats(std::vector<CNodeStats> &vstats);
341  bool DisconnectNode(const std::string &node);
342  bool DisconnectNode(const CSubNet &subnet);
343  bool DisconnectNode(const CNetAddr &addr);
344  bool DisconnectNode(NodeId id);
345 
352  ServiceFlags GetLocalServices() const;
353 
355  void SetMaxOutboundTarget(uint64_t limit);
356  uint64_t GetMaxOutboundTarget();
357 
359  void SetMaxOutboundTimeframe(uint64_t timeframe);
360  uint64_t GetMaxOutboundTimeframe();
361 
365  bool OutboundTargetReached(bool historicalBlockServingLimit);
366 
369  uint64_t GetOutboundTargetBytesLeft();
370 
373  uint64_t GetMaxOutboundTimeLeftInCycle();
374 
375  uint64_t GetTotalBytesRecv();
376  uint64_t GetTotalBytesSent();
377 
378  void SetBestHeight(int height);
379  int GetBestHeight() const;
380 
382  CSipHasher GetDeterministicRandomizer(uint64_t id) const;
383 
384  unsigned int GetReceiveFloodSize() const;
385 
386  void WakeMessageHandler();
387 
393  int64_t PoissonNextSendInbound(int64_t now, int average_interval_seconds);
394 
395  void SetAsmap(std::vector<bool> asmap) {
396  addrman.m_asmap = std::move(asmap);
397  }
398 
399 private:
400  struct ListenSocket {
401  public:
404  NetPermissions::AddFlag(flags, m_permissions);
405  }
406  ListenSocket(SOCKET socket_, NetPermissionFlags permissions_)
407  : socket(socket_), m_permissions(permissions_) {}
408 
409  private:
411  };
412 
413  bool BindListenPort(const CService &bindAddr, bilingual_str &strError,
414  NetPermissionFlags permissions);
415  bool Bind(const CService &addr, unsigned int flags,
416  NetPermissionFlags permissions);
417  bool InitBinds(const std::vector<CService> &binds,
418  const std::vector<NetWhitebindPermissions> &whiteBinds);
419  void ThreadOpenAddedConnections();
420  void AddAddrFetch(const std::string &strDest);
421  void ProcessAddrFetch();
422  void ThreadOpenConnections(std::vector<std::string> connect);
423  void ThreadMessageHandler();
424  void AcceptConnection(const ListenSocket &hListenSocket);
425  void DisconnectNodes();
427  void InactivityCheck(CNode *pnode);
428  bool GenerateSelectSet(std::set<SOCKET> &recv_set,
429  std::set<SOCKET> &send_set,
430  std::set<SOCKET> &error_set);
431  void SocketEvents(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set,
432  std::set<SOCKET> &error_set);
433  void SocketHandler();
434  void ThreadSocketHandler();
435  void ThreadDNSAddressSeed();
436 
437  uint64_t CalculateKeyedNetGroup(const CAddress &ad) const;
438 
439  CNode *FindNode(const CNetAddr &ip);
440  CNode *FindNode(const CSubNet &subNet);
441  CNode *FindNode(const std::string &addrName);
442  CNode *FindNode(const CService &addr);
443 
444  bool AttemptToEvictConnection();
445  CNode *ConnectNode(CAddress addrConnect, const char *pszDest,
446  bool fCountFailure, ConnectionType conn_type);
447  void AddWhitelistPermissionFlags(NetPermissionFlags &flags,
448  const CNetAddr &addr) const;
449 
450  void DeleteNode(CNode *pnode);
451 
452  NodeId GetNewNodeId();
453 
454  size_t SocketSendData(CNode *pnode) const;
455  void DumpAddresses();
456 
457  // Network stats
458  void RecordBytesRecv(uint64_t bytes);
459  void RecordBytesSent(uint64_t bytes);
460 
461  // Whether the node should be passed out in ForEach* callbacks
462  static bool NodeFullyConnected(const CNode *pnode);
463 
464  const Config *config;
465 
466  // Network usage totals
469  uint64_t nTotalBytesRecv GUARDED_BY(cs_totalBytesRecv){0};
470  uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent){0};
471 
472  // outbound limit & stats
473  uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent);
474  uint64_t nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent);
475  uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent);
476  uint64_t nMaxOutboundTimeframe GUARDED_BY(cs_totalBytesSent);
477 
478  // P2P timeout in seconds
480 
481  // Whitelisted ranges. Any node connecting from these is automatically
482  // whitelisted (as well as those connecting to whitelisted binds).
483  std::vector<NetWhitelistPermissions> vWhitelistedRange;
484 
485  unsigned int nSendBufferMaxSize{0};
486  unsigned int nReceiveFloodSize{0};
487 
488  std::vector<ListenSocket> vhListenSocket;
489  std::atomic<bool> fNetworkActive{true};
490  bool fAddressesInitialized{false};
492  std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
494  std::vector<std::string> vAddedNodes GUARDED_BY(cs_vAddedNodes);
496  std::vector<CNode *> vNodes GUARDED_BY(cs_vNodes);
497  std::list<CNode *> vNodesDisconnected;
499  std::atomic<NodeId> nLastNodeId{0};
500  unsigned int nPrevNodeCount{0};
501 
515 
516  std::unique_ptr<CSemaphore> semOutbound;
517  std::unique_ptr<CSemaphore> semAddnode;
519 
520  // How many full-relay (tx, block, addr) outbound peers we want
522 
523  // How many block-relay only outbound peers we want
524  // We do not relay tx or addr messages with these peers
526 
531  std::atomic<int> nBestHeight;
539 
541  const uint64_t nSeed0, nSeed1;
542 
544  bool fMsgProcWake GUARDED_BY(mutexMsgProc);
545 
546  std::condition_variable condMsgProc;
548  std::atomic<bool> flagInterruptMsgProc{false};
549 
551 
552  std::thread threadDNSAddressSeed;
553  std::thread threadSocketHandler;
556  std::thread threadMessageHandler;
557 
562  std::atomic_bool m_try_another_outbound_peer;
563 
564  std::atomic<int64_t> m_next_send_inv_to_incoming{0};
565 
566  friend struct ::CConnmanTest;
567  friend struct ConnmanTestMsg;
568 };
569 
570 void Discover();
571 void StartMapPort();
572 void InterruptMapPort();
573 void StopMapPort();
574 unsigned short GetListenPort();
575 
580 public:
581  virtual bool ProcessMessages(const Config &config, CNode *pnode,
582  std::atomic<bool> &interrupt) = 0;
583  virtual bool SendMessages(const Config &config, CNode *pnode,
584  std::atomic<bool> &interrupt) = 0;
585  virtual void InitializeNode(const Config &config, CNode *pnode) = 0;
586  virtual void FinalizeNode(const Config &config, NodeId id,
587  bool &update_connection_time) = 0;
588 
589 protected:
595  ~NetEventsInterface() = default;
596 };
597 
598 enum {
599  // unknown
601  // address a local interface listens on
603  // address explicit bound to
605  // address reported by UPnP
607  // address explicitly specified (-externalip=)
609 
611 };
612 
613 bool IsPeerAddrLocalGood(CNode *pnode);
614 void AdvertiseLocal(CNode *pnode);
615 
620 void SetReachable(enum Network net, bool reachable);
622 bool IsReachable(enum Network net);
624 bool IsReachable(const CNetAddr &addr);
625 
626 bool AddLocal(const CService &addr, int nScore = LOCAL_NONE);
627 bool AddLocal(const CNetAddr &addr, int nScore = LOCAL_NONE);
628 void RemoveLocal(const CService &addr);
629 bool SeenLocal(const CService &addr);
630 bool IsLocal(const CService &addr);
631 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr);
632 CAddress GetLocalAddress(const CNetAddr *paddrPeer,
633  ServiceFlags nLocalServices);
634 
635 extern bool fDiscover;
636 extern bool fListen;
637 extern bool g_relay_txes;
638 
640  int nScore;
641  int nPort;
642 };
643 
645 extern std::map<CNetAddr, LocalServiceInfo>
646  mapLocalHost GUARDED_BY(cs_mapLocalHost);
647 
648 extern const std::string NET_MESSAGE_COMMAND_OTHER;
649 // Command, total bytes
650 typedef std::map<std::string, uint64_t> mapMsgCmdSize;
651 
657 struct CNodeStats {
658  NodeId nodeid;
661  int64_t nLastSend;
662  int64_t nLastRecv;
663  int64_t nTimeConnected;
664  int64_t nTimeOffset;
665  std::string addrName;
666  int nVersion;
667  std::string cleanSubVer;
668  bool fInbound;
671  uint64_t nSendBytes;
672  mapMsgCmdSize mapSendBytesPerMsgCmd;
673  uint64_t nRecvBytes;
674  mapMsgCmdSize mapRecvBytesPerMsgCmd;
677  int64_t m_ping_usec;
681  // Our address, as reported by the peer
682  std::string addrLocal;
683  // Address of this peer
685  // Bind address of our side of the connection
687  uint32_t m_mapped_as;
688 };
689 
695 class CNetMessage {
696 public:
697  // received message data
699  // time (in microseconds) of message receipt.
700  int64_t m_time = 0;
701  bool m_valid_netmagic = false;
702  bool m_valid_header = false;
703  bool m_valid_checksum = false;
704  // size of the payload
705  uint32_t m_message_size = 0;
706  // used wire size of the message (including header/checksum)
707  uint32_t m_raw_message_size = 0;
708  std::string m_command;
709 
710  CNetMessage(CDataStream &&recv_in) : m_recv(std::move(recv_in)) {}
711 
712  void SetVersion(int nVersionIn) { m_recv.SetVersion(nVersionIn); }
713 };
714 
721 public:
722  // returns true if the current deserialization is complete
723  virtual bool Complete() const = 0;
724  // set the serialization context version
725  virtual void SetVersion(int version) = 0;
726  // read and deserialize data
727  virtual int Read(const Config &config, const char *data,
728  uint32_t bytes) = 0;
729  // decomposes a message from the context
730  virtual CNetMessage GetMessage(const Config &config, int64_t time) = 0;
732 };
733 
735 private:
736  mutable CHash256 hasher;
738 
739  // Parsing header (false) or data (true)
740  bool in_data;
741  // Partially received header.
743  // Complete header.
745  // Received message data.
747  uint32_t nHdrPos;
748  uint32_t nDataPos;
749 
750  const uint256 &GetMessageHash() const;
751  int readHeader(const Config &config, const char *pch, uint32_t nBytes);
752  int readData(const char *pch, uint32_t nBytes);
753 
754  void Reset() {
755  vRecv.clear();
756  hdrbuf.clear();
757  hdrbuf.resize(24);
758  in_data = false;
759  nHdrPos = 0;
760  nDataPos = 0;
761  data_hash.SetNull();
762  hasher.Reset();
763  }
764 
765 public:
767  const CMessageHeader::MessageMagic &pchMessageStartIn, int nTypeIn,
768  int nVersionIn)
769  : hdrbuf(nTypeIn, nVersionIn), hdr(pchMessageStartIn),
770  vRecv(nTypeIn, nVersionIn) {
771  Reset();
772  }
773 
774  bool Complete() const override {
775  if (!in_data) {
776  return false;
777  }
778 
779  return (hdr.nMessageSize == nDataPos);
780  }
781 
782  void SetVersion(int nVersionIn) override {
783  hdrbuf.SetVersion(nVersionIn);
784  vRecv.SetVersion(nVersionIn);
785  }
786  int Read(const Config &config, const char *pch, uint32_t nBytes) override {
787  int ret =
788  in_data ? readData(pch, nBytes) : readHeader(config, pch, nBytes);
789  if (ret < 0) {
790  Reset();
791  }
792  return ret;
793  }
794 
795  CNetMessage GetMessage(const Config &config, int64_t time) override;
796 };
797 
802 public:
803  // prepare message for transport (header construction, error-correction
804  // computation, payload encryption, etc.)
805  virtual void prepareForTransport(const Config &config,
806  CSerializedNetMsg &msg,
807  std::vector<uint8_t> &header) = 0;
808  virtual ~TransportSerializer() {}
809 };
810 
812 public:
813  void prepareForTransport(const Config &config, CSerializedNetMsg &msg,
814  std::vector<uint8_t> &header) override;
815 };
816 
818 class CNode {
819  friend class CConnman;
820  friend struct ConnmanTestMsg;
821 
822 public:
823  std::unique_ptr<TransportDeserializer> m_deserializer;
824  std::unique_ptr<TransportSerializer> m_serializer;
825 
826  // socket
827  std::atomic<ServiceFlags> nServices{NODE_NONE};
828  SOCKET hSocket GUARDED_BY(cs_hSocket);
829  // Total size of all vSendMsg entries.
830  size_t nSendSize{0};
831  // Offset inside the first vSendMsg already sent.
832  size_t nSendOffset{0};
833  uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
834  std::deque<std::vector<uint8_t>> vSendMsg GUARDED_BY(cs_vSend);
838 
840  std::list<CNetMessage> vProcessMsg GUARDED_BY(cs_vProcessMsg);
841  size_t nProcessQueueSize{0};
842 
844 
845  std::deque<CInv> vRecvGetData;
846  uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
847  std::atomic<int> nRecvVersion{INIT_PROTO_VERSION};
848 
849  std::atomic<int64_t> nLastSend{0};
850  std::atomic<int64_t> nLastRecv{0};
851  const int64_t nTimeConnected;
852  std::atomic<int64_t> nTimeOffset{0};
853  // Address of this peer
854  const CAddress addr;
855  // Bind address of our side of the connection
857  std::atomic<int> nVersion{0};
858  // The nonce provided by the remote host.
859  uint64_t nRemoteHostNonce{0};
860  // The extra entropy provided by the remote host.
861  uint64_t nRemoteExtraEntropy{0};
867  std::string cleanSubVer GUARDED_BY(cs_SubVer){};
868  // This peer is preferred for eviction.
869  bool m_prefer_evict{false};
870  bool HasPermission(NetPermissionFlags permission) const {
871  return NetPermissions::HasFlag(m_permissionFlags, permission);
872  }
873  // This boolean is unusued in actual processing, only present for backward
874  // compatibility at RPC/QT level
875  bool m_legacyWhitelisted{false};
876  // set by version message
877  bool fClient{false};
878  // after BIP159, set by version message
879  bool m_limited_node{false};
880  std::atomic_bool fSuccessfullyConnected{false};
881  // Setting fDisconnect to true will cause the node to be disconnected the
882  // next time DisconnectNodes() runs
883  std::atomic_bool fDisconnect{false};
884  bool fSentAddr{false};
886  std::atomic<int> nRefCount{0};
887 
888  const uint64_t nKeyedNetGroup;
889  std::atomic_bool fPauseRecv{false};
890  std::atomic_bool fPauseSend{false};
891 
893  switch (m_conn_type) {
896  return true;
901  return false;
902  }
903 
904  assert(false);
905  }
906 
907  bool IsFullOutboundConn() const {
908  return m_conn_type == ConnectionType::OUTBOUND;
909  }
910 
911  bool IsManualConn() const { return m_conn_type == ConnectionType::MANUAL; }
912 
913  bool IsBlockOnlyConn() const {
914  return m_conn_type == ConnectionType::BLOCK_RELAY;
915  }
916 
917  bool IsFeelerConn() const { return m_conn_type == ConnectionType::FEELER; }
918 
919  bool IsAddrFetchConn() const {
920  return m_conn_type == ConnectionType::ADDR_FETCH;
921  }
922 
923  bool IsInboundConn() const {
924  return m_conn_type == ConnectionType::INBOUND;
925  }
926 
927  bool ExpectServicesFromConn() const {
928  switch (m_conn_type) {
932  return false;
936  return true;
937  }
938 
939  assert(false);
940  }
941 
942 protected:
943  mapMsgCmdSize mapSendBytesPerMsgCmd;
944  mapMsgCmdSize mapRecvBytesPerMsgCmd GUARDED_BY(cs_vRecv);
945 
946 public:
948  std::atomic<int> nStartingHeight{-1};
949 
950  // flood relay
951  std::vector<CAddress> vAddrToSend;
952  std::unique_ptr<CRollingBloomFilter> m_addr_known = nullptr;
953  bool fGetAddr{false};
954  std::chrono::microseconds m_next_addr_send GUARDED_BY(cs_sendProcessing){0};
955  std::chrono::microseconds
956  m_next_local_addr_send GUARDED_BY(cs_sendProcessing){0};
957 
958  bool IsAddrRelayPeer() const { return m_addr_known != nullptr; }
959 
960  // List of block ids we still have to announce.
961  // There is no final sorting before sending, as they are always sent
962  // immediately and in the order requested.
963  std::vector<BlockHash> vInventoryBlockToSend GUARDED_BY(cs_inventory);
965 
966  struct TxRelay {
967  TxRelay() { pfilter = std::make_unique<CBloomFilter>(); }
969  // We use fRelayTxes for two purposes -
970  // a) it allows us to not relay tx invs before receiving the peer's
971  // version message.
972  // b) the peer may tell us in its version message that we should not
973  // relay tx invs unless it loads a bloom filter.
974  bool fRelayTxes GUARDED_BY(cs_filter){false};
975  std::unique_ptr<CBloomFilter> pfilter PT_GUARDED_BY(cs_filter)
976  GUARDED_BY(cs_filter);
977 
979  CRollingBloomFilter filterInventoryKnown GUARDED_BY(cs_tx_inventory){
980  50000, 0.000001};
981  // Set of transaction ids we still have to announce.
982  // They are sorted by the mempool before relay, so the order is not
983  // important.
984  std::set<TxId> setInventoryTxToSend;
985  // Used for BIP35 mempool sending
986  bool fSendMempool GUARDED_BY(cs_tx_inventory){false};
987  // Last time a "MEMPOOL" request was serviced.
988  std::atomic<std::chrono::seconds> m_last_mempool_req{
989  std::chrono::seconds{0}};
990  std::chrono::microseconds nNextInvSend{0};
991 
993  // Minimum fee rate with which to filter inv's to this node
994  Amount minFeeFilter GUARDED_BY(cs_feeFilter){Amount::zero()};
995  Amount lastSentFeeFilter{Amount::zero()};
996  int64_t nextSendTimeFeeFilter{0};
997  };
998 
999  // m_tx_relay == nullptr if we're not relaying transactions with this peer
1000  std::unique_ptr<TxRelay> m_tx_relay;
1001 
1004 
1006  };
1007 
1008  // m_avalanche_state == nullptr if we're not using avalanche with this peer
1009  std::unique_ptr<AvalancheState> m_avalanche_state;
1010 
1011  // Used for headers announcements - unfiltered blocks to relay
1012  std::vector<BlockHash> vBlockHashesToAnnounce GUARDED_BY(cs_inventory);
1013 
1014  // Block and TXN accept times
1015  std::atomic<int64_t> nLastBlockTime{0};
1016  std::atomic<int64_t> nLastTXTime{0};
1017 
1018  // Ping time measurement:
1019  // The pong reply we're expecting, or 0 if no pong expected.
1020  std::atomic<uint64_t> nPingNonceSent{0};
1021  // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
1022  std::atomic<int64_t> nPingUsecStart{0};
1023  // Last measured round-trip time.
1024  std::atomic<int64_t> nPingUsecTime{0};
1025  // Best measured round-trip time.
1026  std::atomic<int64_t> nMinPingUsecTime{std::numeric_limits<int64_t>::max()};
1027  // Whether a ping is requested.
1028  std::atomic<bool> fPingQueued{false};
1029 
1030  std::set<TxId> orphan_work_set;
1031 
1032  CNode(NodeId id, ServiceFlags nLocalServicesIn, int nMyStartingHeightIn,
1033  SOCKET hSocketIn, const CAddress &addrIn, uint64_t nKeyedNetGroupIn,
1034  uint64_t nLocalHostNonceIn, uint64_t nLocalExtraEntropyIn,
1035  const CAddress &addrBindIn, const std::string &addrNameIn,
1036  ConnectionType conn_type_in);
1037  ~CNode();
1038  CNode(const CNode &) = delete;
1039  CNode &operator=(const CNode &) = delete;
1040 
1041 private:
1042  const NodeId id;
1043  const uint64_t nLocalHostNonce;
1044  const uint64_t nLocalExtraEntropy;
1046 
1063 
1065  int nSendVersion{0};
1066  NetPermissionFlags m_permissionFlags{PF_NONE};
1067  // Used only by SocketHandler thread
1068  std::list<CNetMessage> vRecvMsg;
1069 
1071  std::string addrName GUARDED_BY(cs_addrName);
1072 
1073  // Our address, as reported by the peer
1074  CService addrLocal GUARDED_BY(cs_addrLocal);
1076 
1077 public:
1078  NodeId GetId() const { return id; }
1079 
1080  uint64_t GetLocalNonce() const { return nLocalHostNonce; }
1081  uint64_t GetLocalExtraEntropy() const { return nLocalExtraEntropy; }
1082 
1083  int GetMyStartingHeight() const { return nMyStartingHeight; }
1084 
1085  int GetRefCount() const {
1086  assert(nRefCount >= 0);
1087  return nRefCount;
1088  }
1089 
1090  bool ReceiveMsgBytes(const Config &config, const char *pch, uint32_t nBytes,
1091  bool &complete);
1092 
1093  void SetRecvVersion(int nVersionIn) { nRecvVersion = nVersionIn; }
1094  int GetRecvVersion() const { return nRecvVersion; }
1095  void SetSendVersion(int nVersionIn);
1096  int GetSendVersion() const;
1097 
1098  CService GetAddrLocal() const;
1100  void SetAddrLocal(const CService &addrLocalIn);
1101 
1103  nRefCount++;
1104  return this;
1105  }
1106 
1107  void Release() { nRefCount--; }
1108 
1109  void AddAddressKnown(const CAddress &_addr) {
1110  assert(m_addr_known);
1111  m_addr_known->insert(_addr.GetKey());
1112  }
1113 
1114  void PushAddress(const CAddress &_addr, FastRandomContext &insecure_rand) {
1115  // Known checking here is only to save space from duplicates.
1116  // SendMessages will filter it again for knowns that were added
1117  // after addresses were pushed.
1118  assert(m_addr_known);
1119  if (_addr.IsValid() && !m_addr_known->contains(_addr.GetKey())) {
1120  if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
1121  vAddrToSend[insecure_rand.randrange(vAddrToSend.size())] =
1122  _addr;
1123  } else {
1124  vAddrToSend.push_back(_addr);
1125  }
1126  }
1127  }
1128 
1129  void AddKnownTx(const TxId &txid) {
1130  if (m_tx_relay != nullptr) {
1131  LOCK(m_tx_relay->cs_tx_inventory);
1132  m_tx_relay->filterInventoryKnown.insert(txid);
1133  }
1134  }
1135 
1136  void PushInventory(const CInv &inv) {
1137  if (inv.type == MSG_TX && m_tx_relay != nullptr) {
1138  const TxId txid(inv.hash);
1139  LOCK(m_tx_relay->cs_tx_inventory);
1140  if (!m_tx_relay->filterInventoryKnown.contains(txid)) {
1141  m_tx_relay->setInventoryTxToSend.insert(txid);
1142  }
1143  } else if (inv.type == MSG_BLOCK) {
1144  const BlockHash hash(inv.hash);
1145  LOCK(cs_inventory);
1146  vInventoryBlockToSend.push_back(hash);
1147  }
1148  }
1149 
1150  void PushBlockHash(const BlockHash &hash) {
1151  LOCK(cs_inventory);
1152  vBlockHashesToAnnounce.push_back(hash);
1153  }
1154 
1155  void CloseSocketDisconnect();
1156 
1157  void copyStats(CNodeStats &stats, const std::vector<bool> &m_asmap);
1158 
1159  ServiceFlags GetLocalServices() const { return nLocalServices; }
1160 
1161  std::string GetAddrName() const;
1163  void MaybeSetAddrName(const std::string &addrNameIn);
1164 };
1165 
1170 int64_t PoissonNextSend(int64_t now, int average_interval_seconds);
1171 
1173 inline std::chrono::microseconds
1174 PoissonNextSend(std::chrono::microseconds now,
1175  std::chrono::seconds average_interval) {
1176  return std::chrono::microseconds{
1177  PoissonNextSend(now.count(), average_interval.count())};
1178 }
1179 
1180 std::string getSubVersionEB(uint64_t MaxBlockSize);
1181 std::string userAgent(const Config &config);
1182 
1183 #endif // BITCOIN_NET_H
std::vector< CService > vBinds
Definition: net.h:205
int m_max_outbound_full_relay
Definition: net.h:189
uint256 data_hash
Definition: net.h:737
std::string m_type
Definition: net.h:137
uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent)
Definition: net.h:470
int nMaxFeeler
Definition: net.h:528
static constexpr NodeId NO_NODE
Special NodeId that represent no node.
Definition: net.h:116
std::vector< bool > m_asmap
Definition: net.h:209
bool IsReachable(enum Network net)
Definition: net.cpp:275
int m_max_outbound
Definition: net.h:529
static constexpr Amount zero()
Definition: amount.h:35
static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH
Maximum length of incoming protocol messages (Currently 2MB).
Definition: protocol.h:28
Definition: banman.h:58
Amount minFeeFilter
Definition: net.h:680
static void AddFlag(NetPermissionFlags &flags, NetPermissionFlags f)
void AddKnownTx(const TxId &txid)
Definition: net.h:1129
ServiceFlags
nServices flags.
Definition: protocol.h:320
static const uint64_t MAX_UPLOAD_TIMEFRAME
The default timeframe for -maxuploadtarget.
Definition: net.h:101
void SetNull()
Definition: uint256.h:35
std::unique_ptr< TransportSerializer > m_serializer
Definition: net.h:824
RecursiveMutex cs_vNodes
Definition: net.h:498
std::string cleanSubVer GUARDED_BY(cs_SubVer)
Definition: net.h:867
bool fListen
Definition: net.cpp:110
int m_max_outbound_block_relay
Definition: net.h:190
Connections to addresses added via addnode or the connect command line argument.
std::string addrLocal
Definition: net.h:682
std::atomic< int > nBestHeight
Definition: net.h:531
bool fRelayTxes GUARDED_BY(cs_filter)
Definition: net.h:974
Bilingual messages:
Definition: translation.h:17
const std::string NET_MESSAGE_COMMAND_OTHER
Definition: net.cpp:98
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(cs_mapLocalHost)
void SetVersion(int nVersionIn) override
Definition: net.h:782
CAddress addrBind
Definition: net.h:686
BanMan * m_banman
Definition: net.h:196
void PushBlockHash(const BlockHash &hash)
Definition: net.h:1150
Mutex mutexMsgProc
Definition: net.h:547
bool m_legacyWhitelisted
Definition: net.h:676
static const bool DEFAULT_FORCEDNSSEED
Definition: net.h:107
const uint64_t nKeyedNetGroup
Definition: net.h:888
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:285
int GetRecvVersion() const
Definition: net.h:1094
mapMsgCmdSize mapSendBytesPerMsgCmd
Definition: net.h:943
CDataStream hdrbuf
Definition: net.h:742
bool IsOutboundOrBlockRelayConn() const
Definition: net.h:892
void StartMapPort()
Definition: net.cpp:1732
void StopMapPort()
Definition: net.cpp:1738
Inv(ventory) message data.
Definition: protocol.h:493
uint64_t nRecvBytes
Definition: net.h:673
std::list< CNode * > vNodesDisconnected
Definition: net.h:497
RecursiveMutex cs_inventory
Definition: net.h:964
NodeId nodeid
Definition: net.h:658
const ConnectionType m_conn_type
Definition: net.h:1045
Full relay connections (blocks, addrs, txns) made automatically.
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:483
bool IsFeelerConn() const
Definition: net.h:917
unsigned int nReceiveFloodSize
Definition: net.h:198
RecursiveMutex cs_filter
Definition: net.h:968
int m_max_outbound_full_relay
Definition: net.h:521
CClientUIInterface * uiInterface
Definition: net.h:194
void resize(size_type n, value_type c=0)
Definition: streams.h:281
bool g_relay_txes
Definition: net.cpp:111
void SetAsmap(std::vector< bool > asmap)
Definition: net.h:395
Definition: amount.h:17
CDataStream m_recv
Definition: net.h:698
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:85
CNetMessage(CDataStream &&recv_in)
Definition: net.h:710
int nMaxAddnode
Definition: net.h:527
RAII-style semaphore lock.
Definition: sync.h:301
std::set< TxId > orphan_work_set
Definition: net.h:1030
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:81
RecursiveMutex cs_vProcessMsg
Definition: net.h:839
Interface for message handling.
Definition: net.h:579
void SetVersion(int nVersionIn)
Definition: net.h:712
RecursiveMutex cs_addrName
Definition: net.h:1070
RollingBloomFilter is a probabilistic "keep track of most recently inserted" set. ...
Definition: bloom.h:134
NetEventsInterface * m_msgproc
Definition: net.h:533
int nMaxConnections
Definition: net.h:188
V1TransportDeserializer(const CMessageHeader::MessageMagic &pchMessageStartIn, int nTypeIn, int nVersionIn)
Definition: net.h:766
void AdvertiseLocal(CNode *pnode)
Definition: net.cpp:200
int nStartingHeight
Definition: net.h:670
int m_max_outbound_block_relay
Definition: net.h:525
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:196
uint32_t nMessageSize
Definition: protocol.h:79
A hasher class for Bitcoin&#39;s 256-bit hash (double SHA-256).
Definition: hash.h:22
uint64_t GetLocalNonce() const
Definition: net.h:1080
std::unique_ptr< TransportDeserializer > m_deserializer
Definition: net.h:823
std::vector< CAddress > vAddrToSend
Definition: net.h:951
void PushAddress(const CAddress &_addr, FastRandomContext &insecure_rand)
Definition: net.h:1114
NetPermissionFlags m_permissionFlags
Definition: net.h:675
static const int FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes or 120 seconds.
Definition: net.h:63
RecursiveMutex cs_vRecv
Definition: net.h:837
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Definition: net.h:833
static const int TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:61
void SetRecvVersion(int nVersionIn)
Definition: net.h:1093
Definition: net.h:610
Signals for UI communication.
Definition: ui_interface.h:24
std::string userAgent(const Config &config)
Definition: net.cpp:3164
std::list< CNetMessage > vRecvMsg
Definition: net.h:1068
void PushInventory(const CInv &inv)
Definition: net.h:1136
mapMsgCmdSize mapSendBytesPerMsgCmd
Definition: net.h:672
CAddrMan addrman
Definition: net.h:491
static const int MAX_BLOCKS_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:83
std::deque< CInv > vRecvGetData
Definition: net.h:845
avalanche::Delegation delegation
Definition: net.h:1005
bool fConnected
Definition: net.h:121
virtual ~TransportDeserializer()
Definition: net.h:731
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition: net.h:403
int GetRefCount() const
Definition: net.h:1085
RecursiveMutex cs_sendProcessing
Definition: net.h:843
ServiceFlags nLocalServices
Services this instance offers.
Definition: net.h:514
mapMsgCmdSize mapRecvBytesPerMsgCmd
Definition: net.h:674
bool IsValid() const
Definition: netaddress.cpp:244
static const unsigned int MAX_LOCATOR_SZ
The maximum number of entries in a locator.
Definition: net.h:70
CHash256 hasher
Definition: net.h:736
Stochastical (IP) address manager.
Definition: addrman.h:193
CRollingBloomFilter filterInventoryKnown GUARDED_BY(cs_tx_inventory)
Definition: net.h:979
Definition: net.h:602
bool IsAddrRelayPeer() const
Definition: net.h:958
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:108
int GetMyStartingHeight() const
Definition: net.h:1083
std::chrono::microseconds m_next_local_addr_send GUARDED_BY(cs_sendProcessing)
Definition: net.h:956
ServiceFlags GetLocalServices() const
Definition: net.h:1159
RecursiveMutex cs_tx_inventory
Definition: net.h:978
BlockHash hashContinue
Definition: net.h:947
void InterruptMapPort()
Definition: net.cpp:1735
int64_t nTimeConnected
Definition: net.h:663
Definition: config.h:19
void Release()
Definition: net.h:1107
bool GetLocal(CService &addr, const CNetAddr *paddrPeer=nullptr)
Definition: net.cpp:126
std::condition_variable condMsgProc
Definition: net.h:546
RecursiveMutex cs_vAddedNodes
Definition: net.h:495
void Interrupt(NodeContext &node)
Interrupt threads.
Definition: init.cpp:157
ListenSocket(SOCKET socket_, NetPermissionFlags permissions_)
Definition: net.h:406
std::thread threadOpenAddedConnections
Definition: net.h:554
const uint64_t nLocalExtraEntropy
Definition: net.h:1044
#define LOCK(cs)
Definition: sync.h:230
uint32_t nDataPos
Definition: net.h:748
RecursiveMutex m_addr_fetches_mutex
Definition: net.h:493
bool IsPeerAddrLocalGood(CNode *pnode)
Definition: net.cpp:193
NetEventsInterface * m_msgproc
Definition: net.h:195
bool fInbound
Definition: net.h:668
static const int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
Definition: version.h:14
std::string strAddedNode
Definition: net.h:119
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:179
Fast randomness source.
Definition: random.h:111
Transport protocol agnostic message container.
Definition: net.h:695
const CAddress addrBind
Definition: net.h:856
std::vector< std::string > vSeedNodes
Definition: net.h:202
std::vector< std::string > m_specified_outgoing
Definition: net.h:207
int64_t m_peer_connect_timeout
Definition: net.h:479
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:516
std::thread threadMessageHandler
Definition: net.h:556
static bool HasFlag(const NetPermissionFlags &flags, NetPermissionFlags f)
void ForEachNodeThen(Callable &&pre, CallableAfter &&post)
Definition: net.h:294
uint32_t nHdrPos
Definition: net.h:747
bool IsManualConn() const
Definition: net.h:911
A CService with information about it as peer.
Definition: protocol.h:427
RecursiveMutex cs_main
Global state.
Definition: validation.cpp:90
uint256 hash
Definition: protocol.h:497
RecursiveMutex cs_mapLocalHost
Definition: net.cpp:112
bool fInbound
Definition: net.h:122
int nMaxFeeler
Definition: net.h:192
const Config * config
Definition: net.h:464
int nVersion
Definition: net.h:666
Network
Definition: netaddress.h:19
std::string addrName
Definition: net.h:665
bool ExpectServicesFromConn() const
Definition: net.h:927
std::atomic_bool m_try_another_outbound_peer
flag for deciding to connect to an extra outbound peer, in excess of m_max_outbound_full_relay.
Definition: net.h:562
int64_t NodeId
Definition: net.h:111
Definition: net.h:177
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:97
bool GetNetworkActive() const
Definition: net.h:261
NumConnections
Definition: net.h:179
CClientUIInterface * clientInterface
Definition: net.h:532
NodeId GetId() const
Definition: net.h:1078
int nMaxConnections
Definition: net.h:518
A helper class for interruptible sleeps.
The TransportSerializer prepares messages for the network transport.
Definition: net.h:801
std::string getSubVersionEB(uint64_t MaxBlockSize)
This function convert MaxBlockSize from byte to MB with a decimal precision one digit rounded down E...
Definition: net.cpp:3150
NetPermissionFlags
void ForEachNode(Callable &&func)
Definition: net.h:275
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Definition: net.h:846
void Discover()
Definition: net.cpp:2437
Peer initiated connections.
RecursiveMutex cs_SubVer
cleanSubVer is a sanitized string of the user agent byte array we read from the wire.
Definition: net.h:866
unsigned int SOCKET
Definition: compat.h:44
NetPermissionFlags m_permissions
Definition: net.h:410
const CAddress addr
Definition: net.h:854
bool Complete() const override
Definition: net.h:774
bool IsBlockOnlyConn() const
Definition: net.h:913
CDataStream vRecv
Definition: net.h:746
const int64_t nTimeConnected
Definition: net.h:851
CMessageHeader hdr
Definition: net.h:744
virtual ~TransportSerializer()
Definition: net.h:808
int flags
Definition: bitcoin-tx.cpp:529
uint64_t nMaxOutboundTimeframe
Definition: net.h:199
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
Definition: netaddress.h:30
RecursiveMutex cs_feeFilter
Definition: net.h:992
int64_t m_ping_wait_usec
Definition: net.h:678
256-bit opaque blob.
Definition: uint256.h:120
void RemoveLocal(const CService &addr)
Definition: net.cpp:261
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:203
int nScore
Definition: net.h:640
static const unsigned int MAX_ADDR_TO_SEND
The maximum number of new addresses to accumulate before announcing.
Definition: net.h:72
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
Definition: net.h:50
int nMaxAddnode
Definition: net.h:191
void ForEachNode(Callable &&func) const
Definition: net.h:284
BanMan * m_banman
Pointer to this node&#39;s banman.
Definition: net.h:538
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:109
bool fSendMempool GUARDED_BY(cs_tx_inventory)
Definition: net.h:986
CService resolvedAddress
Definition: net.h:120
std::thread threadOpenConnections
Definition: net.h:555
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
std::array< uint8_t, MESSAGE_START_SIZE > MessageMagic
Definition: protocol.h:49
static const uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:99
ConnectionType
Different types of connections to a peer.
Definition: net.h:145
CSemaphoreGrant grantOutbound
Definition: net.h:885
ServiceFlags nServices
Definition: net.h:659
The TransportDeserializer takes care of holding and deserializing the network receive buffer...
Definition: net.h:720
int64_t nLastSend
Definition: net.h:661
A TxId is the identifier of a transaction.
Definition: txid.h:14
std::map< std::string, uint64_t > mapMsgCmdSize
Definition: net.h:650
const NodeId id
Definition: net.h:1042
Short lived connections used to test address validity.
std::thread threadDNSAddressSeed
Definition: net.h:552
ServiceFlags nLocalServices
Definition: net.h:187
uint64_t nMaxOutboundLimit
Definition: net.h:200
std::vector< std::string > m_added_nodes
Definition: net.h:208
RecursiveMutex cs_vSend
Definition: net.h:835
std::vector< uint8_t > data
Definition: net.h:136
int64_t PoissonNextSend(int64_t now, int average_interval_seconds)
Return a timestamp in the future (in microseconds) for exponentially distributed events.
Definition: net.cpp:3117
uint64_t nSendBytes
Definition: net.h:671
std::vector< ListenSocket > vhListenSocket
Definition: net.h:488
int64_t m_min_ping_usec
Definition: net.h:679
std::unique_ptr< AvalancheState > m_avalanche_state
Definition: net.h:1009
uint32_t type
Definition: protocol.h:496
std::string cleanSubVer
Definition: net.h:667
int64_t m_ping_usec
Definition: net.h:677
void ForEachNodeThen(Callable &&pre, CallableAfter &&post) const
Definition: net.h:305
SipHash-2-4.
Definition: siphash.h:13
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:74
uint64_t nTotalBytesRecv GUARDED_BY(cs_totalBytesRecv)
Definition: net.h:469
static const bool DEFAULT_UPNP
-upnp default
Definition: net.h:90
POD that contains various stats about a node.
Definition: net.h:657
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition: net.h:105
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:103
Amount minFeeFilter GUARDED_BY(cs_feeFilter)
Definition: net.h:994
const uint64_t nLocalHostNonce
Definition: net.h:1043
unsigned int nSendBufferMaxSize
Definition: net.h:197
static const int PING_INTERVAL
Time between pings automatically sent out for latency probing and keepalive (in seconds).
Definition: net.h:56
uint32_t m_mapped_as
Definition: net.h:687
std::string m_command
Definition: net.h:708
void clear()
Definition: streams.h:287
const ServiceFlags nLocalServices
Services offered to this peer.
Definition: net.h:1062
bool IsAddrFetchConn() const
Definition: net.h:919
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
Definition: net.h:48
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we&#39;ll relay everything (blocks, tx, addrs, etc)
Definition: net.h:79
CClientUIInterface uiInterface
uint64_t GetLocalExtraEntropy() const
Definition: net.h:1081
Information about a peer.
Definition: net.h:818
int64_t nLastRecv
Definition: net.h:662
std::thread threadSocketHandler
Definition: net.h:553
Only relay blocks to these automatic outbound connections.
RecursiveMutex cs_totalBytesRecv
Definition: net.h:467
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:267
RecursiveMutex cs_addrLocal
Definition: net.h:1075
bool fDiscover
Definition: net.cpp:109
void SetVersion(int n)
Definition: streams.h:385
Short lived connections used to solicit addrs when starting the node without a populated AddrMan...
void AddAddressKnown(const CAddress &_addr)
Definition: net.h:1109
int Read(const Config &config, const char *pch, uint32_t nBytes) override
Definition: net.h:786
std::vector< uint8_t > GetKey() const
Definition: netaddress.cpp:757
CNode * AddRef()
Definition: net.h:1102
std::unique_ptr< CSemaphore > semAddnode
Definition: net.h:517
void Init(const Options &connOptions)
Definition: net.h:212
CThreadInterrupt interruptNet
Definition: net.h:550
static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections)
bool HasPermission(NetPermissionFlags permission) const
Definition: net.h:870
CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
Definition: net.cpp:173
static const unsigned int MAX_INV_SZ
The maximum number of entries in an &#39;inv&#39; protocol message.
Definition: net.h:65
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
Definition: net.cpp:229
bool IsInboundConn() const
Definition: net.h:923
const uint64_t nSeed1
Definition: net.h:541
void Stop()
Definition: net.h:255
bool m_use_addrman_outgoing
Definition: net.h:206
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:204
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:295
CAddress addr
Definition: net.h:684
CHash256 & Reset()
Definition: hash.h:40
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
Definition: random.h:183
bool GetUseAddrmanOutgoing() const
Definition: net.h:262
RecursiveMutex cs_hSocket
Definition: net.h:836
unsigned short GetListenPort()
Definition: net.cpp:121
const int nMyStartingHeight
Definition: net.h:1064
bool m_use_addrman_outgoing
Definition: net.h:530
bool IsFullOutboundConn() const
Definition: net.h:907
int nBestHeight
Definition: net.h:193
RecursiveMutex cs_totalBytesSent
Definition: net.h:468
bool fRelayTxes
Definition: net.h:660
#define PT_GUARDED_BY(x)
Definition: threadsafety.h:46
bool m_manual_connection
Definition: net.h:669
std::chrono::microseconds m_next_addr_send GUARDED_BY(cs_sendProcessing)
Definition: net.h:954
std::unique_ptr< TxRelay > m_tx_relay
Definition: net.h:1000
Message header.
Definition: protocol.h:37
int64_t nTimeOffset
Definition: net.h:664
int64_t m_peer_connect_timeout
Definition: net.h:201