37#include <condition_variable>
48#include <unordered_set>
136 std::vector<unsigned char>
data;
171bool IsLocal(
const CService& addr);
315 std::span<const uint8_t> ,
408 if (!in_data)
return false;
409 return hdr.nMessageSize == nDataPos;
432 Info GetInfo() const noexcept override;
442 msg_bytes = msg_bytes.subspan(
ret);
601 std::vector<uint8_t> m_recv_decode_buffer
GUARDED_BY(m_recv_mutex);
613 std::vector<uint8_t> m_send_garbage
GUARDED_BY(m_send_mutex);
619 bool m_sent_v1_header_worth
GUARDED_BY(m_send_mutex) {
false};
626 static std::optional<std::string> GetMessageType(std::span<const uint8_t>& contents)
noexcept;
768 mapSendBytesPerMsgType[msg_type] += sent_bytes;
859 Network ConnectedThroughNetwork()
const;
862 [[nodiscard]]
bool IsConnectedThroughPrivacyNet()
const;
898 std::atomic<std::chrono::microseconds>
m_min_ping_time{std::chrono::microseconds::max()};
901 std::shared_ptr<Sock> sock,
903 uint64_t nKeyedNetGroupIn,
904 uint64_t nLocalHostNonceIn,
906 const std::string& addrNameIn,
909 uint64_t network_key,
976 std::string LogIP(
bool log_ip)
const;
984 std::string DisconnectMsg(
bool log_ip)
const;
1122 LOCK(m_total_bytes_sent_mutex);
1132 for (
const std::string& added_node : connOptions.m_added_nodes) {
1150 bool network_active =
true,
1151 std::shared_ptr<CThreadInterrupt> interrupt_net = std::make_shared<CThreadInterrupt>());
1169 void SetNetworkActive(
bool active);
1183 bool OpenNetworkConnection(
const CAddress& addrConnect,
1186 const char* pszDest,
1188 bool use_v2transport,
1189 const std::optional<Proxy>& proxy_override = std::nullopt)
1221 std::optional<Network> PickNetwork(std::optional<Proxy>& proxy)
const;
1224 size_t NumToOpen()
const;
1231 void NumToOpenAdd(
size_t n);
1239 size_t NumToOpenSub(
size_t n);
1242 void NumToOpenWait()
const;
1250 std::optional<Proxy> ProxyForIPv4or6()
const;
1256 } m_private_broadcast;
1258 bool CheckIncomingNonce(uint64_t
nonce);
1259 void ASMapHealthCheck();
1272 for (
auto&&
node : m_nodes) {
1281 for (
auto&&
node : m_nodes) {
1299 std::vector<CAddress> GetAddressesUnsafe(
size_t max_addresses,
size_t max_pct, std::optional<Network> network,
bool filtered =
true)
const;
1314 std::vector<CAddress> GetAddresses(
CNode& requestor,
size_t max_addresses,
size_t max_pct);
1318 void SetTryNewOutboundPeer(
bool flag);
1319 bool GetTryNewOutboundPeer()
const;
1321 void StartExtraBlockRelayPeers();
1324 int GetFullOutboundConnCount()
const;
1331 int GetExtraFullOutboundCount()
const;
1333 int GetExtraBlockRelayCount()
const;
1338 std::vector<AddedNodeInfo> GetAddedNodeInfo(
bool include_connected)
const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1356 std::map<CNetAddr, LocalServiceInfo> getNetLocalAddresses()
const;
1357 uint32_t GetMappedAS(
const CNetAddr& addr)
const;
1358 void GetNodeStats(std::vector<CNodeStats>& vstats)
const;
1359 bool DisconnectNode(std::string_view
node);
1360 bool DisconnectNode(
const CSubNet& subnet);
1361 bool DisconnectNode(
const CNetAddr& addr);
1362 bool DisconnectNode(
NodeId id);
1378 std::chrono::seconds GetMaxOutboundTimeframe() const;
1383 bool OutboundTargetReached(
bool historicalBlockServingLimit) const
EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1391 uint64_t GetTotalBytesRecv() const;
1395 CSipHasher GetDeterministicRandomizer(uint64_t
id) const;
1400 bool ShouldRunInactivityChecks(const
CNode&
node,
std::chrono::microseconds now) const;
1471 const
Sock::EventsPerSock& events_per_sock)
1521 const
char* pszDest,
1525 const
std::optional<
Proxy>& proxy_override)
1830 const std::vector<CNode*>&
Nodes()
const
1845extern std::function<void(
const CAddress& addr,
1846 const std::string& msg_type,
1847 std::span<const unsigned char> data,
#define Assume(val)
Assume is the identity function.
Stochastic address manager.
The BIP324 packet cipher, encapsulating its key derivation, stream cipher, and AEAD.
A CService with information about it as peer.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Signals for UI communication.
const std::vector< CNode * > & Nodes() const
NodesSnapshot(const CConnman &connman, bool shuffle)
std::vector< CNode * > m_nodes_copy
Group of private broadcast related members.
std::atomic_bool m_outbound_tor_ok_at_least_once
Remember if we ever established at least one outbound connection to a Tor peer, including sending and...
std::atomic_size_t m_num_to_open
Number of ConnectionType::PRIVATE_BROADCAST connections to open.
friend struct ConnmanTestMsg
std::counting_semaphore m_sem_conn_max
Semaphore used to guard against opening too many connections.
std::unordered_set< Network > GetReachableEmptyNetworks() const
Return reachable networks for which we have no addresses in addrman and therefore may require loading...
std::condition_variable condMsgProc
std::thread threadMessageHandler
void ForEachNode(const NodeFn &func)
void RemoveLocalServices(ServiceFlags services)
bool AlreadyConnectedToHost(std::string_view host) const
Determine whether we're already connected to a given "host:port".
std::reference_wrapper< AddrMan > addrman
void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
void ForEachNode(const NodeFn &func) const
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
void DisconnectNodes() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex
m_max_outbound_full_relay
void DeleteNode(CNode *pnode)
bool AttemptToEvictConnection()
Try to find a connection to evict when the node is full.
bool GetNetworkActive() const
static constexpr size_t MAX_UNUSED_I2P_SESSIONS_SIZE
Cap on the size of m_unused_i2p_sessions, to ensure it does not unexpectedly use too much memory.
std::vector< AddedNodeParams > m_added_node_params GUARDED_BY(m_added_nodes_mutex)
const bool use_v2transport(GetLocalServices() &NODE_P2P_V2)
uint16_t GetDefaultPort(Network net) const
std::array< unsigned int, Network::NET_MAX > m_network_conn_counts GUARDED_BY(m_nodes_mutex)
void PerformReconnections() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex
Attempt reconnections, if m_reconnections non-empty.
void SetCaptureMessages(bool cap)
std::thread threadI2PAcceptIncoming
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type, bool use_v2transport, const std::optional< Proxy > &proxy_override) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Open a new P2P connection.
std::atomic< bool > flagInterruptMsgProc
void CreateNodeFromAcceptedSocket(std::unique_ptr< Sock > &&sock, NetPermissionFlags permission_flags, const CService &addr_bind, const CService &addr)
Create a CNode object from a socket that has just been accepted and add the node to the m_nodes membe...
std::list< ReconnectionInfo > m_reconnections GUARDED_BY(m_reconnections_mutex)
List of reconnections we have to make.
void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
uint64_t nMaxOutboundLimit GUARDED_BY(m_total_bytes_sent_mutex)
std::atomic< NodeId > nLastNodeId
bool fMsgProcWake GUARDED_BY(mutexMsgProc)
flag for waking the message processor.
uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex)
std::thread threadDNSAddressSeed
void SocketHandlerConnected(const std::vector< CNode * > &nodes, const Sock::EventsPerSock &events_per_sock) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
Do the read/write for connected sockets that are ready for IO.
void ThreadI2PAcceptIncoming()
const NetGroupManager & m_netgroupman
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
uint64_t CalculateKeyedNetGroup(const CNetAddr &ad) const
friend struct ConnmanTestMsg
unsigned int nPrevNodeCount
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, std::optional< CNetAddr > addr, const std::vector< NetWhitelistPermissions > &ranges) const
void NotifyNumConnectionsChanged()
ServiceFlags GetLocalServices() 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)
vWhitelistedRangeOutgoing
void AddAddrFetch(const std::string &strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex)
std::vector< ListenSocket > vhListenSocket
bool AlreadyConnectedToAddress(const CNetAddr &addr) const
Determine whether we're already connected to a given address.
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const
Return vector of current BLOCK_RELAY peers.
Mutex m_total_bytes_sent_mutex
void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
std::thread threadOpenConnections
void Stop() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex)
void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Mutex m_addr_fetches_mutex
Mutex m_reconnections_mutex
Mutex protecting m_reconnections.
bool Start(CScheduler &scheduler, const Options &options) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
void SocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
Check connected and listening sockets for IO readiness and process them accordingly.
std::chrono::seconds GetMaxOutboundTimeLeftInCycle_() const EXCLUSIVE_LOCKS_REQUIRED(m_total_bytes_sent_mutex)
std::pair< size_t, bool > SocketSendData(CNode &node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend)
(Try to) send data from node's vSendMsg.
RecursiveMutex m_nodes_mutex
m_max_outbound_block_relay
std::queue< std::unique_ptr< i2p::sam::Session > > m_unused_i2p_sessions GUARDED_BY(m_unused_i2p_sessions_mutex)
A pool of created I2P SAM transient sessions that should be used instead of creating new ones in orde...
static bool NodeFullyConnected(const CNode *pnode)
std::unique_ptr< std::counting_semaphore<> > semOutbound
const CChainParams & m_params
std::deque< std::string > m_addr_fetches GUARDED_BY(m_addr_fetches_mutex)
const std::shared_ptr< CThreadInterrupt > m_interrupt_net
This is signaled when network activity should cease.
void AddLocalServices(ServiceFlags services)
m_max_automatic_connections
std::thread threadPrivateBroadcast
void ThreadOpenConnections(std::vector< std::string > connect, std::span< const std::string > seed_nodes) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
bool fAddressesInitialized
std::thread threadOpenAddedConnections
Mutex m_added_nodes_mutex
vWhitelistedRangeIncoming
void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
void RecordBytesSent(uint64_t bytes) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
void Init(const Options &connOptions) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Mutex m_unused_i2p_sessions_mutex
Mutex protecting m_i2p_sam_sessions.
std::vector< CNode * > m_nodes GUARDED_BY(m_nodes_mutex)
std::unique_ptr< std::counting_semaphore<> > semAddnode
void ThreadPrivateBroadcast() EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
bool MaybePickPreferredNetwork(std::optional< Network > &network)
Search for a "preferred" network, a reachable network to which we currently don't have any OUTBOUND_F...
void RecordBytesRecv(uint64_t bytes)
std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex)
void StopNodes() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex)
uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex)
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
bool GetUseAddrmanOutgoing() const
std::list< CNode * > m_nodes_disconnected
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
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::function< void(CNode *)> NodeFn
Sock::EventsPerSock GenerateWaitSockets(std::span< CNode *const > nodes)
Generate a collection of sockets to check for IO readiness.
std::atomic< uint64_t > nTotalBytesRecv
std::atomic< bool > fNetworkActive
std::atomic_bool m_start_extra_block_relay_peers
flag for initiating extra block-relay-only peer connections.
bool InactivityCheck(const CNode &node, std::chrono::microseconds now) const
Return true if the peer is inactive and should be disconnected.
void SocketHandlerListening(const Sock::EventsPerSock &events_per_sock)
Accept incoming connections, one from each read-ready listening socket.
CConnman(uint64_t seed0, uint64_t seed1, AddrMan &addrman, const NetGroupManager &netgroupman, const CChainParams ¶ms, bool network_active=true, std::shared_ptr< CThreadInterrupt > interrupt_net=std::make_shared< CThreadInterrupt >())
bool AlreadyConnectedToAddressPort(const CService &addr_port) const
Determine whether we're already connected to a given address:port.
RecursiveMutex & GetNodesMutex() const LOCK_RETURNED(m_nodes_mutex)
std::thread threadSocketHandler
void AcceptConnection(const ListenSocket &hListenSocket)
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
An encapsulated private key.
Transport protocol agnostic message container.
CNetMessage(CNetMessage &&)=default
size_t GetMemoryUsage() const noexcept
Compute total memory usage of this object (own memory + any dynamic memory).
uint32_t m_message_size
size of the payload
std::chrono::microseconds m_time
time of message receipt
CNetMessage(DataStream &&recv_in)
uint32_t m_raw_message_size
used wire size of the message (including header/checksum)
DataStream m_recv
received message data
CNetMessage & operator=(const CNetMessage &)=delete
CNetMessage(const CNetMessage &)=delete
CNetMessage & operator=(CNetMessage &&)=default
Information about a peer.
bool IsFeelerConn() const
const std::chrono::seconds m_connected
Unix epoch time at peer connection.
bool ExpectServicesFromConn() const
const std::string m_dest
The pszDest argument provided to ConnectNode().
std::atomic< int > nVersion
CService m_addr_local GUARDED_BY(m_addr_local_mutex)
std::atomic_bool m_has_all_wanted_services
Whether this peer provides all services that we want.
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
bool IsInboundConn() const
bool HasPermission(NetPermissionFlags permission) const
CountingSemaphoreGrant grantOutbound
std::atomic_bool fPauseRecv
bool IsOutboundOrBlockRelayConn() const
bool IsManualConn() const
const std::string m_addr_name
void CopyStats(CNodeStats &stats) EXCLUSIVE_LOCKS_REQUIRED(!m_subver_mutex
CNode & operator=(const CNode &)=delete
std::string ConnectionTypeAsString() const
void SetCommonVersion(int greatest_common_version)
std::atomic< bool > m_bip152_highbandwidth_to
std::list< CNetMessage > vRecvMsg
std::atomic_bool m_relays_txs
Whether we should relay transactions to this peer.
std::atomic< bool > m_bip152_highbandwidth_from
void PongReceived(std::chrono::microseconds ping_time)
A ping-pong round trip has completed successfully.
std::atomic_bool fSuccessfullyConnected
fSuccessfullyConnected is set to true on receiving VERACK from the peer.
const bool m_prefer_evict
size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex)
bool IsAddrFetchConn() const
uint64_t GetLocalNonce() const
mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend)
const uint64_t nKeyedNetGroup
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session GUARDED_BY(m_sock_mutex)
If an I2P session is created per connection (for outbound transient I2P connections) then it is store...
std::atomic< int > nRefCount
std::atomic< int > m_greatest_common_version
bool IsBlockOnlyConn() const
CNode(NodeId id, std::shared_ptr< Sock > sock, const CAddress &addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const CService &addrBindIn, const std::string &addrNameIn, ConnectionType conn_type_in, bool inbound_onion, uint64_t network_key, CNodeOptions &&node_opts={})
void MarkReceivedMsgsForProcessing() EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex)
Move all messages from the received queue to the processing queue.
int GetCommonVersion() const
mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv)
bool IsFullOutboundConn() const
const uint64_t m_network_key
Network key used to prevent fingerprinting our node across networks.
std::atomic_bool fPauseSend
std::optional< std::pair< CNetMessage, bool > > PollMessage() EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex)
Poll the next message from the processing queue of this connection.
Mutex m_msg_process_queue_mutex
std::atomic_bool m_bloom_filter_loaded
Whether this peer has loaded a bloom filter.
const ConnectionType m_conn_type
const size_t m_recv_flood_size
const uint64_t nLocalHostNonce
std::atomic< std::chrono::microseconds > m_last_ping_time
Last measured round-trip time.
bool IsManualOrFullOutboundConn() const
bool IsPrivateBroadcastConn() const
const std::unique_ptr< Transport > m_transport
Transport serializer/deserializer.
std::shared_ptr< Sock > m_sock GUARDED_BY(m_sock_mutex)
Socket used for communication with the node.
const NetPermissionFlags m_permission_flags
CNode(const CNode &)=delete
size_t m_send_memusage GUARDED_BY(cs_vSend)
Sum of GetMemoryUsage of all vSendMsg entries.
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e. connected via our Tor onion service.
std::atomic< std::chrono::microseconds > m_min_ping_time
Lowest measured round-trip time.
void AccountForSentBytes(const std::string &msg_type, size_t sent_bytes) EXCLUSIVE_LOCKS_REQUIRED(cs_vSend)
Account for the total size of a sent message in the per msg type connection stats.
std::atomic< std::chrono::seconds > m_last_block_time
UNIX epoch time of the last block received from this peer that we had not yet seen (e....
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Total number of bytes sent on the wire to this peer.
std::atomic_bool fDisconnect
std::atomic< std::chrono::seconds > m_last_recv
std::atomic< std::chrono::seconds > m_last_tx_time
UNIX epoch time of the last transaction received from this peer that we had not yet seen (e....
std::atomic< std::chrono::seconds > m_last_send
std::list< CNetMessage > m_msg_process_queue GUARDED_BY(m_msg_process_queue_mutex)
std::deque< CSerializedNetMsg > vSendMsg GUARDED_BY(cs_vSend)
Messages still to be fed to m_transport->SetMessageToSend.
std::string cleanSubVer GUARDED_BY(m_subver_mutex)
cleanSubVer is a sanitized string of the user agent byte array we read from the wire.
std::string m_session_id
BIP324 session id string in hex, if any.
std::chrono::microseconds m_last_ping_time
mapMsgTypeSize mapRecvBytesPerMsgType
std::chrono::seconds m_last_recv
ConnectionType m_conn_type
std::chrono::seconds m_last_send
std::chrono::seconds m_last_tx_time
mapMsgTypeSize mapSendBytesPerMsgType
std::chrono::microseconds m_min_ping_time
TransportProtocolType m_transport_type
Transport protocol type.
std::chrono::seconds m_connected
bool m_bip152_highbandwidth_from
bool m_bip152_highbandwidth_to
std::chrono::seconds m_last_block_time
NetPermissionFlags m_permission_flags
Simple class for background tasks that should be run periodically or once "after a while".
A combination of a network address (CNetAddr) and a (TCP) port.
General SipHash-2-4 implementation.
RAII-style semaphore lock.
Double ended buffer combining vector and stream-like interfaces.
Different type to mark Mutex at global scope.
Interface for message handling.
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
virtual void FinalizeNode(const CNode &node)=0
Handle removal of a peer (clear state).
virtual bool ProcessMessages(CNode &node, std::atomic< bool > &interrupt) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Process protocol messages received from a given node.
virtual bool HasAllDesirableServiceFlags(ServiceFlags services) const =0
Callback to determine whether the given set of service flags are sufficient for a peer to be "relevan...
virtual bool SendMessages(CNode &node) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Send queued protocol messages to a given node.
~NetEventsInterface()=default
Protected destructor so that instances can only be deleted by derived classes.
virtual void InitializeNode(const CNode &node, ServiceFlags our_services)=0
Initialize a peer (setup state).
static void AddFlag(NetPermissionFlags &flags, NetPermissionFlags f)
static bool HasFlag(NetPermissionFlags flags, NetPermissionFlags f)
RAII helper class that manages a socket and closes it automatically when it goes out of scope.
The Transport converts one connection's sent messages to wire bytes, and received bytes back.
virtual BytesToSend GetBytesToSend(bool have_next_message) const noexcept=0
Get bytes to send on the wire, if any, along with other information about it.
virtual size_t GetSendMemoryUsage() const noexcept=0
Return the memory usage of this transport attributable to buffered data to send.
virtual bool ReceivedBytes(std::span< const uint8_t > &msg_bytes)=0
Feed wire bytes to the transport.
virtual void MarkBytesSent(size_t bytes_sent) noexcept=0
Report how many bytes returned by the last GetBytesToSend() have been sent.
virtual bool ShouldReconnectV1() const noexcept=0
Whether upon disconnections, a reconnect with V1 is warranted.
virtual CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool &reject_message)=0
Retrieve a completed message from transport.
virtual bool ReceivedMessageComplete() const =0
Returns true if the current message is complete (so GetReceivedMessage can be called).
virtual ~Transport()=default
virtual Info GetInfo() const noexcept=0
Retrieve information about this transport.
std::tuple< std::span< const uint8_t >, bool, const std::string & > BytesToSend
Return type for GetBytesToSend, consisting of:
virtual bool SetMessageToSend(CSerializedNetMsg &msg) noexcept=0
Set the next message to send.
CHash256 hasher GUARDED_BY(m_recv_mutex)
DataStream hdrbuf GUARDED_BY(m_recv_mutex)
bool m_sending_header GUARDED_BY(m_send_mutex)
Whether we're currently sending header bytes or message bytes.
int readData(std::span< const uint8_t > msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Mutex m_send_mutex
Lock for sending state.
CSerializedNetMsg m_message_to_send GUARDED_BY(m_send_mutex)
The data of the message currently being sent.
size_t m_bytes_sent GUARDED_BY(m_send_mutex)
How many bytes have been sent so far (from m_header_to_send, or from m_message_to_send....
unsigned int nDataPos GUARDED_BY(m_recv_mutex)
bool in_data GUARDED_BY(m_recv_mutex)
uint256 data_hash GUARDED_BY(m_recv_mutex)
std::vector< uint8_t > m_header_to_send GUARDED_BY(m_send_mutex)
The header of the message currently being sent.
const MessageStartChars m_magic_bytes
const uint256 & GetMessageHash() const EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
int readHeader(std::span< const uint8_t > msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
unsigned int nHdrPos GUARDED_BY(m_recv_mutex)
DataStream vRecv GUARDED_BY(m_recv_mutex)
bool CompleteInternal() const noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
CMessageHeader hdr GUARDED_BY(m_recv_mutex)
bool ReceivedBytes(std::span< const uint8_t > &msg_bytes) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Feed wire bytes to the transport.
V1Transport(NodeId node_id) noexcept
void Reset() EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
bool ShouldReconnectV1() const noexcept override
Whether upon disconnections, a reconnect with V1 is warranted.
Mutex m_recv_mutex
Lock for receive state.
bool ReceivedMessageComplete() const override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Returns true if the current message is complete (so GetReceivedMessage can be called).
std::vector< uint8_t > m_send_buffer GUARDED_BY(m_send_mutex)
The send buffer; meaning is determined by m_send_state.
bool m_sent_v1_header_worth GUARDED_BY(m_send_mutex)
Whether we've sent at least 24 bytes (which would trigger disconnect for V1 peers).
void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Report how many bytes returned by the last GetBytesToSend() have been sent.
static constexpr uint32_t MAX_GARBAGE_LEN
const NodeId m_nodeid
NodeId (for debug logging).
BIP324Cipher m_cipher
Cipher state.
size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Return the memory usage of this transport attributable to buffered data to send.
void ProcessReceivedMaybeV1Bytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex
Process bytes in m_recv_buffer, while in KEY_MAYBE_V1 state.
SendState
State type that controls the sender side.
V1Transport m_v1_fallback
Encapsulate a V1Transport to fall back to.
Mutex m_send_mutex ACQUIRED_AFTER(m_recv_mutex)
Lock for sending-side fields.
SendState m_send_state GUARDED_BY(m_send_mutex)
Current sender state.
static constexpr size_t V1_PREFIX_LEN
The length of the V1 prefix to match bytes initially received by responders with to determine if thei...
std::string m_send_type GUARDED_BY(m_send_mutex)
Type of the message being sent.
bool ProcessReceivedPacketBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Process bytes in m_recv_buffer, while in VERSION/APP state.
bool ProcessReceivedKeyBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex
Process bytes in m_recv_buffer, while in KEY state.
const bool m_initiating
Whether we are the initiator side.
Info GetInfo() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Retrieve information about this transport.
std::vector< uint8_t > m_recv_buffer GUARDED_BY(m_recv_mutex)
Receive buffer; meaning is determined by m_recv_state.
BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Get bytes to send on the wire, if any, along with other information about it.
std::vector< uint8_t > m_send_garbage GUARDED_BY(m_send_mutex)
The garbage sent, or to be sent (MAYBE_V1 and AWAITING_KEY state only).
bool ProcessReceivedGarbageBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Process bytes in m_recv_buffer, while in GARB_GARBTERM state.
uint32_t m_recv_len GUARDED_BY(m_recv_mutex)
In {VERSION, APP}, the decrypted packet length, if m_recv_buffer.size() >= BIP324Cipher::LENGTH_LEN.
uint32_t m_send_pos GUARDED_BY(m_send_mutex)
How many bytes from the send buffer have been sent so far.
RecvState m_recv_state GUARDED_BY(m_recv_mutex)
Current receiver state.
bool ReceivedMessageComplete() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Returns true if the current message is complete (so GetReceivedMessage can be called).
CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool &reject_message) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Retrieve a completed message from transport.
Mutex m_recv_mutex ACQUIRED_BEFORE(m_send_mutex)
Lock for receiver-side fields.
static constexpr std::array< std::byte, 0 > VERSION_CONTENTS
Contents of the version packet to send.
bool ReceivedBytes(std::span< const uint8_t > &msg_bytes) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex
Feed wire bytes to the transport.
bool ShouldReconnectV1() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex
Whether upon disconnections, a reconnect with V1 is warranted.
std::vector< uint8_t > m_recv_aad GUARDED_BY(m_recv_mutex)
AAD expected in next received packet (currently used only for garbage).
bool SetMessageToSend(CSerializedNetMsg &msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Set the next message to send.
V2Transport(NodeId nodeid, bool initiating) noexcept
Construct a V2 transport with securely generated random keys.
std::vector< uint8_t > m_recv_decode_buffer GUARDED_BY(m_recv_mutex)
Buffer to put decrypted contents in, for converting to CNetMessage.
RecvState
State type that defines the current contents of the receive buffer and/or how the next received bytes...
ConnectionType
Different types of connections to a peer.
@ PRIVATE_BROADCAST
Private broadcast connections are short-lived and only opened to privacy networks (Tor,...
@ BLOCK_RELAY
We use block-relay-only connections to help prevent against partition attacks.
@ MANUAL
We open manual connections to addresses that users explicitly requested via the addnode RPC or the -a...
@ OUTBOUND_FULL_RELAY
These are the default connections that we use to connect with the network.
@ FEELER
Feeler connections are short-lived connections made to check that a node is alive.
@ INBOUND
Inbound connections are those initiated by a peer.
@ ADDR_FETCH
AddrFetch connections are short lived connections used to solicit addresses from peers.
TransportProtocolType
Transport layer version.
@ V1
Unencrypted, plaintext protocol.
std::array< uint8_t, 4 > MessageStartChars
const std::string NET_MESSAGE_TYPE_OTHER
GlobalMutex g_maplocalhost_mutex
std::function< void(const CAddress &addr, const std::string &msg_type, std::span< const unsigned char > data, bool is_incoming)> CaptureMessage
Defaults to CaptureMessageToFile(), but can be overridden by unit tests.
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
static constexpr bool DEFAULT_PRIVATE_BROADCAST
Default for -privatebroadcast.
bool IsLocal(const CService &addr)
check whether a given address is potentially local
void RemoveLocal(const CService &addr)
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
static constexpr std::chrono::minutes TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
static const size_t DEFAULT_MAXSENDBUFFER
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
static constexpr bool DEFAULT_FIXEDSEEDS
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH
Maximum length of incoming protocol messages (no message over 4 MB is currently acceptable).
static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL
Run the extra block-relay-only connection loop once every 5 minutes.
static const size_t DEFAULT_MAXRECEIVEBUFFER
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
static const std::string DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
std::map< std::string, uint64_t > mapMsgTypeSize
static constexpr bool DEFAULT_FORCEDNSSEED
static constexpr size_t MAX_PRIVATE_BROADCAST_CONNECTIONS
Maximum number of private broadcast connections.
static constexpr bool DEFAULT_DNSSEED
CService GetLocalAddress(const CNode &peer)
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
static const bool DEFAULT_LISTEN
-listen default
static constexpr std::chrono::hours ASMAP_HEALTH_CHECK_INTERVAL
Interval for ASMap Health Check.
static constexpr auto FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes.
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
static constexpr bool DEFAULT_V2_TRANSPORT
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
void Discover()
Look up IP addresses from all interfaces on the machine and add them to the list of local addresses t...
bool SeenLocal(const CService &addr)
vote for a local address
constexpr bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
constexpr bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
ServiceFlags
nServices flags
static const int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
Cache responses to addr requests to minimize privacy leak.
std::chrono::microseconds m_cache_entry_expiration
std::vector< CAddress > m_addrs_response_cache
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
ListenSocket(std::shared_ptr< Sock > sock_, NetPermissionFlags permissions_)
NetPermissionFlags m_permissions
std::shared_ptr< Sock > sock
unsigned int nReceiveFloodSize
std::vector< NetWhitebindPermissions > vWhiteBinds
uint64_t nMaxOutboundLimit
CClientUIInterface * uiInterface
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
std::vector< CService > onion_binds
std::vector< std::string > m_specified_outgoing
NetEventsInterface * m_msgproc
std::vector< std::string > m_added_nodes
int64_t m_peer_connect_timeout
std::vector< CService > vBinds
unsigned int nSendBufferMaxSize
int m_max_automatic_connections
ServiceFlags m_local_services
bool m_i2p_accept_incoming
std::vector< std::string > vSeedNodes
bool m_use_addrman_outgoing
bool whitelist_forcerelay
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Struct for entries in m_reconnections.
CountingSemaphoreGrant grant
NetPermissionFlags permission_flags
std::unique_ptr< i2p::sam::Session > i2p_sam_session
CSerializedNetMsg(const CSerializedNetMsg &msg)=delete
CSerializedNetMsg Copy() const
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
CSerializedNetMsg & operator=(const CSerializedNetMsg &)=delete
CSerializedNetMsg()=default
CSerializedNetMsg(CSerializedNetMsg &&)=default
std::vector< unsigned char > data
size_t GetMemoryUsage() const noexcept
Compute total memory usage of this object (own memory + any dynamic memory).
std::optional< uint256 > session_id
TransportProtocolType transport_type
#define AssertLockNotHeld(cs)
AnnotatedMixin< std::mutex > Mutex
Wrapped mutex: supports waiting but not recursive locking.
AnnotatedMixin< std::recursive_mutex > RecursiveMutex
Wrapped mutex: supports recursive locking, but no waiting TODO: We should move away from using the re...
#define WITH_LOCK(cs, code)
#define AssertLockHeld(cs)
#define EXCLUSIVE_LOCKS_REQUIRED(...)