Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
251/** Protects misbehavior data members */252Mutex m_misbehavior_mutex;253/** Whether this peer should be disconnected and marked as discouraged (unless it has NetPermissionFlags::NoBan permission). */254bool m_should_discourage GUARDED_BY(m_misbehavior_mutex){false};256/** Protects block inventory data members */257Mutex m_block_inv_mutex;258/** List of blocks that we'll announce via an `inv` message.259* There is no final sorting before sending, as they are always sent260* immediately and in the order requested. */261std::vector<uint256> m_blocks_for_inv_relay GUARDED_BY(m_block_inv_mutex);262/** Unfiltered list of blocks that we'd like to announce via a `headers`263* message. If we can't announce via a `headers` message, we'll fall back to264* announcing via `inv`. */265std::vector<uint256> m_blocks_for_headers_relay GUARDED_BY(m_block_inv_mutex);266/** The final block hash that we sent in an `inv` message to this peer.267* When the peer requests this block, we send an `inv` message to trigger268* the peer to request the next sequence of block hashes.269* Most peers use headers-first syncing, which doesn't use this mechanism */270uint256 m_continuation_block GUARDED_BY(m_block_inv_mutex) {};272/** Set to true once initial VERSION message was sent (only relevant for outbound peers). */273bool m_outbound_version_message_sent GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false};275/** The pong reply we're expecting, or 0 if no pong expected. */276std::atomic<uint64_t> m_ping_nonce_sent{0};277/** When the last ping was sent, or 0 if no ping was ever sent */278std::atomic<NodeClock::time_point> m_ping_start{NodeClock::epoch};279/** Whether a ping has been requested by the user */280std::atomic<bool> m_ping_queued{false};282/** Whether this peer relays txs via wtxid */283std::atomic<bool> m_wtxid_relay{false};284/** The feerate in the most recent BIP133 `feefilter` message sent to the peer.285* It is *not* a p2p protocol violation for the peer to send us286* transactions with a lower fee rate than this. See BIP133. */287CAmount m_fee_filter_sent GUARDED_BY(NetEventsInterface::g_msgproc_mutex){0};288/** Timestamp after which we will send the next BIP133 `feefilter` message289* to the peer. */290std::chrono::microseconds m_next_send_feefilter GUARDED_BY(NetEventsInterface::g_msgproc_mutex){0};292struct TxRelay {293mutable RecursiveMutex m_bloom_filter_mutex;294/** Whether we relay transactions to this peer. */295bool m_relay_txs GUARDED_BY(m_bloom_filter_mutex){false};296/** A bloom filter for which transactions to announce to the peer. See BIP37. */297std::unique_ptr<CBloomFilter> m_bloom_filter PT_GUARDED_BY(m_bloom_filter_mutex) GUARDED_BY(m_bloom_filter_mutex){nullptr};299mutable RecursiveMutex m_tx_inventory_mutex;300/** A filter of all the (w)txids that the peer has announced to301* us or we have announced to the peer. We use this to avoid announcing302* the same (w)txid to a peer that already has the transaction. */303CRollingBloomFilter m_tx_inventory_known_filter GUARDED_BY(m_tx_inventory_mutex){50000, 0.000001};304/** Vector of wtxids we still have to announce. For non-wtxid-relay peers,305* we retrieve the txid from the corresponding mempool transaction when306* constructing the `inv` message. We use the mempool to sort transactions307* in dependency order before relay, so this does not have to be sorted. */308std::vector<Wtxid> m_tx_inventory_to_send GUARDED_BY(m_tx_inventory_mutex);309/** Whether the peer has requested us to send our complete mempool. Only310* permitted if the peer has NetPermissionFlags::Mempool or we advertise311* NODE_BLOOM. See BIP35. */312bool m_send_mempool GUARDED_BY(m_tx_inventory_mutex){false};313/** The next time after which we will send an `inv` message containing314* transaction announcements to this peer. */315std::chrono::microseconds m_next_inv_send_time GUARDED_BY(m_tx_inventory_mutex){0};316/** The mempool sequence num at which we sent the last `inv` message to this peer.317* Can relay txs with lower sequence numbers than this (see CTxMempool::info_for_relay). */318uint64_t m_last_inv_sequence GUARDED_BY(m_tx_inventory_mutex){1};320/** Minimum fee rate with which to filter transaction announcements to this node. See BIP133. */321std::atomic<CAmount> m_fee_filter_received{0};322};324/* Initializes a TxRelay struct for this peer. Can be called at most once for a peer. */325TxRelay* SetTxRelay() EXCLUSIVE_LOCKS_REQUIRED(!m_tx_relay_mutex)326{327LOCK(m_tx_relay_mutex);328Assume(!m_tx_relay);329m_tx_relay = std::make_unique<Peer::TxRelay>();330return m_tx_relay.get();331};333TxRelay* GetTxRelay() EXCLUSIVE_LOCKS_REQUIRED(!m_tx_relay_mutex)334{335return WITH_LOCK(m_tx_relay_mutex, return m_tx_relay.get());336};338/** A vector of addresses to send to the peer, limited to MAX_ADDR_TO_SEND. */339std::vector<CAddress> m_addrs_to_send GUARDED_BY(NetEventsInterface::g_msgproc_mutex);340/** Probabilistic filter to track recent addr messages relayed with this341* peer. Used to avoid relaying redundant addresses to this peer.342*343* We initialize this filter for outbound peers (other than344* block-relay-only connections) or when an inbound peer sends us an345* address related message (ADDR, ADDRV2, GETADDR).346*347* Presence of this filter must correlate with m_addr_relay_enabled.348**/349std::unique_ptr<CRollingBloomFilter> m_addr_known GUARDED_BY(NetEventsInterface::g_msgproc_mutex);350/** Whether we are participating in address relay with this connection.351*352* We set this bool to true for outbound peers (other than353* block-relay-only connections), or when an inbound peer sends us an354* address related message (ADDR, ADDRV2, GETADDR).355*356* We use this bool to decide whether a peer is eligible for gossiping357* addr messages. This avoids relaying to peers that are unlikely to358* forward them, effectively blackholing self announcements. Reasons359* peers might support addr relay on the link include that they connected360* to us as a block-relay-only peer or they are a light client.361*362* This field must correlate with whether m_addr_known has been363* initialized.*/364std::atomic_bool m_addr_relay_enabled{false};365/** Whether a getaddr request to this peer is outstanding. */366bool m_getaddr_sent GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false};367/** Guards address sending timers. */368mutable Mutex m_addr_send_times_mutex;369/** Time point to send the next ADDR message to this peer. */370std::chrono::microseconds m_next_addr_send GUARDED_BY(m_addr_send_times_mutex){0};371/** Time point to possibly re-announce our local address to this peer. */372std::chrono::microseconds m_next_local_addr_send GUARDED_BY(m_addr_send_times_mutex){0};373/** Whether the peer has signaled support for receiving ADDRv2 (BIP155)374* messages, indicating a preference to receive ADDRv2 instead of ADDR ones. */375std::atomic_bool m_wants_addrv2{false};376/** Whether this peer has already sent us a getaddr message. */377bool m_getaddr_recvd GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false};378/** Number of addresses that can be processed from this peer. Start at 1 to379* permit self-announcement. */380double m_addr_token_bucket GUARDED_BY(NetEventsInterface::g_msgproc_mutex){1.0};381/** When m_addr_token_bucket was last updated */382NodeClock::time_point m_addr_token_timestamp GUARDED_BY(NetEventsInterface::g_msgproc_mutex){NodeClock::now()};383/** Total number of addresses that were dropped due to rate limiting. */384std::atomic<uint64_t> m_addr_rate_limited{0};385/** Total number of addresses that were processed (excludes rate-limited ones). */386std::atomic<uint64_t> m_addr_processed{0};388/** Whether we've sent this peer a getheaders in response to an inv prior to initial-headers-sync completing */389bool m_inv_triggered_getheaders_before_sync GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false};391/** Protects m_getdata_requests **/392Mutex m_getdata_requests_mutex;393/** Work queue of items requested by this peer **/394std::deque<CInv> m_getdata_requests GUARDED_BY(m_getdata_requests_mutex);396/** Time of the last getheaders message to this peer */397NodeClock::time_point m_last_getheaders_timestamp GUARDED_BY(NetEventsInterface::g_msgproc_mutex){};399/** Protects m_headers_sync **/400Mutex m_headers_sync_mutex;401/** Headers-sync state for this peer (eg for initial sync, or syncing large402* reorgs) **/403std::unique_ptr<HeadersSyncState> m_headers_sync PT_GUARDED_BY(m_headers_sync_mutex) GUARDED_BY(m_headers_sync_mutex) {};405/** Whether we've sent our peer a sendheaders message. **/406std::atomic<bool> m_sent_sendheaders{false};408/** When to potentially disconnect peer for stalling headers download */409std::chrono::microseconds m_headers_sync_timeout GUARDED_BY(NetEventsInterface::g_msgproc_mutex){0us};411/** Whether this peer wants invs or headers (when possible) for block announcements */412bool m_prefers_headers GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false};414/** Time offset computed during the version handshake based on the415* timestamp the peer sent in the version message. */416std::atomic<std::chrono::seconds> m_time_offset{0s};418explicit Peer(NodeId id, ServiceFlags our_services, bool is_inbound)419: m_id{id}420, m_our_services{our_services}421, m_is_inbound{is_inbound}422{}424private:425mutable Mutex m_tx_relay_mutex;427/** Transaction relay data. May be a nullptr. */428std::unique_ptr<TxRelay> m_tx_relay GUARDED_BY(m_tx_relay_mutex);429};431using PeerRef = std::shared_ptr<Peer>;433/**434* Maintain validation-specific state about nodes, protected by cs_main, instead435* by CNode's own locks. This simplifies asynchronous operation, where436* processing of incoming data is done after the ProcessMessage call returns,437* and we're no longer holding the node's locks.438*/439struct CNodeState {440//! The best known block we know this peer has announced.441const CBlockIndex* pindexBestKnownBlock{nullptr};442//! The hash of the last unknown block this peer has announced.443uint256 hashLastUnknownBlock{};444//! The last full block we both have.445const CBlockIndex* pindexLastCommonBlock{nullptr};446//! The best header we have sent our peer.447const CBlockIndex* pindexBestHeaderSent{nullptr};448//! Whether we've started headers synchronization with this peer.449bool fSyncStarted{false};450//! Since when we're stalling block download progress (in microseconds), or 0.451std::chrono::microseconds m_stalling_since{0us};452std::list<QueuedBlock> vBlocksInFlight;453//! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty.454std::chrono::microseconds m_downloading_since{0us};455//! Whether we consider this a preferred download peer.456bool fPreferredDownload{false};457/** Whether this peer wants invs or cmpctblocks (when possible) for block announcements. */458bool m_requested_hb_cmpctblocks{false};459/** Whether this peer will send us cmpctblocks if we request them. */460bool m_provides_cmpctblocks{false};462/** State used to enforce CHAIN_SYNC_TIMEOUT and EXTRA_PEER_CHECK_INTERVAL logic.463*464* Both are only in effect for outbound, non-manual, non-protected connections.465* Any peer protected (m_protect = true) is not chosen for eviction. A peer is466* marked as protected if all of these are true:467* - its connection type is IsBlockOnlyConn() == false468* - it gave us a valid connecting header469* - we haven't reached MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT yet470* - its chain tip has at least as much work as ours471*472* CHAIN_SYNC_TIMEOUT: if a peer's best known block has less work than our tip,473* set a timeout CHAIN_SYNC_TIMEOUT in the future:474* - If at timeout their best known block now has more work than our tip475* when the timeout was set, then either reset the timeout or clear it476* (after comparing against our current tip's work)477* - If at timeout their best known block still has less work than our478* tip did when the timeout was set, then send a getheaders message,479* and set a shorter timeout, HEADERS_RESPONSE_TIME seconds in future.480* If their best known block is still behind when that new timeout is481* reached, disconnect.482*483* EXTRA_PEER_CHECK_INTERVAL: after each interval, if we have too many outbound peers,484* drop the outbound one that least recently announced us a new block.485*/486struct ChainSyncTimeoutState {487//! A timeout used for checking whether our peer has sufficiently synced488std::chrono::seconds m_timeout{0s};489//! A header with the work we require on our peer's chain490const CBlockIndex* m_work_header{nullptr};491//! After timeout is reached, set to true after sending getheaders492bool m_sent_getheaders{false};493//! Whether this peer is protected from disconnection due to a bad/slow chain494bool m_protect{false};495};497ChainSyncTimeoutState m_chain_sync;499//! Time of last new block announcement500int64_t m_last_block_announcement{0};