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.
1// Copyright (c) 2009-2010 Satoshi Nakamoto2// Copyright (c) 2009-present The Bitcoin Core developers3// Distributed under the MIT software license, see the accompanying4// file COPYING or http://www.opensource.org/licenses/mit-license.php.6#ifndef BITCOIN_NET_PROCESSING_H7#define BITCOIN_NET_PROCESSING_H9#include <consensus/amount.h>10#include <net.h>11#include <node/txorphanage.h>12#include <node/types.h>13#include <private_broadcast.h>14#include <protocol.h>15#include <uint256.h>16#include <util/expected.h>17#include <validationinterface.h>19#include <atomic>20#include <chrono>21#include <cstdint>22#include <memory>23#include <optional>24#include <string>25#include <vector>27class AddrMan;28class CTxMemPool;29class ChainstateManager;30class BanMan;31class CBlockIndex;32class CScheduler;33class DataStream;34class uint256;36namespace node {37class Warnings;38} // namespace node40/** Whether transaction reconciliation protocol should be enabled by default. */41inline constexpr bool DEFAULT_TXRECONCILIATION_ENABLE{false};42/** Default number of non-mempool transactions to keep around for block reconstruction. Includes43orphan, replaced, and rejected transactions. */44inline constexpr uint32_t DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN{100};45/** Default maximum per-second rate for sending transaction inventory to peers. */46inline constexpr unsigned int DEFAULT_TX_SEND_RATE{14};47inline constexpr bool DEFAULT_PEERBLOOMFILTERS = false;48inline constexpr bool DEFAULT_PEERBLOCKFILTERS = false;49/** Maximum number of outstanding CMPCTBLOCK requests for the same block. */50inline constexpr unsigned int MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK = 3;51/** Number of headers sent in one getheaders result. We rely on the assumption that if a peer sends52* less than this number, we reached its tip. Changing this value is a protocol upgrade. */53inline constexpr unsigned int MAX_HEADERS_RESULTS = 2000;54/** The compactblocks version we support. See BIP 152. */55inline constexpr uint64_t CMPCTBLOCKS_VERSION{2};57struct CNodeStateStats {58int nSyncHeight = -1;59int nCommonHeight = -1;60NodeClock::duration m_ping_wait;61std::vector<int> vHeightInFlight;62bool m_relay_txs;63int m_inv_to_send = 0;64uint64_t m_last_inv_seq{0};65CAmount m_fee_filter_received;66uint64_t m_addr_processed = 0;67uint64_t m_addr_rate_limited = 0;68bool m_addr_relay_enabled{false};69ServiceFlags their_services;70int64_t presync_height{-1};71std::chrono::seconds time_offset{0};72};74struct PeerManagerInfo {75struct InvBucketInfo {76size_t backlog_count{0};77double count_bucket{0};78double size_bucket{0};79};81std::chrono::seconds median_outbound_time_offset{0s};82bool ignores_incoming_txs{false};83bool private_broadcast{DEFAULT_PRIVATE_BROADCAST};84unsigned int tx_send_rate{0};85InvBucketInfo inbound_bucket;86InvBucketInfo outbound_bucket;87};89class PeerManager : public CValidationInterface, public NetEventsInterface90{91public:92struct Options {93//! Whether this node is running in -blocksonly mode94bool ignore_incoming_txs{DEFAULT_BLOCKSONLY};95//! Whether transaction reconciliation protocol is enabled96bool reconcile_txs{DEFAULT_TXRECONCILIATION_ENABLE};97//! Number of non-mempool transactions to keep around for block reconstruction. Includes98//! orphan, replaced, and rejected transactions.99uint32_t max_extra_txs{DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN};100//! Whether all P2P messages are captured to disk101bool capture_messages{false};102//! Whether or not the internal RNG behaves deterministically (this is103//! a test-only option).104bool deterministic_rng{false};105//! Number of headers sent in one getheaders message result (this is106//! a test-only option).107uint32_t max_headers_result{MAX_HEADERS_RESULTS};108//! Whether private broadcast is used for sending transactions.109bool private_broadcast{DEFAULT_PRIVATE_BROADCAST};110//! Maximum per-second rate for sending transaction inventory to peers.111unsigned int tx_send_rate{DEFAULT_TX_SEND_RATE};112};114static std::unique_ptr<PeerManager> make(CConnman& connman, AddrMan& addrman,115BanMan* banman, ChainstateManager& chainman,116CTxMemPool& pool, node::Warnings& warnings, Options opts);117virtual ~PeerManager() = default;119/**120* Attempt to manually fetch block from a given peer. We must already have the header.121*122* @param[in] peer_id The peer id123* @param[in] block_index The blockindex124*/125virtual util::Expected<void, std::string> FetchBlock(NodeId peer_id, const CBlockIndex& block_index) = 0;127/** Begin running background tasks, should only be called once */128virtual void StartScheduledTasks(CScheduler& scheduler) = 0;130/** Get statistics from node state */131virtual bool GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) const = 0;133virtual std::vector<node::TxOrphanage::OrphanInfo> GetOrphanTransactions() = 0;135/** Get peer manager info. */136virtual PeerManagerInfo GetInfo() const = 0;138/** Get info about transactions currently being privately broadcast. */139virtual std::vector<PrivateBroadcast::TxBroadcastInfo> GetPrivateBroadcastInfo() const = 0;141/**142* Abort private broadcast attempts for transactions currently being privately broadcast.143*144* @param[in] id A transaction identifier. It will be matched against both txid and wtxid for145* all transactions in the private broadcast queue.146*147* @return Transactions removed from the private broadcast queue. If the provided id matches a148* txid that corresponds to multiple transactions with different wtxids, multiple149* transactions may be returned.150*/151virtual std::vector<CTransactionRef> AbortPrivateBroadcast(const uint256& id) = 0;153/**154* Initiate a transaction broadcast to eligible peers.155* Queue the witness transaction id to the inbound and outbound inv backlogs.156* Later, depending on `-txsendrate`, `Peer::TxRelay::m_next_inv_send_time` and if157* the transaction is in the mempool, an `INV` about it may be sent to the peer.158*/159virtual void InitiateTxBroadcastToAll(const Wtxid& wtxid) = 0;161/**162* Initiate a private transaction broadcast. This is done163* asynchronously via short-lived connections to peers on privacy networks.164* @retval node::TransactionError::OK The transaction is scheduled for private broadcast (or was already scheduled).165* @retval node::TransactionError::PRIVATE_BROADCAST_FULL Rejected because the private broadcast queue is full.166*/167[[nodiscard]] virtual node::TransactionError InitiateTxBroadcastPrivate(const CTransactionRef& tx) = 0;169/** Send ping message to all peers */170virtual void SendPings() = 0;172/** Set the height of the best block and its time (seconds since epoch). */173virtual void SetBestBlock(int height, std::chrono::seconds time) = 0;175/* Public for unit testing. */176virtual void UnitTestMisbehaving(NodeId peer_id) = 0;178/**179* Evict extra outbound peers. If we think our tip may be stale, connect to an extra outbound.180* Public for unit testing.181*/182virtual void CheckForStaleTipAndEvictPeers() = 0;184/** This function is used for testing the stale tip eviction logic, see denialofservice_tests.cpp */185virtual void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds) = 0;187/**188* Gets the set of service flags which are "desirable" for a given peer.189*190* These are the flags which are required for a peer to support for them191* to be "interesting" to us, ie for us to wish to use one of our few192* outbound connection slots for or for us to wish to prioritize keeping193* their connection around.194*195* Relevant service flags may be peer- and state-specific in that the196* version of the peer may determine which flags are required (eg in the197* case of NODE_NETWORK_LIMITED where we seek out NODE_NETWORK peers198* unless they set NODE_NETWORK_LIMITED and we are out of IBD, in which199* case NODE_NETWORK_LIMITED suffices).200*201* Thus, generally, avoid calling with 'services' == NODE_NONE, unless202* state-specific flags must absolutely be avoided. When called with203* 'services' == NODE_NONE, the returned desirable service flags are204* guaranteed to not change dependent on state - ie they are suitable for205* use when describing peers which we know to be desirable, but for which206* we do not have a confirmed set of service flags.207*/208virtual ServiceFlags GetDesirableServiceFlags(ServiceFlags services) const = 0;209};211#endif // BITCOIN_NET_PROCESSING_H
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.