31 #include <condition_variable> 38 #include <arpa/inet.h> 67 "Max protocol message length must be greater than largest " 68 "possible INV message");
90 static const bool DEFAULT_UPNP =
false;
180 CONNECTIONS_NONE = 0,
181 CONNECTIONS_IN = (1U << 0),
182 CONNECTIONS_OUT = (1U << 1),
183 CONNECTIONS_ALL = (CONNECTIONS_IN | CONNECTIONS_OUT),
188 int nMaxConnections = 0;
189 int m_max_outbound_full_relay = 0;
190 int m_max_outbound_block_relay = 0;
197 unsigned int nSendBufferMaxSize = 0;
198 unsigned int nReceiveFloodSize = 0;
199 uint64_t nMaxOutboundTimeframe = 0;
200 uint64_t nMaxOutboundLimit = 0;
206 bool m_use_addrman_outgoing =
true;
222 m_max_outbound_full_relay =
226 m_max_outbound = m_max_outbound_full_relay +
227 m_max_outbound_block_relay + nMaxFeeler;
237 LOCK(cs_totalBytesSent);
243 LOCK(cs_vAddedNodes);
263 void SetNetworkActive(
bool active);
265 OpenNetworkConnection(
const CAddress &addrConnect,
bool fCountFailure,
267 const char *strDest =
nullptr,
269 bool CheckIncomingNonce(uint64_t nonce);
271 bool ForNode(NodeId
id, std::function<
bool(
CNode *pnode)> func);
277 for (
auto &&node : vNodes) {
278 if (NodeFullyConnected(node)) {
284 template <
typename Callable>
void ForEachNode(Callable &&func)
const {
286 for (
auto &&node : vNodes) {
287 if (NodeFullyConnected(node)) {
293 template <
typename Callable,
typename CallableAfter>
296 for (
auto &&node : vNodes) {
297 if (NodeFullyConnected(node)) {
304 template <
typename Callable,
typename CallableAfter>
307 for (
auto &&node : vNodes) {
308 if (NodeFullyConnected(node)) {
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();
324 void SetTryNewOutboundPeer(
bool flag);
325 bool GetTryNewOutboundPeer();
333 int GetExtraOutboundCount();
335 bool AddNode(
const std::string &node);
336 bool RemoveAddedNode(
const std::string &node);
337 std::vector<AddedNodeInfo> GetAddedNodeInfo();
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);
355 void SetMaxOutboundTarget(uint64_t limit);
356 uint64_t GetMaxOutboundTarget();
359 void SetMaxOutboundTimeframe(uint64_t timeframe);
360 uint64_t GetMaxOutboundTimeframe();
365 bool OutboundTargetReached(
bool historicalBlockServingLimit);
369 uint64_t GetOutboundTargetBytesLeft();
373 uint64_t GetMaxOutboundTimeLeftInCycle();
375 uint64_t GetTotalBytesRecv();
376 uint64_t GetTotalBytesSent();
378 void SetBestHeight(
int height);
379 int GetBestHeight()
const;
382 CSipHasher GetDeterministicRandomizer(uint64_t
id)
const;
384 unsigned int GetReceiveFloodSize()
const;
386 void WakeMessageHandler();
393 int64_t PoissonNextSendInbound(int64_t now,
int average_interval_seconds);
396 addrman.m_asmap = std::move(asmap);
407 : socket(socket_), m_permissions(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();
437 uint64_t CalculateKeyedNetGroup(
const CAddress &ad)
const;
441 CNode *FindNode(
const std::string &addrName);
444 bool AttemptToEvictConnection();
445 CNode *ConnectNode(
CAddress addrConnect,
const char *pszDest,
450 void DeleteNode(
CNode *pnode);
452 NodeId GetNewNodeId();
454 size_t SocketSendData(
CNode *pnode)
const;
455 void DumpAddresses();
458 void RecordBytesRecv(uint64_t bytes);
459 void RecordBytesSent(uint64_t bytes);
462 static bool NodeFullyConnected(
const CNode *pnode);
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);
485 unsigned int nSendBufferMaxSize{0};
486 unsigned int nReceiveFloodSize{0};
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);
499 std::atomic<NodeId> nLastNodeId{0};
500 unsigned int nPrevNodeCount{0};
548 std::atomic<bool> flagInterruptMsgProc{
false};
564 std::atomic<int64_t> m_next_send_inv_to_incoming{0};
566 friend struct ::CConnmanTest;
567 friend struct ConnmanTestMsg;
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;
645 extern std::map<CNetAddr, LocalServiceInfo>
701 bool m_valid_netmagic =
false;
702 bool m_valid_header =
false;
703 bool m_valid_checksum =
false;
705 uint32_t m_message_size = 0;
707 uint32_t m_raw_message_size = 0;
723 virtual bool Complete()
const = 0;
725 virtual void SetVersion(
int version) = 0;
727 virtual int Read(
const Config &config,
const char *data,
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);
769 : hdrbuf(nTypeIn, nVersionIn), hdr(pchMessageStartIn),
770 vRecv(nTypeIn, nVersionIn) {
786 int Read(
const Config &config,
const char *pch, uint32_t nBytes)
override {
788 in_data ? readData(pch, nBytes) : readHeader(config, pch, nBytes);
805 virtual void prepareForTransport(
const Config &config,
807 std::vector<uint8_t> &header) = 0;
814 std::vector<uint8_t> &header)
override;
820 friend struct ConnmanTestMsg;
832 size_t nSendOffset{0};
834 std::deque<std::vector<uint8_t>> vSendMsg
GUARDED_BY(cs_vSend);
840 std::list<CNetMessage> vProcessMsg
GUARDED_BY(cs_vProcessMsg);
841 size_t nProcessQueueSize{0};
849 std::atomic<int64_t> nLastSend{0};
850 std::atomic<int64_t> nLastRecv{0};
852 std::atomic<int64_t> nTimeOffset{0};
857 std::atomic<int> nVersion{0};
859 uint64_t nRemoteHostNonce{0};
861 uint64_t nRemoteExtraEntropy{0};
869 bool m_prefer_evict{
false};
875 bool m_legacyWhitelisted{
false};
879 bool m_limited_node{
false};
880 std::atomic_bool fSuccessfullyConnected{
false};
883 std::atomic_bool fDisconnect{
false};
884 bool fSentAddr{
false};
886 std::atomic<int> nRefCount{0};
889 std::atomic_bool fPauseRecv{
false};
890 std::atomic_bool fPauseSend{
false};
893 switch (m_conn_type) {
928 switch (m_conn_type) {
944 mapMsgCmdSize mapRecvBytesPerMsgCmd
GUARDED_BY(cs_vRecv);
948 std::atomic<int> nStartingHeight{-1};
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
963 std::vector<BlockHash> vInventoryBlockToSend
GUARDED_BY(cs_inventory);
967 TxRelay() { pfilter = std::make_unique<CBloomFilter>(); }
975 std::unique_ptr<CBloomFilter> pfilter
PT_GUARDED_BY(cs_filter)
984 std::set<TxId> setInventoryTxToSend;
988 std::atomic<std::chrono::seconds> m_last_mempool_req{
989 std::chrono::seconds{0}};
990 std::chrono::microseconds nNextInvSend{0};
996 int64_t nextSendTimeFeeFilter{0};
1012 std::vector<BlockHash> vBlockHashesToAnnounce
GUARDED_BY(cs_inventory);
1015 std::atomic<int64_t> nLastBlockTime{0};
1016 std::atomic<int64_t> nLastTXTime{0};
1020 std::atomic<uint64_t> nPingNonceSent{0};
1022 std::atomic<int64_t> nPingUsecStart{0};
1024 std::atomic<int64_t> nPingUsecTime{0};
1026 std::atomic<int64_t> nMinPingUsecTime{std::numeric_limits<int64_t>::max()};
1028 std::atomic<bool> fPingQueued{
false};
1033 SOCKET hSocketIn,
const CAddress &addrIn, uint64_t nKeyedNetGroupIn,
1034 uint64_t nLocalHostNonceIn, uint64_t nLocalExtraEntropyIn,
1035 const CAddress &addrBindIn,
const std::string &addrNameIn,
1065 int nSendVersion{0};
1071 std::string addrName
GUARDED_BY(cs_addrName);
1086 assert(nRefCount >= 0);
1090 bool ReceiveMsgBytes(
const Config &config,
const char *pch, uint32_t nBytes,
1095 void SetSendVersion(
int nVersionIn);
1096 int GetSendVersion()
const;
1100 void SetAddrLocal(
const CService &addrLocalIn);
1110 assert(m_addr_known);
1111 m_addr_known->insert(_addr.
GetKey());
1118 assert(m_addr_known);
1119 if (_addr.
IsValid() && !m_addr_known->contains(_addr.
GetKey())) {
1121 vAddrToSend[insecure_rand.
randrange(vAddrToSend.size())] =
1124 vAddrToSend.push_back(_addr);
1130 if (m_tx_relay !=
nullptr) {
1131 LOCK(m_tx_relay->cs_tx_inventory);
1132 m_tx_relay->filterInventoryKnown.insert(txid);
1137 if (inv.
type ==
MSG_TX && m_tx_relay !=
nullptr) {
1139 LOCK(m_tx_relay->cs_tx_inventory);
1140 if (!m_tx_relay->filterInventoryKnown.contains(txid)) {
1141 m_tx_relay->setInventoryTxToSend.insert(txid);
1146 vInventoryBlockToSend.push_back(hash);
1152 vBlockHashesToAnnounce.push_back(hash);
1155 void CloseSocketDisconnect();
1157 void copyStats(
CNodeStats &stats,
const std::vector<bool> &m_asmap);
1161 std::string GetAddrName()
const;
1163 void MaybeSetAddrName(
const std::string &addrNameIn);
1173 inline std::chrono::microseconds
1175 std::chrono::seconds average_interval) {
1176 return std::chrono::microseconds{
1183 #endif // BITCOIN_NET_H std::vector< CService > vBinds
int m_max_outbound_full_relay
uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent)
static constexpr NodeId NO_NODE
Special NodeId that represent no node.
std::vector< bool > m_asmap
bool IsReachable(enum Network net)
static constexpr Amount zero()
static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH
Maximum length of incoming protocol messages (Currently 2MB).
static void AddFlag(NetPermissionFlags &flags, NetPermissionFlags f)
void AddKnownTx(const TxId &txid)
ServiceFlags
nServices flags.
static const uint64_t MAX_UPLOAD_TIMEFRAME
The default timeframe for -maxuploadtarget.
std::unique_ptr< TransportSerializer > m_serializer
std::string cleanSubVer GUARDED_BY(cs_SubVer)
int m_max_outbound_block_relay
Connections to addresses added via addnode or the connect command line argument.
std::atomic< int > nBestHeight
bool fRelayTxes GUARDED_BY(cs_filter)
const std::string NET_MESSAGE_COMMAND_OTHER
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(cs_mapLocalHost)
void SetVersion(int nVersionIn) override
void PushBlockHash(const BlockHash &hash)
static const bool DEFAULT_FORCEDNSSEED
const uint64_t nKeyedNetGroup
bool SeenLocal(const CService &addr)
vote for a local address
int GetRecvVersion() const
mapMsgCmdSize mapSendBytesPerMsgCmd
bool IsOutboundOrBlockRelayConn() const
Inv(ventory) message data.
std::list< CNode * > vNodesDisconnected
RecursiveMutex cs_inventory
const ConnectionType m_conn_type
Full relay connections (blocks, addrs, txns) made automatically.
std::vector< NetWhitelistPermissions > vWhitelistedRange
bool IsFeelerConn() const
unsigned int nReceiveFloodSize
int m_max_outbound_full_relay
CClientUIInterface * uiInterface
void resize(size_type n, value_type c=0)
void SetAsmap(std::vector< bool > asmap)
static const bool DEFAULT_LISTEN
-listen default
CNetMessage(CDataStream &&recv_in)
RAII-style semaphore lock.
std::set< TxId > orphan_work_set
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
RecursiveMutex cs_vProcessMsg
Interface for message handling.
void SetVersion(int nVersionIn)
RecursiveMutex cs_addrName
RollingBloomFilter is a probabilistic "keep track of most recently inserted" set. ...
NetEventsInterface * m_msgproc
V1TransportDeserializer(const CMessageHeader::MessageMagic &pchMessageStartIn, int nTypeIn, int nVersionIn)
void AdvertiseLocal(CNode *pnode)
int m_max_outbound_block_relay
Double ended buffer combining vector and stream-like interfaces.
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
uint64_t GetLocalNonce() const
std::unique_ptr< TransportDeserializer > m_deserializer
std::vector< CAddress > vAddrToSend
void PushAddress(const CAddress &_addr, FastRandomContext &insecure_rand)
NetPermissionFlags m_permissionFlags
static const int FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes or 120 seconds.
uint64_t nSendBytes GUARDED_BY(cs_vSend)
static const int TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
void SetRecvVersion(int nVersionIn)
Signals for UI communication.
std::string userAgent(const Config &config)
std::list< CNetMessage > vRecvMsg
void PushInventory(const CInv &inv)
mapMsgCmdSize mapSendBytesPerMsgCmd
static const int MAX_BLOCKS_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
std::deque< CInv > vRecvGetData
avalanche::Delegation delegation
virtual ~TransportDeserializer()
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
RecursiveMutex cs_sendProcessing
ServiceFlags nLocalServices
Services this instance offers.
mapMsgCmdSize mapRecvBytesPerMsgCmd
static const unsigned int MAX_LOCATOR_SZ
The maximum number of entries in a locator.
Stochastical (IP) address manager.
CRollingBloomFilter filterInventoryKnown GUARDED_BY(cs_tx_inventory)
bool IsAddrRelayPeer() const
static const size_t DEFAULT_MAXRECEIVEBUFFER
int GetMyStartingHeight() const
std::chrono::microseconds m_next_local_addr_send GUARDED_BY(cs_sendProcessing)
ServiceFlags GetLocalServices() const
RecursiveMutex cs_tx_inventory
bool GetLocal(CService &addr, const CNetAddr *paddrPeer=nullptr)
std::condition_variable condMsgProc
RecursiveMutex cs_vAddedNodes
void Interrupt(NodeContext &node)
Interrupt threads.
ListenSocket(SOCKET socket_, NetPermissionFlags permissions_)
std::thread threadOpenAddedConnections
const uint64_t nLocalExtraEntropy
RecursiveMutex m_addr_fetches_mutex
bool IsPeerAddrLocalGood(CNode *pnode)
NetEventsInterface * m_msgproc
static const int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
A combination of a network address (CNetAddr) and a (TCP) port.
Transport protocol agnostic message container.
std::vector< std::string > vSeedNodes
std::vector< std::string > m_specified_outgoing
int64_t m_peer_connect_timeout
std::unique_ptr< CSemaphore > semOutbound
std::thread threadMessageHandler
static bool HasFlag(const NetPermissionFlags &flags, NetPermissionFlags f)
void ForEachNodeThen(Callable &&pre, CallableAfter &&post)
bool IsManualConn() const
A CService with information about it as peer.
RecursiveMutex cs_main
Global state.
RecursiveMutex cs_mapLocalHost
bool ExpectServicesFromConn() const
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.
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
bool GetNetworkActive() const
CClientUIInterface * clientInterface
A helper class for interruptible sleeps.
The TransportSerializer prepares messages for the network transport.
std::string getSubVersionEB(uint64_t MaxBlockSize)
This function convert MaxBlockSize from byte to MB with a decimal precision one digit rounded down E...
void ForEachNode(Callable &&func)
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Peer initiated connections.
RecursiveMutex cs_SubVer
cleanSubVer is a sanitized string of the user agent byte array we read from the wire.
NetPermissionFlags m_permissions
bool Complete() const override
bool IsBlockOnlyConn() const
const int64_t nTimeConnected
virtual ~TransportSerializer()
uint64_t nMaxOutboundTimeframe
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
RecursiveMutex cs_feeFilter
void RemoveLocal(const CService &addr)
std::vector< NetWhitelistPermissions > vWhitelistedRange
static const unsigned int MAX_ADDR_TO_SEND
The maximum number of new addresses to accumulate before announcing.
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
void ForEachNode(Callable &&func) const
BanMan * m_banman
Pointer to this node's banman.
static const size_t DEFAULT_MAXSENDBUFFER
bool fSendMempool GUARDED_BY(cs_tx_inventory)
std::thread threadOpenConnections
A BlockHash is a unqiue identifier for a block.
static const uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
ConnectionType
Different types of connections to a peer.
CSemaphoreGrant grantOutbound
The TransportDeserializer takes care of holding and deserializing the network receive buffer...
A TxId is the identifier of a transaction.
std::map< std::string, uint64_t > mapMsgCmdSize
Short lived connections used to test address validity.
std::thread threadDNSAddressSeed
ServiceFlags nLocalServices
uint64_t nMaxOutboundLimit
std::vector< std::string > m_added_nodes
std::vector< uint8_t > data
int64_t PoissonNextSend(int64_t now, int average_interval_seconds)
Return a timestamp in the future (in microseconds) for exponentially distributed events.
std::vector< ListenSocket > vhListenSocket
std::unique_ptr< AvalancheState > m_avalanche_state
void ForEachNodeThen(Callable &&pre, CallableAfter &&post) const
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
uint64_t nTotalBytesRecv GUARDED_BY(cs_totalBytesRecv)
static const bool DEFAULT_UPNP
-upnp default
POD that contains various stats about a node.
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Amount minFeeFilter GUARDED_BY(cs_feeFilter)
const uint64_t nLocalHostNonce
unsigned int nSendBufferMaxSize
static const int PING_INTERVAL
Time between pings automatically sent out for latency probing and keepalive (in seconds).
const ServiceFlags nLocalServices
Services offered to this peer.
bool IsAddrFetchConn() const
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks, tx, addrs, etc)
CClientUIInterface uiInterface
uint64_t GetLocalExtraEntropy() const
Information about a peer.
std::thread threadSocketHandler
Only relay blocks to these automatic outbound connections.
RecursiveMutex cs_totalBytesRecv
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
RecursiveMutex cs_addrLocal
Short lived connections used to solicit addrs when starting the node without a populated AddrMan...
void AddAddressKnown(const CAddress &_addr)
int Read(const Config &config, const char *pch, uint32_t nBytes) override
std::vector< uint8_t > GetKey() const
std::unique_ptr< CSemaphore > semAddnode
void Init(const Options &connOptions)
CThreadInterrupt interruptNet
static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections)
bool HasPermission(NetPermissionFlags permission) const
CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
static const unsigned int MAX_INV_SZ
The maximum number of entries in an 'inv' protocol message.
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
bool IsInboundConn() const
bool m_use_addrman_outgoing
std::vector< NetWhitebindPermissions > vWhiteBinds
bool IsLocal(const CService &addr)
check whether a given address is potentially local
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
bool GetUseAddrmanOutgoing() const
RecursiveMutex cs_hSocket
unsigned short GetListenPort()
const int nMyStartingHeight
bool m_use_addrman_outgoing
bool IsFullOutboundConn() const
RecursiveMutex cs_totalBytesSent
std::chrono::microseconds m_next_addr_send GUARDED_BY(cs_sendProcessing)
std::unique_ptr< TxRelay > m_tx_relay
int64_t m_peer_connect_timeout