34 #include <condition_variable> 37 #include <arpa/inet.h> 114 std::vector<unsigned char>
data;
255 CConnman(uint64_t seed0, uint64_t seed1,
bool network_active =
true);
278 using NodeFn = std::function<void(CNode*)>;
282 for (
auto&& node : vNodes) {
291 for (
auto&& node : vNodes) {
297 template<
typename Callable,
typename CallableAfter>
301 for (
auto&& node : vNodes) {
308 template<
typename Callable,
typename CallableAfter>
312 for (
auto&& node : vNodes) {
323 std::vector<CAddress>
GetAddresses(
size_t max_addresses,
size_t max_pct);
330 std::vector<CAddress>
GetAddresses(
CNode& requestor,
size_t max_addresses,
size_t max_pct);
345 bool AddNode(
const std::string& node);
419 const std::vector<CService>& binds,
420 const std::vector<NetWhitebindPermissions>& whiteBinds,
421 const std::vector<CService>& onion_binds);
432 bool GenerateSelectSet(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set);
433 void SocketEvents(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set);
761 virtual int Read(
const char *data,
unsigned int bytes) = 0;
782 int readHeader(
const char *pch,
unsigned int nBytes);
783 int readData(
const char *pch,
unsigned int nBytes);
800 hdrbuf(nTypeIn, nVersionIn),
801 vRecv(nTypeIn, nVersionIn)
817 int Read(
const char *pch,
unsigned int nBytes)
override {
819 if (ret < 0)
Reset();
1051 std::atomic<std::chrono::microseconds>
m_ping_start{std::chrono::microseconds{0}};
1059 CNode(
NodeId id,
ServiceFlags nLocalServicesIn,
int nMyStartingHeightIn,
SOCKET hSocketIn,
const CAddress &addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn,
const CAddress &addrBindIn,
const std::string &addrNameIn,
ConnectionType conn_type_in,
bool inbound_onion =
false);
1121 bool ReceiveMsgBytes(
const char *pch,
unsigned int nBytes,
bool& complete);
1180 m_tx_relay->filterInventoryKnown.insert(hash);
1188 if (!
m_tx_relay->filterInventoryKnown.contains(hash)) {
1189 m_tx_relay->setInventoryTxToSend.insert(hash);
1213 inline std::chrono::microseconds
PoissonNextSend(std::chrono::microseconds
now, std::chrono::seconds average_interval)
1215 return std::chrono::microseconds{
PoissonNextSend(
now.count(), average_interval.count())};
1218 #endif // BITCOIN_NET_H 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
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
uint64_t CalculateKeyedNetGroup(const CAddress &ad) const
uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent)
std::atomic< uint64_t > nPingNonceSent
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).
mapMsgCmdSize mapRecvBytesPerMsgCmd
const std::chrono::seconds now
std::atomic< bool > fNetworkActive
static void AddFlag(NetPermissionFlags &flags, NetPermissionFlags f)
ServiceFlags
nServices flags
static const uint64_t MAX_UPLOAD_TIMEFRAME
The default timeframe for -maxuploadtarget.
friend struct ConnmanTestMsg
std::unique_ptr< TransportSerializer > m_serializer
std::string cleanSubVer GUARDED_BY(cs_SubVer)
cleanSubVer is a sanitized string of the user agent byte array we read from the wire.
int m_max_outbound_block_relay
We open manual connections to addresses that users explicitly inputted via the addnode RPC...
std::atomic< int > nBestHeight
void WakeMessageHandler()
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
bool fRelayTxes GUARDED_BY(cs_filter)
void SetServices(const CService &addr, ServiceFlags nServices)
void SocketEvents(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set)
const std::string NET_MESSAGE_COMMAND_OTHER
int64_t nextSendTimeFeeFilter
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
bool ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool &complete)
Receive bytes from the buffer and deserialize them into messages.
CNode & operator=(const CNode &)=delete
mapMsgCmdSize mapSendBytesPerMsgCmd
bool IsOutboundOrBlockRelayConn() const
std::vector< unsigned char > data
const ConnectionType m_conn_type
std::vector< NetWhitelistPermissions > vWhitelistedRange
CAmount minFeeFilter GUARDED_BY(cs_feeFilter)
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)
std::atomic_bool m_wants_addrv2
Whether the peer has signaled support for receiving ADDRv2 (BIP155) messages, implying a preference t...
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
bool GetTryNewOutboundPeer()
std::atomic< int64_t > m_next_send_inv_to_incoming
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
virtual Optional< CNetMessage > GetMessage(std::chrono::microseconds time, uint32_t &out_err)=0
void SetCommonVersion(int greatest_common_version)
uint64_t GetMaxOutboundTarget()
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
int readHeader(const char *pch, unsigned int nBytes)
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
RecursiveMutex cs_vProcessMsg
uint32_t m_message_size
size of the payload
void SetMaxOutboundTimeframe(uint64_t timeframe)
set the timeframe for the max outbound target
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
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
void ForEachNode(const NodeFn &func) const
void AdvertiseLocal(CNode *pnode)
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()
std::vector< CAddress > vAddrToSend
CAmount lastSentFeeFilter
virtual bool SendMessages(CNode *pnode)=0
size_t GetNodeCount(NumConnections num)
virtual void prepareForTransport(CSerializedNetMsg &msg, std::vector< unsigned char > &header)=0
std::atomic< int > nStartingHeight
void PushAddress(const CAddress &_addr, FastRandomContext &insecure_rand)
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).
Signals for UI communication.
std::list< CNetMessage > vRecvMsg
void NotifyNumConnectionsChanged()
virtual int Read(const char *data, unsigned int bytes)=0
void SetMaxOutboundTarget(uint64_t limit)
set the max outbound target in bytes
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.
uint64_t GetMaxOutboundTimeframe()
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.
int64_t CAmount
Amount in satoshis (Can be negative)
std::atomic< int64_t > nLastSend
void RecordBytesRecv(uint64_t bytes)
int readData(const char *pch, unsigned int nBytes)
static const size_t DEFAULT_MAXRECEIVEBUFFER
std::atomic< int64_t > nPingUsecTime
std::atomic< int64_t > nMinPingUsecTime
int GetMyStartingHeight() const
std::chrono::microseconds m_next_local_addr_send GUARDED_BY(cs_sendProcessing)
ServiceFlags GetLocalServices() const
void CloseSocketDisconnect()
RecursiveMutex cs_tx_inventory
uint64_t GetOutboundTargetBytesLeft()
response the bytes left in the current max outbound cycle in case of no limit, it will always respons...
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
std::unique_ptr< CRollingBloomFilter > m_addr_known
bool AddNode(const std::string &node)
std::condition_variable condMsgProc
RecursiveMutex cs_vAddedNodes
CService GetAddrLocal() const
uint64_t GetMaxOutboundTimeLeftInCycle()
response the time in second left in the current max outbound cycle in case of no limit, it will always response 0
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *strDest, ConnectionType conn_type)
ListenSocket(SOCKET socket_, NetPermissionFlags permissions_)
void InactivityCheck(CNode *pnode)
std::atomic< int64_t > nLastRecv
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
std::thread threadOpenAddedConnections
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
A combination of a network address (CNetAddr) and a (TCP) port.
Transport protocol agnostic message container.
std::vector< std::string > vSeedNodes
int64_t PoissonNextSendInbound(int64_t now, int average_interval_seconds)
Attempts to obfuscate tx time through exponentially distributed emitting.
bool OutboundTargetReached(bool historicalBlockServingLimit)
check if the outbound target is reached if param historicalBlockServingLimit is set true...
std::vector< std::string > m_specified_outgoing
int64_t m_peer_connect_timeout
std::unique_ptr< CSemaphore > semOutbound
void ThreadOpenConnections(std::vector< std::string > connect)
std::thread threadMessageHandler
bool RelayAddrsWithConn() const
static bool HasFlag(const NetPermissionFlags &flags, NetPermissionFlags f)
void ForEachNodeThen(Callable &&pre, CallableAfter &&post)
friend struct ConnmanTestMsg
virtual void FinalizeNode(const CNode &node, bool &update_connection_time)=0
const uint256 & GetMessageHash() const
~NetEventsInterface()=default
Protected destructor so that instances can only be deleted by derived classes.
bool IsManualConn() const
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)
std::vector< unsigned char > GetKey() const
void MaybeSetAddrName(const std::string &addrNameIn)
Sets the addrName only if it was not previously set.
int Read(const char *pch, unsigned int nBytes) override
uint64_t GetTotalBytesRecv()
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 This t...
void SetNetworkActive(bool active)
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
bool GetNetworkActive() const
CClientUIInterface * clientInterface
void GetNodeStats(std::vector< CNodeStats > &vstats)
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
const bool m_inbound_onion
Whether this peer connected via our Tor onion service.
bool AddNewAddresses(const std::vector< CAddress > &vAddr, const CAddress &addrFrom, int64_t nTimePenalty=0)
std::atomic_bool fDisconnect
bool InitBinds(const std::vector< CService > &binds, const std::vector< NetWhitebindPermissions > &whiteBinds, const std::vector< CService > &onion_binds)
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
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
unsigned int GetReceiveFloodSize() const
Inbound connections are those initiated by a peer.
void DeleteNode(CNode *pnode)
NetPermissionFlags m_permissions
bool CheckIncomingNonce(uint64_t nonce)
std::atomic< int > nRefCount
bool Complete() const override
bool IsBlockOnlyConn() const
const int64_t nTimeConnected
virtual ~TransportSerializer()
uint64_t nMaxOutboundTimeframe
std::atomic< NodeId > nLastNodeId
bool RemoveAddedNode(const std::string &node)
RecursiveMutex cs_feeFilter
std::list< CNode * > vNodesDisconnected
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type)
std::atomic< bool > fPingQueued
void RemoveLocal(const CService &addr)
std::vector< NetWhitelistPermissions > vWhitelistedRange
std::vector< CService > onion_binds
int GetBestHeight() const
uint32_t m_raw_message_size
used wire size of the message (including header/checksum)
Optional< CNetMessage > GetMessage(std::chrono::microseconds time, uint32_t &out_err_raw_size) override
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
void AddKnownTx(const uint256 &hash)
BanMan * m_banman
Pointer to this node's banman.
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.
static const uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
ConnectionType
Different types of connections to a peer.
CNode(NodeId id, ServiceFlags nLocalServicesIn, int nMyStartingHeightIn, SOCKET hSocketIn, const CAddress &addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const CAddress &addrBindIn, const std::string &addrNameIn, ConnectionType conn_type_in, bool inbound_onion=false)
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.
static constexpr size_t MAX_ADDR_TO_SEND
The maximum number of addresses from our addrman to return in response to a getaddr message...
NetPermissionFlags m_permissionFlags
bool fAddressesInitialized
std::thread threadDNSAddressSeed
ServiceFlags nLocalServices
uint64_t nMaxOutboundLimit
size_t SocketSendData(CNode *pnode) const
std::vector< std::string > m_added_nodes
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
void SetBestHeight(int height)
std::atomic< int > m_greatest_common_version
std::atomic< int64_t > nTimeOffset
void ForEachNodeThen(Callable &&pre, CallableAfter &&post) const
std::atomic_bool fSuccessfullyConnected
std::string m_conn_type_string
void ThreadMessageHandler()
std::vector< CAddress > GetAddresses(size_t max_addresses, size_t max_pct)
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.
uint64_t nTotalBytesRecv GUARDED_BY(cs_totalBytesRecv)
std::atomic< int > nVersion
static const bool DEFAULT_UPNP
-upnp default
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
unsigned int nSendBufferMaxSize
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
const ServiceFlags nLocalServices
Services offered to this peer.
int GetExtraOutboundCount()
bool IsAddrFetchConn() const
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
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)
uint64_t GetTotalBytesSent()
bool GenerateSelectSet(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set)
void AcceptConnection(const ListenSocket &hListenSocket)
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
void MarkAddressGood(const CAddress &addr)
boost::optional< T > Optional
Substitute for C++17 std::optional.
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
NetPermissionFlags m_permissionFlags
CConnman(uint64_t seed0, uint64_t seed1, bool network_active=true)
Network ConnectedThroughNetwork() const
Get network the peer connected through.
virtual void InitializeNode(CNode *pnode)=0
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.
void AddAddressKnown(const CAddress &_addr)
int GetCommonVersion() const
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
std::atomic_bool fPauseRecv
std::unique_ptr< CSemaphore > semAddnode
bool IsAddrV1Compatible() const
Check if the current object can be serialized in pre-ADDRv2/BIP155 format.
void Init(const Options &connOptions)
CThreadInterrupt interruptNet
bool HasPermission(NetPermissionFlags permission) const
virtual void SetVersion(int version)=0
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
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
bool GetUseAddrmanOutgoing() const
std::vector< AddedNodeInfo > GetAddedNodeInfo()
RecursiveMutex cs_hSocket
const int nMyStartingHeight
bool m_use_addrman_outgoing
Cache responses to addr requests to minimize privacy leak.
virtual bool ProcessMessages(CNode *pnode, std::atomic< bool > &interrupt)=0
bool IsFullOutboundConn() const
std::atomic< std::chrono::microseconds > m_ping_start
When the last ping was sent, or 0 if no ping was ever sent.
RecursiveMutex cs_totalBytesSent
unsigned int nReceiveFloodSize
std::chrono::microseconds m_next_addr_send GUARDED_BY(cs_sendProcessing)
std::unique_ptr< TxRelay > m_tx_relay
void ThreadDNSAddressSeed()
int64_t m_peer_connect_timeout
std::unique_ptr< CBloomFilter > pfilter PT_GUARDED_BY(cs_filter) GUARDED_BY(cs_filter)