32 #include <condition_variable> 110 std::vector<unsigned char>
data;
312 virtual std::optional<CNetMessage>
GetMessage(std::chrono::microseconds time, uint32_t& out_err) = 0;
349 hdrbuf(nTypeIn, nVersionIn),
350 vRecv(nTypeIn, nVersionIn)
372 msg_bytes = msg_bytes.
subspan(ret);
376 std::optional<CNetMessage>
GetMessage(std::chrono::microseconds time, uint32_t& out_err_raw_size)
override;
578 std::atomic<std::chrono::microseconds>
m_min_ping_time{std::chrono::microseconds::max()};
639 m_tx_relay->filterInventoryKnown.insert(hash);
647 if (!
m_tx_relay->filterInventoryKnown.contains(hash)) {
648 m_tx_relay->setInventoryTxToSend.insert(hash);
831 using NodeFn = std::function<void(CNode*)>;
835 for (
auto&&
node : vNodes) {
844 for (
auto&&
node : vNodes) {
858 std::vector<CAddress>
GetAddresses(
size_t max_addresses,
size_t max_pct, std::optional<Network> network)
const;
865 std::vector<CAddress>
GetAddresses(
CNode& requestor,
size_t max_addresses,
size_t max_pct);
906 void GetNodeStats(std::vector<CNodeStats>& vstats)
const;
950 std::chrono::microseconds
PoissonNextSendInbound(std::chrono::microseconds now, std::chrono::seconds average_interval);
996 bool GenerateSelectSet(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set);
997 void SocketEvents(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set);
1195 std::chrono::microseconds
PoissonNextSend(std::chrono::microseconds now, std::chrono::seconds average_interval);
1223 [[nodiscard]] std::optional<NodeId>
SelectNodeToEvict(std::vector<NodeEvictionCandidate>&& vEvictionCandidates);
1248 #endif // BITCOIN_NET_H std::chrono::microseconds m_min_ping_time
std::vector< CService > vBinds
int m_max_outbound_full_relay
std::atomic< bool > flagInterruptMsgProc
void copyStats(CNodeStats &stats, const std::vector< bool > &m_asmap)
std::vector< CAddress > m_addrs_response_cache
std::chrono::microseconds m_min_ping_time
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
std::optional< NodeId > SelectNodeToEvict(std::vector< NodeEvictionCandidate > &&vEvictionCandidates)
Select an inbound peer to evict after filtering out (protecting) peers having distinct, difficult-to-forge characteristics.
uint64_t CalculateKeyedNetGroup(const CAddress &ad) const
uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent)
CONSTEXPR_IF_NOT_DEBUG Span< C > subspan(std::size_t offset) const noexcept
std::vector< bool > m_asmap
bool IsReachable(enum Network net)
std::atomic_bool fPauseSend
void ThreadOpenAddedConnections()
static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH
Maximum length of incoming protocol messages (no message over 4 MB is currently acceptable).
bool m_i2p_accept_incoming
std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const
returns the time left in the current max outbound cycle in case of no limit, it will always return 0 ...
mapMsgCmdSize mapRecvBytesPerMsgCmd
std::atomic< bool > fNetworkActive
uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent)
static void AddFlag(NetPermissionFlags &flags, NetPermissionFlags f)
ServiceFlags
nServices flags
friend struct ConnmanTestMsg
std::unique_ptr< TransportSerializer > m_serializer
#define LogPrint(category,...)
std::string cleanSubVer GUARDED_BY(cs_SubVer)
cleanSubVer is a sanitized string of the user agent byte array we read from the wire.
int readData(Span< const uint8_t > msg_bytes)
int m_max_outbound_block_relay
We open manual connections to addresses that users explicitly requested via the addnode RPC or the -a...
void WakeMessageHandler()
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
bool fRelayTxes GUARDED_BY(cs_filter)
uint64_t GetOutboundTargetBytesLeft() const
response the bytes left in the current max outbound cycle in case of no limit, it will always respons...
void SocketEvents(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set)
const std::string NET_MESSAGE_COMMAND_OTHER
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(cs_mapLocalHost)
void SetVersion(int nVersionIn) override
void PushTxInventory(const uint256 &hash)
static const bool DEFAULT_FORCEDNSSEED
const uint64_t nKeyedNetGroup
bool SeenLocal(const CService &addr)
vote for a local address
CNode & operator=(const CNode &)=delete
bool IsOutboundOrBlockRelayConn() const
std::vector< unsigned char > data
const ConnectionType m_conn_type
void ProtectEvictionCandidatesByRatio(std::vector< NodeEvictionCandidate > &vEvictionCandidates)
Protect desirable or disadvantaged inbound peers from eviction by ratio.
uint64_t GetTotalBytesRecv() const
std::vector< NetWhitelistPermissions > vWhitelistedRange
bool IsFeelerConn() const
unsigned int nReceiveFloodSize
int m_max_outbound_full_relay
mapMsgCmdSize mapSendBytesPerMsgCmd
CClientUIInterface * uiInterface
void resize(size_type n, value_type c=0)
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...
void SetAsmap(std::vector< bool > asmap)
void CaptureMessage(const CAddress &addr, const std::string &msg_type, const Span< const unsigned char > &data, bool is_incoming)
Dump binary message to file, with timestamp.
bool AlreadyConnectedToAddress(const CAddress &addr)
Determine whether we're already connected to a given address, in order to avoid initiating duplicate ...
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, const CNetAddr &addr) const
CDataStream m_recv
received message data
static const bool DEFAULT_LISTEN
-listen default
CNetMessage(CDataStream &&recv_in)
RAII-style semaphore lock.
std::chrono::microseconds nNextInvSend
friend struct CConnmanTest
void SetCommonVersion(int greatest_common_version)
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
RecursiveMutex cs_vProcessMsg
uint32_t m_message_size
size of the payload
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
CSerializedNetMsg()=default
void CreateNodeFromAcceptedSocket(SOCKET hSocket, NetPermissionFlags permissionFlags, const CAddress &addr_bind, const CAddress &addr)
Create a CNode object from a socket that has just been accepted and add the node to the vNodes member...
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
void ForEachNode(const NodeFn &func) const
int m_max_outbound_block_relay
Double ended buffer combining vector and stream-like interfaces.
void SetTryNewOutboundPeer(bool flag)
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
uint64_t GetLocalNonce() const
std::unique_ptr< TransportDeserializer > m_deserializer
void ThreadSocketHandler()
CAmount lastSentFeeFilter
virtual void prepareForTransport(CSerializedNetMsg &msg, std::vector< unsigned char > &header)=0
ConnectionType m_conn_type
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).
std::vector< CAddress > GetAddresses(size_t max_addresses, size_t max_pct, std::optional< Network > network) const
Return all or many randomly selected addresses, optionally by network.
void GetNodeStats(std::vector< CNodeStats > &vstats) const
Signals for UI communication.
std::list< CNetMessage > vRecvMsg
bool GetTryNewOutboundPeer() const
void NotifyNumConnectionsChanged()
void RecordBytesSent(uint64_t bytes)
std::map< uint64_t, CachedAddrResponse > m_addr_response_caches
Addr responses stored in different caches per (network, local socket) prevent cross-network node iden...
std::atomic< ServiceFlags > nServices
void SetAddrLocal(const CService &addrLocalIn)
May not be called more than once.
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
static bool HasFlag(NetPermissionFlags flags, NetPermissionFlags f)
virtual ~TransportDeserializer()
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
RecursiveMutex cs_sendProcessing
ServiceFlags nLocalServices
Services this instance offers.
bool DisconnectNode(const std::string &node)
Stochastical (IP) address manager.
int GetExtraBlockRelayCount() const
int64_t CAmount
Amount in satoshis (Can be negative)
std::atomic< int64_t > nLastSend
std::atomic< CAmount > minFeeFilter
Minimum fee rate with which to filter inv's to this node.
void RecordBytesRecv(uint64_t bytes)
static const size_t DEFAULT_MAXRECEIVEBUFFER
std::chrono::microseconds PoissonNextSendInbound(std::chrono::microseconds now, std::chrono::seconds average_interval)
Attempts to obfuscate tx time through exponentially distributed emitting.
std::thread threadI2PAcceptIncoming
ServiceFlags GetLocalServices() const
void CloseSocketDisconnect()
RecursiveMutex cs_tx_inventory
std::chrono::microseconds m_cache_entry_expiration
void AddAddrFetch(const std::string &strDest)
bool GetLocal(CService &addr, const CNetAddr *paddrPeer=nullptr)
static bool NodeFullyConnected(const CNode *pnode)
unsigned int nPrevNodeCount
bool InactivityCheck(const CNode &node) const
Return true if the peer is inactive and should be disconnected.
bool AddNode(const std::string &node)
std::condition_variable condMsgProc
std::atomic_bool m_start_extra_block_relay_peers
flag for initiating extra block-relay-only peer connections.
RecursiveMutex cs_vAddedNodes
CService GetAddrLocal() const
virtual int Read(Span< const uint8_t > &msg_bytes)=0
read and deserialize data, advances msg_bytes data pointer
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *strDest, ConnectionType conn_type)
size_t SocketSendData(CNode &node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend)
ListenSocket(SOCKET socket_, NetPermissionFlags permissions_)
std::atomic< int64_t > nLastRecv
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
int Read(Span< const uint8_t > &msg_bytes) override
read and deserialize data, advances msg_bytes data pointer
std::thread threadOpenAddedConnections
void StartExtraBlockRelayPeers()
CNode * FindNode(const CNetAddr &ip)
ServiceFlags GetLocalServices() const
Used to convey which local services we are offering peers during node connection. ...
RecursiveMutex m_addr_fetches_mutex
bool IsPeerAddrLocalGood(CNode *pnode)
std::function< void(CNode *)> NodeFn
NetEventsInterface * m_msgproc
static const int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
CConnman(uint64_t seed0, uint64_t seed1, CAddrMan &addrman, bool network_active=true)
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
bool m_bip152_highbandwidth_from
int64_t m_peer_connect_timeout
std::unique_ptr< CSemaphore > semOutbound
void ThreadOpenConnections(std::vector< std::string > connect)
std::thread threadMessageHandler
friend struct ConnmanTestMsg
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
const uint256 & GetMessageHash() const
~NetEventsInterface()=default
Protected destructor so that instances can only be deleted by derived classes.
bool IsManualConn() const
virtual void FinalizeNode(const CNode &node)=0
Handle removal of a peer (clear state)
int GetExtraFullOutboundCount() const
std::chrono::microseconds m_last_ping_time
A CService with information about it as peer.
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const
Return vector of current BLOCK_RELAY peers.
bool Start(CScheduler &scheduler, const Options &options)
void MaybeSetAddrName(const std::string &addrNameIn)
Sets the addrName only if it was not previously set.
RecursiveMutex cs_mapLocalHost
bool ReceiveMsgBytes(Span< const uint8_t > msg_bytes, bool &complete)
Receive bytes from the buffer and deserialize them into messages.
bool m_bip152_highbandwidth_to
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 This t...
bool InitBinds(const Options &options)
void SetNetworkActive(bool active)
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
bool GetNetworkActive() const
std::atomic< bool > m_bip152_highbandwidth_to
CClientUIInterface * clientInterface
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
std::optional< CNetMessage > GetMessage(std::chrono::microseconds time, uint32_t &out_err_raw_size) override
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e. connected via our Tor onion service.
std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent)
void PongReceived(std::chrono::microseconds ping_time)
A ping-pong round trip has completed successfully.
std::atomic_bool fDisconnect
The TransportSerializer prepares messages for the network transport.
std::set< uint256 > setInventoryTxToSend
void prepareForTransport(CSerializedNetMsg &msg, std::vector< unsigned char > &header) override
std::atomic< std::chrono::seconds > m_last_mempool_req
#define Assume(val)
Assume is the identity function.
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
unsigned int GetReceiveFloodSize() const
Inbound connections are those initiated by a peer.
void DeleteNode(CNode *pnode)
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
NetPermissionFlags m_permissions
bool CheckIncomingNonce(uint64_t nonce)
std::atomic< int > nRefCount
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)
bool Complete() const override
static const bool DEFAULT_DNSSEED
bool IsBlockOnlyConn() const
std::chrono::microseconds m_next_send_feefilter
const int64_t nTimeConnected
Unix epoch time at peer connection, in seconds.
virtual ~TransportSerializer()
std::atomic< NodeId > nLastNodeId
static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
bool RemoveAddedNode(const std::string &node)
std::list< CNode * > vNodesDisconnected
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type)
void RemoveLocal(const CService &addr)
std::vector< NetWhitelistPermissions > vWhitelistedRange
std::vector< CService > onion_binds
size_t GetNodeCount(ConnectionDirection) const
uint32_t m_raw_message_size
used wire size of the message (including header/checksum)
#define EXCLUSIVE_LOCKS_REQUIRED(...)
bool ShouldRunInactivityChecks(const CNode &node, std::optional< int64_t > now=std::nullopt) const
Return true if we should disconnect the peer for failing an inactivity check.
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
BanMan * m_banman
Pointer to this node's banman.
void AddKnownTx(const uint256 &hash)
std::atomic< int64_t > nLastTXTime
UNIX epoch time of the last transaction received from this peer that we had not yet seen (e...
static const size_t DEFAULT_MAXSENDBUFFER
bool fSendMempool GUARDED_BY(cs_tx_inventory)
std::thread threadOpenConnections
bool AttemptToEvictConnection()
Try to find a connection to evict when the node is full.
ConnectionType
Different types of connections to a peer.
int readHeader(Span< const uint8_t > msg_bytes)
CSemaphoreGrant grantOutbound
The TransportDeserializer takes care of holding and deserializing the network receive buffer...
const CChainParams & m_chain_params
std::map< std::string, uint64_t > mapMsgCmdSize
Feeler connections are short-lived connections made to check that a node is alive.
std::vector< AddedNodeInfo > GetAddedNodeInfo() const
NetPermissionFlags m_permissionFlags
bool fAddressesInitialized
std::thread threadDNSAddressSeed
ServiceFlags nLocalServices
uint64_t nMaxOutboundLimit
std::vector< std::string > m_added_nodes
std::vector< ListenSocket > vhListenSocket
std::chrono::seconds GetMaxOutboundTimeframe() const
std::atomic< int > m_greatest_common_version
std::atomic< int64_t > nTimeOffset
size_t nSendOffset GUARDED_BY(cs_vSend)
Offset inside the first vSendMsg already sent.
std::atomic_bool fSuccessfullyConnected
fSuccessfullyConnected is set to true on receiving VERACK from the peer.
void ThreadMessageHandler()
These are the default connections that we use to connect with the network.
bool OutboundTargetReached(bool historicalBlockServingLimit) const
check if the outbound target is reached if param historicalBlockServingLimit is set true...
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
static constexpr auto FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes.
uint64_t nTotalBytesRecv GUARDED_BY(cs_totalBytesRecv)
std::atomic< int > nVersion
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
unsigned int nSendBufferMaxSize
static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL
Run the extra block-relay-only connection loop once every 5 minutes.
std::string ConnectionTypeAsString() const
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
const uint64_t nLocalHostNonce
unsigned int nSendBufferMaxSize
std::vector< bool > m_asmap
std::atomic< bool > m_bip152_highbandwidth_from
void ThreadI2PAcceptIncoming()
const ServiceFlags nLocalServices
Services offered to this peer.
bool IsAddrFetchConn() const
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
bool AddConnection(const std::string &address, ConnectionType conn_type)
Attempts to open a connection.
SOCKET hSocket GUARDED_BY(cs_hSocket)
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks, tx, addrs, etc)
bool GenerateSelectSet(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set)
void AcceptConnection(const ListenSocket &hListenSocket)
A Span is an object that can refer to a contiguous sequence of objects.
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
std::chrono::microseconds PoissonNextSend(std::chrono::microseconds now, std::chrono::seconds average_interval)
Return a timestamp in the future (in microseconds) for exponentially distributed events.
uint64_t GetMaxOutboundTarget() const
Information about a peer.
void ForEachNode(const NodeFn &func)
std::thread threadSocketHandler
Simple class for background tasks that should be run periodically or once "after a while"...
We use block-relay-only connections to help prevent against partition attacks.
RecursiveMutex cs_totalBytesRecv
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
virtual bool Complete() const =0
std::atomic< std::chrono::microseconds > m_last_ping_time
Last measured round-trip time.
NetPermissionFlags m_permissionFlags
Network ConnectedThroughNetwork() const
Get network the peer connected through.
virtual void InitializeNode(CNode *pnode)=0
Initialize a peer (setup state, queue any initial messages)
std::string GetAddrName() const
V1TransportDeserializer(const CChainParams &chain_params, const NodeId node_id, int nTypeIn, int nVersionIn)
std::chrono::microseconds m_time
time of message receipt
RecursiveMutex cs_addrLocal
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
AddrFetch connections are short lived connections used to solicit addresses from peers.
std::atomic< std::chrono::microseconds > m_min_ping_time
Lowest measured round-trip time.
int GetCommonVersion() const
uint64_t GetTotalBytesSent() const
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
std::atomic_bool fPauseRecv
virtual std::optional< CNetMessage > GetMessage(std::chrono::microseconds time, uint32_t &out_err)=0
std::unique_ptr< CSemaphore > semAddnode
std::atomic< std::chrono::microseconds > m_next_send_inv_to_incoming
void Init(const Options &connOptions)
CThreadInterrupt interruptNet
This is signaled when network activity should cease.
bool HasPermission(NetPermissionFlags permission) const
virtual void SetVersion(int version)=0
std::optional< CAddress > GetLocalAddrForPeer(CNode *pnode)
Returns a local address that we should advertise to this peer.
CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
bool IsInboundConn() const
bool m_use_addrman_outgoing
std::vector< NetWhitebindPermissions > vWhiteBinds
std::atomic< int64_t > nLastBlockTime
UNIX epoch time of the last block received from this peer that we had not yet seen (e...
bool IsLocal(const CService &addr)
check whether a given address is potentially local
size_t nSendSize GUARDED_BY(cs_vSend)
Total size of all vSendMsg entries.
bool GetUseAddrmanOutgoing() const
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0...
bool m_use_addrman_outgoing
Cache responses to addr requests to minimize privacy leak.
virtual bool ProcessMessages(CNode *pnode, std::atomic< bool > &interrupt)=0
Process protocol messages received from a given node.
bool IsFullOutboundConn() const
RecursiveMutex cs_totalBytesSent
unsigned int nReceiveFloodSize
std::unique_ptr< TxRelay > m_tx_relay
virtual bool SendMessages(CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(pnode -> cs_sendProcessing)=0
Send queued protocol messages to a given node.
void ThreadDNSAddressSeed()
int64_t m_peer_connect_timeout
std::unique_ptr< CBloomFilter > pfilter PT_GUARDED_BY(cs_filter) GUARDED_BY(cs_filter)
static const bool DEFAULT_FIXEDSEEDS