Bitcoin Core  21.99.0
P2P Digital Currency
net.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #ifndef BITCOIN_NET_H
7 #define BITCOIN_NET_H
8 
9 #include <addrdb.h>
10 #include <addrman.h>
11 #include <amount.h>
12 #include <bloom.h>
13 #include <chainparams.h>
14 #include <compat.h>
15 #include <crypto/siphash.h>
16 #include <hash.h>
17 #include <net_permissions.h>
18 #include <netaddress.h>
19 #include <optional.h>
20 #include <policy/feerate.h>
21 #include <protocol.h>
22 #include <random.h>
23 #include <streams.h>
24 #include <sync.h>
25 #include <threadinterrupt.h>
26 #include <uint256.h>
27 #include <util/check.h>
28 
29 #include <atomic>
30 #include <condition_variable>
31 #include <cstdint>
32 #include <deque>
33 #include <map>
34 #include <memory>
35 #include <thread>
36 #include <vector>
37 
38 class CScheduler;
39 class CNode;
40 class BanMan;
41 struct bilingual_str;
42 
44 static const bool DEFAULT_WHITELISTRELAY = true;
46 static const bool DEFAULT_WHITELISTFORCERELAY = false;
47 
49 static const int TIMEOUT_INTERVAL = 20 * 60;
51 static const int FEELER_INTERVAL = 120;
53 static const int EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL = 300;
55 static constexpr size_t MAX_ADDR_TO_SEND = 1000;
57 static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
59 static const unsigned int MAX_SUBVERSION_LENGTH = 256;
63 static const int MAX_ADDNODE_CONNECTIONS = 8;
65 static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS = 2;
67 static const int MAX_FEELER_CONNECTIONS = 1;
69 static const bool DEFAULT_LISTEN = true;
71 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
73 static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET = 0;
75 static const bool DEFAULT_BLOCKSONLY = false;
77 static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
78 
79 static const bool DEFAULT_FORCEDNSSEED = false;
80 static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
81 static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
82 
83 typedef int64_t NodeId;
84 
86 {
87  std::string strAddedNode;
89  bool fConnected;
90  bool fInbound;
91 };
92 
93 class CNodeStats;
94 class CClientUIInterface;
95 
97 {
98  CSerializedNetMsg() = default;
100  CSerializedNetMsg& operator=(CSerializedNetMsg&&) = default;
101  // No copying, only moves.
102  CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
103  CSerializedNetMsg& operator=(const CSerializedNetMsg&) = delete;
104 
105  std::vector<unsigned char> data;
106  std::string m_type;
107 };
108 
115 enum class ConnectionType {
121  INBOUND,
122 
130 
131 
138  MANUAL,
139 
155  FEELER,
156 
166  BLOCK_RELAY,
167 
174  ADDR_FETCH,
175 };
176 
178 std::string ConnectionTypeAsString(ConnectionType conn_type);
179 void Discover();
180 uint16_t GetListenPort();
181 
182 enum
183 {
184  LOCAL_NONE, // unknown
185  LOCAL_IF, // address a local interface listens on
186  LOCAL_BIND, // address explicit bound to
187  LOCAL_MAPPED, // address reported by UPnP or NAT-PMP
188  LOCAL_MANUAL, // address explicitly specified (-externalip=)
189 
191 };
192 
193 bool IsPeerAddrLocalGood(CNode *pnode);
194 void AdvertiseLocal(CNode *pnode);
195 
200 void SetReachable(enum Network net, bool reachable);
202 bool IsReachable(enum Network net);
204 bool IsReachable(const CNetAddr& addr);
205 
206 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
207 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
208 void RemoveLocal(const CService& addr);
209 bool SeenLocal(const CService& addr);
210 bool IsLocal(const CService& addr);
211 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr);
212 CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices);
213 
214 
215 extern bool fDiscover;
216 extern bool fListen;
217 
219 extern std::string strSubVersion;
220 
222  int nScore;
223  int nPort;
224 };
225 
227 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(cs_mapLocalHost);
228 
229 extern const std::string NET_MESSAGE_COMMAND_OTHER;
230 typedef std::map<std::string, uint64_t> mapMsgCmdSize; //command, total bytes
231 
233 {
234 public:
238  int64_t nLastSend;
239  int64_t nLastRecv;
240  int64_t nLastTXTime;
241  int64_t nLastBlockTime;
242  int64_t nTimeConnected;
243  int64_t nTimeOffset;
244  std::string addrName;
245  int nVersion;
246  std::string cleanSubVer;
247  bool fInbound;
251  uint64_t nSendBytes;
253  uint64_t nRecvBytes;
256  int64_t m_ping_usec;
260  // Our address, as reported by the peer
261  std::string addrLocal;
262  // Address of this peer
264  // Bind address of our side of the connection
266  // Network the peer connected through
268  uint32_t m_mapped_as;
270 };
271 
272 
277 class CNetMessage {
278 public:
280  std::chrono::microseconds m_time{0};
281  uint32_t m_message_size{0};
282  uint32_t m_raw_message_size{0};
283  std::string m_command;
284 
285  CNetMessage(CDataStream&& recv_in) : m_recv(std::move(recv_in)) {}
286 
287  void SetVersion(int nVersionIn)
288  {
289  m_recv.SetVersion(nVersionIn);
290  }
291 };
292 
298 public:
299  // returns true if the current deserialization is complete
300  virtual bool Complete() const = 0;
301  // set the serialization context version
302  virtual void SetVersion(int version) = 0;
304  virtual int Read(Span<const uint8_t>& msg_bytes) = 0;
305  // decomposes a message from the context
306  virtual Optional<CNetMessage> GetMessage(std::chrono::microseconds time, uint32_t& out_err) = 0;
308 };
309 
311 {
312 private:
314  const NodeId m_node_id; // Only for logging
315  mutable CHash256 hasher;
317  bool in_data; // parsing header (false) or data (true)
318  CDataStream hdrbuf; // partially received header
319  CMessageHeader hdr; // complete header
320  CDataStream vRecv; // received message data
321  unsigned int nHdrPos;
322  unsigned int nDataPos;
323 
324  const uint256& GetMessageHash() const;
325  int readHeader(Span<const uint8_t> msg_bytes);
326  int readData(Span<const uint8_t> msg_bytes);
327 
328  void Reset() {
329  vRecv.clear();
330  hdrbuf.clear();
331  hdrbuf.resize(24);
332  in_data = false;
333  nHdrPos = 0;
334  nDataPos = 0;
335  data_hash.SetNull();
336  hasher.Reset();
337  }
338 
339 public:
340  V1TransportDeserializer(const CChainParams& chain_params, const NodeId node_id, int nTypeIn, int nVersionIn)
341  : m_chain_params(chain_params),
342  m_node_id(node_id),
343  hdrbuf(nTypeIn, nVersionIn),
344  vRecv(nTypeIn, nVersionIn)
345  {
346  Reset();
347  }
348 
349  bool Complete() const override
350  {
351  if (!in_data)
352  return false;
353  return (hdr.nMessageSize == nDataPos);
354  }
355  void SetVersion(int nVersionIn) override
356  {
357  hdrbuf.SetVersion(nVersionIn);
358  vRecv.SetVersion(nVersionIn);
359  }
360  int Read(Span<const uint8_t>& msg_bytes) override
361  {
362  int ret = in_data ? readData(msg_bytes) : readHeader(msg_bytes);
363  if (ret < 0) {
364  Reset();
365  } else {
366  msg_bytes = msg_bytes.subspan(ret);
367  }
368  return ret;
369  }
370  Optional<CNetMessage> GetMessage(std::chrono::microseconds time, uint32_t& out_err_raw_size) override;
371 };
372 
376 public:
377  // prepare message for transport (header construction, error-correction computation, payload encryption, etc.)
378  virtual void prepareForTransport(CSerializedNetMsg& msg, std::vector<unsigned char>& header) = 0;
379  virtual ~TransportSerializer() {}
380 };
381 
383 public:
384  void prepareForTransport(CSerializedNetMsg& msg, std::vector<unsigned char>& header) override;
385 };
386 
388 class CNode
389 {
390  friend class CConnman;
391  friend struct ConnmanTestMsg;
392 
393 public:
394  std::unique_ptr<TransportDeserializer> m_deserializer;
395  std::unique_ptr<TransportSerializer> m_serializer;
396 
397  NetPermissionFlags m_permissionFlags{PF_NONE};
398  std::atomic<ServiceFlags> nServices{NODE_NONE};
399  SOCKET hSocket GUARDED_BY(cs_hSocket);
401  size_t nSendSize GUARDED_BY(cs_vSend){0};
403  size_t nSendOffset GUARDED_BY(cs_vSend){0};
404  uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
405  std::deque<std::vector<unsigned char>> vSendMsg GUARDED_BY(cs_vSend);
409 
411  std::list<CNetMessage> vProcessMsg GUARDED_BY(cs_vProcessMsg);
412  size_t nProcessQueueSize{0};
413 
415 
416  uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
417 
418  std::atomic<int64_t> nLastSend{0};
419  std::atomic<int64_t> nLastRecv{0};
420  const int64_t nTimeConnected;
421  std::atomic<int64_t> nTimeOffset{0};
422  // Address of this peer
423  const CAddress addr;
424  // Bind address of our side of the connection
426  std::atomic<int> nVersion{0};
432  std::string cleanSubVer GUARDED_BY(cs_SubVer){};
433  bool m_prefer_evict{false}; // This peer is preferred for eviction.
434  bool HasPermission(NetPermissionFlags permission) const {
435  return NetPermissions::HasFlag(m_permissionFlags, permission);
436  }
437  bool fClient{false}; // set by version message
438  bool m_limited_node{false}; //after BIP159, set by version message
443  std::atomic_bool m_wants_addrv2{false};
444  std::atomic_bool fSuccessfullyConnected{false};
445  // Setting fDisconnect to true will cause the node to be disconnected the
446  // next time DisconnectNodes() runs
447  std::atomic_bool fDisconnect{false};
448  bool fSentAddr{false};
450  std::atomic<int> nRefCount{0};
451 
452  const uint64_t nKeyedNetGroup;
453  std::atomic_bool fPauseRecv{false};
454  std::atomic_bool fPauseSend{false};
455 
457  switch (m_conn_type) {
460  return true;
465  return false;
466  } // no default case, so the compiler can warn about missing cases
467 
468  assert(false);
469  }
470 
471  bool IsFullOutboundConn() const {
472  return m_conn_type == ConnectionType::OUTBOUND_FULL_RELAY;
473  }
474 
475  bool IsManualConn() const {
476  return m_conn_type == ConnectionType::MANUAL;
477  }
478 
479  bool IsBlockOnlyConn() const {
480  return m_conn_type == ConnectionType::BLOCK_RELAY;
481  }
482 
483  bool IsFeelerConn() const {
484  return m_conn_type == ConnectionType::FEELER;
485  }
486 
487  bool IsAddrFetchConn() const {
488  return m_conn_type == ConnectionType::ADDR_FETCH;
489  }
490 
491  bool IsInboundConn() const {
492  return m_conn_type == ConnectionType::INBOUND;
493  }
494 
495  /* Whether we send addr messages over this connection */
496  bool RelayAddrsWithConn() const
497  {
498  // Don't relay addr messages to peers that we connect to as block-relay-only
499  // peers (to prevent adversaries from inferring these links from addr
500  // traffic).
501  return m_conn_type != ConnectionType::BLOCK_RELAY;
502  }
503 
504  bool ExpectServicesFromConn() const {
505  switch (m_conn_type) {
509  return false;
513  return true;
514  } // no default case, so the compiler can warn about missing cases
515 
516  assert(false);
517  }
518 
529  Network ConnectedThroughNetwork() const;
530 
531  // We selected peer as (compact blocks) high-bandwidth peer (BIP152)
532  std::atomic<bool> m_bip152_highbandwidth_to{false};
533  // Peer selected us as (compact blocks) high-bandwidth peer (BIP152)
534  std::atomic<bool> m_bip152_highbandwidth_from{false};
535 
536  // flood relay
537  std::vector<CAddress> vAddrToSend;
538  std::unique_ptr<CRollingBloomFilter> m_addr_known{nullptr};
539  bool fGetAddr{false};
540  std::chrono::microseconds m_next_addr_send GUARDED_BY(cs_sendProcessing){0};
541  std::chrono::microseconds m_next_local_addr_send GUARDED_BY(cs_sendProcessing){0};
542 
543  struct TxRelay {
545  // We use fRelayTxes for two purposes -
546  // a) it allows us to not relay tx invs before receiving the peer's version message
547  // b) the peer may tell us in its version message that we should not relay tx invs
548  // unless it loads a bloom filter.
549  bool fRelayTxes GUARDED_BY(cs_filter){false};
550  std::unique_ptr<CBloomFilter> pfilter PT_GUARDED_BY(cs_filter) GUARDED_BY(cs_filter){nullptr};
551 
552  mutable RecursiveMutex cs_tx_inventory;
553  CRollingBloomFilter filterInventoryKnown GUARDED_BY(cs_tx_inventory){50000, 0.000001};
554  // Set of transaction ids we still have to announce.
555  // They are sorted by the mempool before relay, so the order is not important.
556  std::set<uint256> setInventoryTxToSend;
557  // Used for BIP35 mempool sending
558  bool fSendMempool GUARDED_BY(cs_tx_inventory){false};
559  // Last time a "MEMPOOL" request was serviced.
560  std::atomic<std::chrono::seconds> m_last_mempool_req{0s};
561  std::chrono::microseconds nNextInvSend{0};
562 
564  std::atomic<CAmount> minFeeFilter{0};
565  CAmount lastSentFeeFilter{0};
566  int64_t nextSendTimeFeeFilter{0};
567  };
568 
569  // m_tx_relay == nullptr if we're not relaying transactions with this peer
570  std::unique_ptr<TxRelay> m_tx_relay;
571 
577  std::atomic<int64_t> nLastBlockTime{0};
578 
583  std::atomic<int64_t> nLastTXTime{0};
584 
585  // Ping time measurement:
586  // The pong reply we're expecting, or 0 if no pong expected.
587  std::atomic<uint64_t> nPingNonceSent{0};
589  std::atomic<std::chrono::microseconds> m_ping_start{0us};
590  // Last measured round-trip time.
591  std::atomic<int64_t> nPingUsecTime{0};
592  // Best measured round-trip time.
593  std::atomic<int64_t> nMinPingUsecTime{std::numeric_limits<int64_t>::max()};
594  // Whether a ping is requested.
595  std::atomic<bool> fPingQueued{false};
596 
597  CNode(NodeId id, ServiceFlags nLocalServicesIn, SOCKET hSocketIn, const CAddress& addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const CAddress& addrBindIn, const std::string& addrNameIn, ConnectionType conn_type_in, bool inbound_onion = false);
598  ~CNode();
599  CNode(const CNode&) = delete;
600  CNode& operator=(const CNode&) = delete;
601 
602  NodeId GetId() const {
603  return id;
604  }
605 
606  uint64_t GetLocalNonce() const {
607  return nLocalHostNonce;
608  }
609 
610  int GetRefCount() const
611  {
612  assert(nRefCount >= 0);
613  return nRefCount;
614  }
615 
625  bool ReceiveMsgBytes(Span<const uint8_t> msg_bytes, bool& complete);
626 
627  void SetCommonVersion(int greatest_common_version)
628  {
629  Assume(m_greatest_common_version == INIT_PROTO_VERSION);
630  m_greatest_common_version = greatest_common_version;
631  }
632  int GetCommonVersion() const
633  {
634  return m_greatest_common_version;
635  }
636 
637  CService GetAddrLocal() const;
639  void SetAddrLocal(const CService& addrLocalIn);
640 
642  {
643  nRefCount++;
644  return this;
645  }
646 
647  void Release()
648  {
649  nRefCount--;
650  }
651 
652  void AddAddressKnown(const CAddress& _addr)
653  {
654  assert(m_addr_known);
655  m_addr_known->insert(_addr.GetKey());
656  }
657 
663  bool IsAddrCompatible(const CAddress& addr) const
664  {
665  return m_wants_addrv2 || addr.IsAddrV1Compatible();
666  }
667 
668  void PushAddress(const CAddress& _addr, FastRandomContext &insecure_rand)
669  {
670  // Known checking here is only to save space from duplicates.
671  // SendMessages will filter it again for knowns that were added
672  // after addresses were pushed.
673  assert(m_addr_known);
674  if (_addr.IsValid() && !m_addr_known->contains(_addr.GetKey()) && IsAddrCompatible(_addr)) {
675  if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
676  vAddrToSend[insecure_rand.randrange(vAddrToSend.size())] = _addr;
677  } else {
678  vAddrToSend.push_back(_addr);
679  }
680  }
681  }
682 
683  void AddKnownTx(const uint256& hash)
684  {
685  if (m_tx_relay != nullptr) {
686  LOCK(m_tx_relay->cs_tx_inventory);
687  m_tx_relay->filterInventoryKnown.insert(hash);
688  }
689  }
690 
691  void PushTxInventory(const uint256& hash)
692  {
693  if (m_tx_relay == nullptr) return;
694  LOCK(m_tx_relay->cs_tx_inventory);
695  if (!m_tx_relay->filterInventoryKnown.contains(hash)) {
696  m_tx_relay->setInventoryTxToSend.insert(hash);
697  }
698  }
699 
700  void CloseSocketDisconnect();
701 
702  void copyStats(CNodeStats &stats, const std::vector<bool> &m_asmap);
703 
705  {
706  return nLocalServices;
707  }
708 
709  std::string GetAddrName() const;
711  void MaybeSetAddrName(const std::string& addrNameIn);
712 
713  std::string ConnectionTypeAsString() const { return ::ConnectionTypeAsString(m_conn_type); }
714 
716  bool IsInboundOnion() const { return m_inbound_onion; }
717 
718 private:
719  const NodeId id;
720  const uint64_t nLocalHostNonce;
722  std::atomic<int> m_greatest_common_version{INIT_PROTO_VERSION};
723 
740 
741  std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
742 
744  std::string addrName GUARDED_BY(cs_addrName);
745 
746  // Our address, as reported by the peer
747  CService addrLocal GUARDED_BY(cs_addrLocal);
749 
751  const bool m_inbound_onion{false};
752 
753  mapMsgCmdSize mapSendBytesPerMsgCmd GUARDED_BY(cs_vSend);
754  mapMsgCmdSize mapRecvBytesPerMsgCmd GUARDED_BY(cs_vRecv);
755 };
756 
761 {
762 public:
764  virtual void InitializeNode(CNode* pnode) = 0;
765 
767  virtual void FinalizeNode(const CNode& node, bool& update_connection_time) = 0;
768 
776  virtual bool ProcessMessages(CNode* pnode, std::atomic<bool>& interrupt) = 0;
777 
784  virtual bool SendMessages(CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(pnode->cs_sendProcessing) = 0;
785 
786 
787 protected:
792  ~NetEventsInterface() = default;
793 };
794 
795 class CConnman
796 {
797 public:
798 
801  CONNECTIONS_IN = (1U << 0),
802  CONNECTIONS_OUT = (1U << 1),
804  };
805 
806  struct Options
807  {
808  ServiceFlags nLocalServices = NODE_NONE;
809  int nMaxConnections = 0;
810  int m_max_outbound_full_relay = 0;
811  int m_max_outbound_block_relay = 0;
812  int nMaxAddnode = 0;
813  int nMaxFeeler = 0;
815  NetEventsInterface* m_msgproc = nullptr;
816  BanMan* m_banman = nullptr;
817  unsigned int nSendBufferMaxSize = 0;
818  unsigned int nReceiveFloodSize = 0;
819  uint64_t nMaxOutboundLimit = 0;
820  int64_t m_peer_connect_timeout = DEFAULT_PEER_CONNECT_TIMEOUT;
821  std::vector<std::string> vSeedNodes;
822  std::vector<NetWhitelistPermissions> vWhitelistedRange;
823  std::vector<NetWhitebindPermissions> vWhiteBinds;
824  std::vector<CService> vBinds;
825  std::vector<CService> onion_binds;
826  bool m_use_addrman_outgoing = true;
827  std::vector<std::string> m_specified_outgoing;
828  std::vector<std::string> m_added_nodes;
829  std::vector<bool> m_asmap;
830  };
831 
832  void Init(const Options& connOptions) {
833  nLocalServices = connOptions.nLocalServices;
834  nMaxConnections = connOptions.nMaxConnections;
835  m_max_outbound_full_relay = std::min(connOptions.m_max_outbound_full_relay, connOptions.nMaxConnections);
836  m_max_outbound_block_relay = connOptions.m_max_outbound_block_relay;
837  m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
838  nMaxAddnode = connOptions.nMaxAddnode;
839  nMaxFeeler = connOptions.nMaxFeeler;
840  m_max_outbound = m_max_outbound_full_relay + m_max_outbound_block_relay + nMaxFeeler;
841  clientInterface = connOptions.uiInterface;
842  m_banman = connOptions.m_banman;
843  m_msgproc = connOptions.m_msgproc;
844  nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
845  nReceiveFloodSize = connOptions.nReceiveFloodSize;
846  m_peer_connect_timeout = connOptions.m_peer_connect_timeout;
847  {
848  LOCK(cs_totalBytesSent);
849  nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
850  }
851  vWhitelistedRange = connOptions.vWhitelistedRange;
852  {
853  LOCK(cs_vAddedNodes);
854  vAddedNodes = connOptions.m_added_nodes;
855  }
856  m_onion_binds = connOptions.onion_binds;
857  }
858 
859  CConnman(uint64_t seed0, uint64_t seed1, bool network_active = true);
860  ~CConnman();
861  bool Start(CScheduler& scheduler, const Options& options);
862 
863  void StopThreads();
864  void StopNodes();
865  void Stop()
866  {
867  StopThreads();
868  StopNodes();
869  };
870 
871  void Interrupt();
872  bool GetNetworkActive() const { return fNetworkActive; };
873  bool GetUseAddrmanOutgoing() const { return m_use_addrman_outgoing; };
874  void SetNetworkActive(bool active);
875  void OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant* grantOutbound, const char* strDest, ConnectionType conn_type);
876  bool CheckIncomingNonce(uint64_t nonce);
877 
878  bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
879 
880  void PushMessage(CNode* pnode, CSerializedNetMsg&& msg);
881 
882  using NodeFn = std::function<void(CNode*)>;
883  void ForEachNode(const NodeFn& func)
884  {
885  LOCK(cs_vNodes);
886  for (auto&& node : vNodes) {
887  if (NodeFullyConnected(node))
888  func(node);
889  }
890  };
891 
892  void ForEachNode(const NodeFn& func) const
893  {
894  LOCK(cs_vNodes);
895  for (auto&& node : vNodes) {
896  if (NodeFullyConnected(node))
897  func(node);
898  }
899  };
900 
901  template<typename Callable, typename CallableAfter>
902  void ForEachNodeThen(Callable&& pre, CallableAfter&& post)
903  {
904  LOCK(cs_vNodes);
905  for (auto&& node : vNodes) {
906  if (NodeFullyConnected(node))
907  pre(node);
908  }
909  post();
910  };
911 
912  template<typename Callable, typename CallableAfter>
913  void ForEachNodeThen(Callable&& pre, CallableAfter&& post) const
914  {
915  LOCK(cs_vNodes);
916  for (auto&& node : vNodes) {
917  if (NodeFullyConnected(node))
918  pre(node);
919  }
920  post();
921  };
922 
923  // Addrman functions
924  void SetServices(const CService &addr, ServiceFlags nServices);
925  void MarkAddressGood(const CAddress& addr);
926  bool AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
927  std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct);
934  std::vector<CAddress> GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct);
935 
936  // This allows temporarily exceeding m_max_outbound_full_relay, with the goal of finding
937  // a peer that is better than all our current peers.
938  void SetTryNewOutboundPeer(bool flag);
939  bool GetTryNewOutboundPeer();
940 
942  LogPrint(BCLog::NET, "net: enabling extra block-relay-only peers\n");
943  m_start_extra_block_relay_peers = true;
944  }
945 
946  // Return the number of outbound peers we have in excess of our target (eg,
947  // if we previously called SetTryNewOutboundPeer(true), and have since set
948  // to false, we may have extra peers that we wish to disconnect). This may
949  // return a value less than (num_outbound_connections - num_outbound_slots)
950  // in cases where some outbound connections are not yet fully connected, or
951  // not yet fully disconnected.
952  int GetExtraFullOutboundCount();
953  // Count the number of block-relay-only peers we have over our limit.
954  int GetExtraBlockRelayCount();
955 
956  bool AddNode(const std::string& node);
957  bool RemoveAddedNode(const std::string& node);
958  std::vector<AddedNodeInfo> GetAddedNodeInfo();
959 
971  bool AddConnection(const std::string& address, ConnectionType conn_type);
972 
973  size_t GetNodeCount(NumConnections num);
974  void GetNodeStats(std::vector<CNodeStats>& vstats);
975  bool DisconnectNode(const std::string& node);
976  bool DisconnectNode(const CSubNet& subnet);
977  bool DisconnectNode(const CNetAddr& addr);
978  bool DisconnectNode(NodeId id);
979 
986  ServiceFlags GetLocalServices() const;
987 
988  uint64_t GetMaxOutboundTarget();
989  std::chrono::seconds GetMaxOutboundTimeframe();
990 
994  bool OutboundTargetReached(bool historicalBlockServingLimit);
995 
998  uint64_t GetOutboundTargetBytesLeft();
999 
1002  std::chrono::seconds GetMaxOutboundTimeLeftInCycle();
1003 
1004  uint64_t GetTotalBytesRecv();
1005  uint64_t GetTotalBytesSent();
1006 
1008  CSipHasher GetDeterministicRandomizer(uint64_t id) const;
1009 
1010  unsigned int GetReceiveFloodSize() const;
1011 
1012  void WakeMessageHandler();
1013 
1018  int64_t PoissonNextSendInbound(int64_t now, int average_interval_seconds);
1019 
1020  void SetAsmap(std::vector<bool> asmap) { addrman.m_asmap = std::move(asmap); }
1021 
1022 private:
1023  struct ListenSocket {
1024  public:
1026  inline void AddSocketPermissionFlags(NetPermissionFlags& flags) const { NetPermissions::AddFlag(flags, m_permissions); }
1027  ListenSocket(SOCKET socket_, NetPermissionFlags permissions_) : socket(socket_), m_permissions(permissions_) {}
1028  private:
1030  };
1031 
1032  bool BindListenPort(const CService& bindAddr, bilingual_str& strError, NetPermissionFlags permissions);
1033  bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions);
1034  bool InitBinds(
1035  const std::vector<CService>& binds,
1036  const std::vector<NetWhitebindPermissions>& whiteBinds,
1037  const std::vector<CService>& onion_binds);
1038 
1039  void ThreadOpenAddedConnections();
1040  void AddAddrFetch(const std::string& strDest);
1041  void ProcessAddrFetch();
1042  void ThreadOpenConnections(std::vector<std::string> connect);
1043  void ThreadMessageHandler();
1044  void AcceptConnection(const ListenSocket& hListenSocket);
1045  void DisconnectNodes();
1048  bool InactivityCheck(const CNode& node) const;
1049  bool GenerateSelectSet(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set);
1050  void SocketEvents(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set);
1051  void SocketHandler();
1052  void ThreadSocketHandler();
1053  void ThreadDNSAddressSeed();
1054 
1055  uint64_t CalculateKeyedNetGroup(const CAddress& ad) const;
1056 
1057  CNode* FindNode(const CNetAddr& ip);
1058  CNode* FindNode(const CSubNet& subNet);
1059  CNode* FindNode(const std::string& addrName);
1060  CNode* FindNode(const CService& addr);
1061 
1066  bool AlreadyConnectedToAddress(const CAddress& addr);
1067 
1068  bool AttemptToEvictConnection();
1069  CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type);
1070  void AddWhitelistPermissionFlags(NetPermissionFlags& flags, const CNetAddr &addr) const;
1071 
1072  void DeleteNode(CNode* pnode);
1073 
1074  NodeId GetNewNodeId();
1075 
1076  size_t SocketSendData(CNode& node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend);
1077  void DumpAddresses();
1078 
1079  // Network stats
1080  void RecordBytesRecv(uint64_t bytes);
1081  void RecordBytesSent(uint64_t bytes);
1082 
1086  std::vector<CAddress> GetCurrentBlockRelayOnlyConns() const;
1087 
1088  // Whether the node should be passed out in ForEach* callbacks
1089  static bool NodeFullyConnected(const CNode* pnode);
1090 
1091  // Network usage totals
1094  uint64_t nTotalBytesRecv GUARDED_BY(cs_totalBytesRecv) {0};
1095  uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent) {0};
1096 
1097  // outbound limit & stats
1098  uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent) {0};
1099  std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent) {0};
1100  uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent);
1101 
1102  // P2P timeout in seconds
1104 
1105  // Whitelisted ranges. Any node connecting from these is automatically
1106  // whitelisted (as well as those connecting to whitelisted binds).
1107  std::vector<NetWhitelistPermissions> vWhitelistedRange;
1108 
1109  unsigned int nSendBufferMaxSize{0};
1110  unsigned int nReceiveFloodSize{0};
1111 
1112  std::vector<ListenSocket> vhListenSocket;
1113  std::atomic<bool> fNetworkActive{true};
1114  bool fAddressesInitialized{false};
1116  std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
1118  std::vector<std::string> vAddedNodes GUARDED_BY(cs_vAddedNodes);
1120  std::vector<CNode*> vNodes GUARDED_BY(cs_vNodes);
1121  std::list<CNode*> vNodesDisconnected;
1123  std::atomic<NodeId> nLastNodeId{0};
1124  unsigned int nPrevNodeCount{0};
1125 
1133  std::vector<CAddress> m_addrs_response_cache;
1134  std::chrono::microseconds m_cache_entry_expiration{0};
1135  };
1136 
1151  std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
1152 
1166 
1167  std::unique_ptr<CSemaphore> semOutbound;
1168  std::unique_ptr<CSemaphore> semAddnode;
1170 
1171  // How many full-relay (tx, block, addr) outbound peers we want
1173 
1174  // How many block-relay only outbound peers we want
1175  // We do not relay tx or addr messages with these peers
1177 
1186 
1191  std::vector<CAddress> m_anchors;
1192 
1194  const uint64_t nSeed0, nSeed1;
1195 
1197  bool fMsgProcWake GUARDED_BY(mutexMsgProc);
1198 
1199  std::condition_variable condMsgProc;
1201  std::atomic<bool> flagInterruptMsgProc{false};
1202 
1204 
1206  std::thread threadSocketHandler;
1210 
1215 
1220  std::atomic_bool m_start_extra_block_relay_peers{false};
1221 
1222  std::atomic<int64_t> m_next_send_inv_to_incoming{0};
1223 
1228  std::vector<CService> m_onion_binds;
1229 
1230  friend struct CConnmanTest;
1231  friend struct ConnmanTestMsg;
1232 };
1233 
1235 int64_t PoissonNextSend(int64_t now, int average_interval_seconds);
1236 
1238 inline std::chrono::microseconds PoissonNextSend(std::chrono::microseconds now, std::chrono::seconds average_interval)
1239 {
1240  return std::chrono::microseconds{PoissonNextSend(now.count(), average_interval.count())};
1241 }
1242 
1244 {
1249  int64_t nLastTXTime;
1253  uint64_t nKeyedNetGroup;
1256 };
1257 
1258 [[nodiscard]] Optional<NodeId> SelectNodeToEvict(std::vector<NodeEvictionCandidate>&& vEvictionCandidates);
1259 
1260 #endif // BITCOIN_NET_H
std::vector< CService > vBinds
Definition: net.h:824
int m_max_outbound_full_relay
Definition: net.h:810
uint256 data_hash
Definition: net.h:316
std::vector< CAddress > m_addrs_response_cache
Definition: net.h:1133
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:65
std::string m_type
Definition: net.h:106
uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1095
CONSTEXPR_IF_NOT_DEBUG Span< C > subspan(std::size_t offset) const noexcept
Definition: span.h:189
int nMaxFeeler
Definition: net.h:1179
std::vector< bool > m_asmap
Definition: net.h:829
bool IsReachable(enum Network net)
Definition: net.cpp:276
bool IsInboundOnion() const
Whether this peer is an inbound onion, e.g.
Definition: net.h:716
static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH
Maximum length of incoming protocol messages (no message over 4 MB is currently acceptable).
Definition: net.h:57
int m_max_outbound
Definition: net.h:1180
mapMsgCmdSize mapRecvBytesPerMsgCmd
Definition: net.h:254
const std::chrono::seconds now
uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1098
Definition: banman.h:57
static void AddFlag(NetPermissionFlags &flags, NetPermissionFlags f)
ServiceFlags
nServices flags
Definition: protocol.h:269
void SetNull()
Definition: uint256.h:39
std::unique_ptr< TransportSerializer > m_serializer
Definition: net.h:395
RecursiveMutex cs_vNodes
Definition: net.h:1122
#define LogPrint(category,...)
Definition: logging.h:182
std::string cleanSubVer GUARDED_BY(cs_SubVer)
cleanSubVer is a sanitized string of the user agent byte array we read from the wire.
Definition: net.h:432
int64_t nTimeOffset
Definition: net.h:243
int64_t m_ping_usec
Definition: net.h:256
assert(!tx.IsCoinBase())
bool fListen
Definition: net.cpp:108
int m_max_outbound_block_relay
Definition: net.h:811
We open manual connections to addresses that users explicitly inputted via the addnode RPC...
uint32_t m_mapped_as
Definition: net.h:268
bool fRelayTxes GUARDED_BY(cs_filter)
Definition: net.h:549
int64_t nLastTXTime
Definition: net.h:1249
Bilingual messages:
Definition: translation.h:16
const std::string NET_MESSAGE_COMMAND_OTHER
Definition: net.cpp:99
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(cs_mapLocalHost)
void SetVersion(int nVersionIn) override
Definition: net.h:355
void PushTxInventory(const uint256 &hash)
Definition: net.h:691
BanMan * m_banman
Definition: net.h:816
Mutex mutexMsgProc
Definition: net.h:1200
static const bool DEFAULT_FORCEDNSSEED
Definition: net.h:79
const uint64_t nKeyedNetGroup
Definition: net.h:452
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:288
CDataStream hdrbuf
Definition: net.h:318
bool IsOutboundOrBlockRelayConn() const
Definition: net.h:456
std::vector< unsigned char > data
Definition: net.h:105
unsigned int nDataPos
Definition: net.h:322
const ConnectionType m_conn_type
Definition: net.h:721
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:1107
bool IsFeelerConn() const
Definition: net.h:483
unsigned int nReceiveFloodSize
Definition: net.h:818
uint16_t GetListenPort()
Definition: net.cpp:120
RecursiveMutex cs_filter
Definition: net.h:544
int m_max_outbound_full_relay
Definition: net.h:1172
mapMsgCmdSize mapSendBytesPerMsgCmd
Definition: net.h:252
CClientUIInterface * uiInterface
Definition: net.h:814
void resize(size_type n, value_type c=0)
Definition: streams.h:295
std::vector< CService > m_onion_binds
A vector of -bind=<address>:<port>=onion arguments each of which is an address and port that are desi...
Definition: net.h:1228
void SetAsmap(std::vector< bool > asmap)
Definition: net.h:1020
ServiceFlags nServices
Definition: net.h:236
CDataStream m_recv
received message data
Definition: net.h:279
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:69
CNetMessage(CDataStream &&recv_in)
Definition: net.h:285
int nMaxAddnode
Definition: net.h:1178
RAII-style semaphore lock.
Definition: sync.h:315
void SetCommonVersion(int greatest_common_version)
Definition: net.h:627
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:63
RecursiveMutex cs_vProcessMsg
Definition: net.h:410
std::string cleanSubVer
Definition: net.h:246
Interface for message handling.
Definition: net.h:760
void SetVersion(int nVersionIn)
Definition: net.h:287
RecursiveMutex cs_addrName
Definition: net.h:743
RollingBloomFilter is a probabilistic "keep track of most recently inserted" set. ...
Definition: bloom.h:110
NetEventsInterface * m_msgproc
Definition: net.h:1183
CAmount minFeeFilter
Definition: net.h:259
int nMaxConnections
Definition: net.h:809
int64_t nTimeConnected
Definition: net.h:242
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:52
void ForEachNode(const NodeFn &func) const
Definition: net.h:892
void AdvertiseLocal(CNode *pnode)
Definition: net.cpp:203
int m_max_outbound_block_relay
Definition: net.h:1176
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:202
uint32_t nMessageSize
Definition: protocol.h:54
A hasher class for Bitcoin&#39;s 256-bit hash (double SHA-256).
Definition: hash.h:24
uint64_t GetLocalNonce() const
Definition: net.h:606
std::unique_ptr< TransportDeserializer > m_deserializer
Definition: net.h:394
std::vector< CAddress > vAddrToSend
Definition: net.h:537
void PushAddress(const CAddress &_addr, FastRandomContext &insecure_rand)
Definition: net.h:668
static const int FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes or 120 seconds.
Definition: net.h:51
ConnectionType m_conn_type
Definition: net.h:269
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Definition: net.h:404
static const int TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:49
Definition: net.h:190
Signals for UI communication.
Definition: ui_interface.h:24
std::list< CNetMessage > vRecvMsg
Definition: net.h:741
const NodeId m_node_id
Definition: net.h:314
CAddrMan addrman
Definition: net.h:1115
std::map< uint64_t, CachedAddrResponse > m_addr_response_caches
Addr responses stored in different caches per (network, local socket) prevent cross-network node iden...
Definition: net.h:1151
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition: net.h:67
bool fConnected
Definition: net.h:89
virtual ~TransportDeserializer()
Definition: net.h:307
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition: net.h:1026
int GetRefCount() const
Definition: net.h:610
RecursiveMutex cs_sendProcessing
Definition: net.h:414
ServiceFlags nLocalServices
Services this instance offers.
Definition: net.h:1165
bool IsValid() const
Definition: netaddress.cpp:432
Stochastical (IP) address manager.
Definition: addrman.h:172
CHash256 hasher
Definition: net.h:315
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:80
int64_t nLastTXTime
Definition: net.h:240
std::chrono::microseconds m_next_local_addr_send GUARDED_BY(cs_sendProcessing)
Definition: net.h:541
ServiceFlags GetLocalServices() const
Definition: net.h:704
int nVersion
Definition: net.h:245
int64_t m_ping_wait_usec
Definition: net.h:257
void Release()
Definition: net.h:647
bool GetLocal(CService &addr, const CNetAddr *paddrPeer=nullptr)
Definition: net.cpp:126
std::condition_variable condMsgProc
Definition: net.h:1199
RecursiveMutex cs_vAddedNodes
Definition: net.h:1119
void Interrupt(NodeContext &node)
Interrupt threads.
Definition: init.cpp:160
ListenSocket(SOCKET socket_, NetPermissionFlags permissions_)
Definition: net.h:1027
int m_starting_height
Definition: net.h:250
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
Definition: net.cpp:501
int Read(Span< const uint8_t > &msg_bytes) override
read and deserialize data, advances msg_bytes data pointer
Definition: net.h:360
std::thread threadOpenAddedConnections
Definition: net.h:1207
#define LOCK(cs)
Definition: sync.h:232
Mutex cs_hSocket
Definition: net.h:407
void StartExtraBlockRelayPeers()
Definition: net.h:941
RecursiveMutex m_addr_fetches_mutex
Definition: net.h:1117
bool IsPeerAddrLocalGood(CNode *pnode)
Definition: net.cpp:195
std::function< void(CNode *)> NodeFn
Definition: net.h:882
NetEventsInterface * m_msgproc
Definition: net.h:815
static const int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
Definition: version.h:15
std::string strAddedNode
Definition: net.h:87
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:523
Fast randomness source.
Definition: random.h:119
Transport protocol agnostic message container.
Definition: net.h:277
const CAddress addrBind
Definition: net.h:425
std::vector< std::string > vSeedNodes
Definition: net.h:821
std::vector< std::string > m_specified_outgoing
Definition: net.h:827
bool m_bip152_highbandwidth_from
Definition: net.h:249
int64_t m_peer_connect_timeout
Definition: net.h:1103
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:1167
std::thread threadMessageHandler
Definition: net.h:1209
bool RelayAddrsWithConn() const
Definition: net.h:496
static bool HasFlag(const NetPermissionFlags &flags, NetPermissionFlags f)
void ForEachNodeThen(Callable &&pre, CallableAfter &&post)
Definition: net.h:902
Network m_network
Definition: net.h:267
bool fInbound
Definition: net.h:247
bool IsManualConn() const
Definition: net.h:475
A CService with information about it as peer.
Definition: protocol.h:356
uint64_t nRecvBytes
Definition: net.h:253
std::vector< unsigned char > GetKey() const
Definition: netaddress.cpp:964
RecursiveMutex cs_mapLocalHost
Definition: net.cpp:109
bool fInbound
Definition: net.h:90
std::string addrName
Definition: net.h:244
int nMaxFeeler
Definition: net.h:813
Network
A network type.
Definition: netaddress.h:43
bool m_bip152_highbandwidth_to
Definition: net.h:248
bool ExpectServicesFromConn() const
Definition: net.h:504
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 This t...
Definition: net.h:1214
int64_t NodeId
Definition: net.h:83
Definition: net.h:795
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:71
bool GetNetworkActive() const
Definition: net.h:872
NumConnections
Definition: net.h:799
CClientUIInterface * clientInterface
Definition: net.h:1182
NodeId GetId() const
Definition: net.h:602
uint64_t nSendBytes
Definition: net.h:251
std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1099
int nMaxConnections
Definition: net.h:1169
The TransportSerializer prepares messages for the network transport.
Definition: net.h:375
NetPermissionFlags
#define Assume(val)
Assume is the identity function.
Definition: check.h:72
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Definition: net.h:416
void Discover()
Definition: net.cpp:2239
Inbound connections are those initiated by a peer.
RecursiveMutex cs_SubVer
Definition: net.h:427
unsigned int SOCKET
Definition: compat.h:41
NetPermissionFlags m_permissions
Definition: net.h:1029
const CAddress addr
Definition: net.h:423
bool Complete() const override
Definition: net.h:349
bool IsBlockOnlyConn() const
Definition: net.h:479
CDataStream vRecv
Definition: net.h:320
const int64_t nTimeConnected
Definition: net.h:420
CMessageHeader hdr
Definition: net.h:319
virtual ~TransportSerializer()
Definition: net.h:379
int flags
Definition: bitcoin-tx.cpp:512
static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:73
Network address.
Definition: netaddress.h:119
std::list< CNode * > vNodesDisconnected
Definition: net.h:1121
256-bit opaque blob.
Definition: uint256.h:124
void RemoveLocal(const CService &addr)
Definition: net.cpp:261
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:822
std::vector< CService > onion_binds
Definition: net.h:825
int nScore
Definition: net.h:222
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
Definition: net.h:46
int nMaxAddnode
Definition: net.h:812
BanMan * m_banman
Pointer to this node&#39;s banman.
Definition: net.h:1185
void AddKnownTx(const uint256 &hash)
Definition: net.h:683
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:81
CAddress addrBind
Definition: net.h:265
bool fSendMempool GUARDED_BY(cs_tx_inventory)
Definition: net.h:558
Mutex cs_vRecv
Definition: net.h:408
CService resolvedAddress
Definition: net.h:88
std::thread threadOpenConnections
Definition: net.h:1208
ConnectionType
Different types of connections to a peer.
Definition: net.h:115
CSemaphoreGrant grantOutbound
Definition: net.h:449
The TransportDeserializer takes care of holding and deserializing the network receive buffer...
Definition: net.h:297
const CChainParams & m_chain_params
Definition: net.h:313
std::map< std::string, uint64_t > mapMsgCmdSize
Definition: net.h:230
const NodeId id
Definition: net.h:719
Feeler connections are short-lived connections made to check that a node is alive.
std::string addrLocal
Definition: net.h:261
static constexpr size_t MAX_ADDR_TO_SEND
The maximum number of addresses from our addrman to return in response to a getaddr message...
Definition: net.h:55
std::thread threadDNSAddressSeed
Definition: net.h:1205
ServiceFlags nLocalServices
Definition: net.h:808
int64_t nTimeConnected
Definition: net.h:1246
uint64_t nMaxOutboundLimit
Definition: net.h:819
std::vector< std::string > m_added_nodes
Definition: net.h:828
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:2930
std::vector< ListenSocket > vhListenSocket
Definition: net.h:1112
Mutex cs_vSend
Definition: net.h:406
size_t nSendOffset GUARDED_BY(cs_vSend)
Offset inside the first vSendMsg already sent.
Definition: net.h:403
void ForEachNodeThen(Callable &&pre, CallableAfter &&post) const
Definition: net.h:913
SipHash-2-4.
Definition: siphash.h:13
These are the default connections that we use to connect with the network.
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:59
uint64_t nTotalBytesRecv GUARDED_BY(cs_totalBytesRecv)
Definition: net.h:1094
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition: net.h:77
std::string ConnectionTypeAsString() const
Definition: net.h:713
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:75
int64_t nMinPingUsecTime
Definition: net.h:1247
const uint64_t nLocalHostNonce
Definition: net.h:720
unsigned int nSendBufferMaxSize
Definition: net.h:817
std::string m_command
Definition: net.h:283
void clear()
Definition: streams.h:299
const ServiceFlags nLocalServices
Services offered to this peer.
Definition: net.h:739
bool IsAddrFetchConn() const
Definition: net.h:487
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
Definition: net.h:44
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:61
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:92
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:112
CClientUIInterface uiInterface
Definition: net.h:185
Information about a peer.
Definition: net.h:388
static const int EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL
Run the extra block-relay-only connection loop once every 5 minutes.
Definition: net.h:53
void ForEachNode(const NodeFn &func)
Definition: net.h:883
std::thread threadSocketHandler
Definition: net.h:1206
Simple class for background tasks that should be run periodically or once "after a while"...
Definition: scheduler.h:32
We use block-relay-only connections to help prevent against partition attacks.
RecursiveMutex cs_totalBytesRecv
Definition: net.h:1092
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:268
NetPermissionFlags m_permissionFlags
Definition: net.h:255
uint64_t nKeyedNetGroup
Definition: net.h:1253
V1TransportDeserializer(const CChainParams &chain_params, const NodeId node_id, int nTypeIn, int nVersionIn)
Definition: net.h:340
RecursiveMutex cs_addrLocal
Definition: net.h:748
bool fDiscover
Definition: net.cpp:107
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
Definition: net.h:1191
void SetVersion(int n)
Definition: streams.h:395
AddrFetch connections are short lived connections used to solicit addresses from peers.
void AddAddressKnown(const CAddress &_addr)
Definition: net.h:652
int GetCommonVersion() const
Definition: net.h:632
CNode * AddRef()
Definition: net.h:641
std::unique_ptr< CSemaphore > semAddnode
Definition: net.h:1168
bool IsAddrV1Compatible() const
Check if the current object can be serialized in pre-ADDRv2/BIP155 format.
Definition: netaddress.cpp:486
void Init(const Options &connOptions)
Definition: net.h:832
CThreadInterrupt interruptNet
Definition: net.h:1203
unsigned int nHdrPos
Definition: net.h:321
static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections)
bool HasPermission(NetPermissionFlags permission) const
Definition: net.h:434
CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
Definition: net.cpp:175
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
Definition: net.cpp:230
bool IsInboundConn() const
Definition: net.h:491
const uint64_t nSeed1
Definition: net.h:1194
void Stop()
Definition: net.h:865
bool m_use_addrman_outgoing
Definition: net.h:826
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:823
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:301
size_t nSendSize GUARDED_BY(cs_vSend)
Total size of all vSendMsg entries.
Definition: net.h:401
CHash256 & Reset()
Definition: hash.h:42
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
Definition: random.h:190
bool GetUseAddrmanOutgoing() const
Definition: net.h:873
bool fRelayTxes
Definition: net.h:237
std::optional< T > Optional
Substitute for C++17 std::optional DEPRECATED use std::optional in new code.
Definition: optional.h:14
int64_t nLastSend
Definition: net.h:238
int64_t nLastBlockTime
Definition: net.h:1248
int64_t m_min_ping_usec
Definition: net.h:258
bool m_use_addrman_outgoing
Definition: net.h:1181
Cache responses to addr requests to minimize privacy leak.
Definition: net.h:1132
bool IsFullOutboundConn() const
Definition: net.h:471
bool IsAddrCompatible(const CAddress &addr) const
Whether the peer supports the address.
Definition: net.h:663
NodeId nodeid
Definition: net.h:235
int64_t nLastRecv
Definition: net.h:239
RecursiveMutex cs_totalBytesSent
Definition: net.h:1093
bool fRelevantServices
Definition: net.h:1250
std::chrono::microseconds m_next_addr_send GUARDED_BY(cs_sendProcessing)
Definition: net.h:540
std::unique_ptr< TxRelay > m_tx_relay
Definition: net.h:570
CAddress addr
Definition: net.h:263
Message header.
Definition: protocol.h:28
int64_t nLastBlockTime
Definition: net.h:241
int64_t m_peer_connect_timeout
Definition: net.h:820
std::unique_ptr< CBloomFilter > pfilter PT_GUARDED_BY(cs_filter) GUARDED_BY(cs_filter)
Definition: net.h:550
Optional< NodeId > SelectNodeToEvict(std::vector< NodeEvictionCandidate > &&vEvictionCandidates)
Definition: net.cpp:889