Inside Bitcoin
Opening the selected file…
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#include <net_processing.h>8#include <addrman.h>9#include <arith_uint256.h>10#include <banman.h>11#include <blockencodings.h>12#include <blockfilter.h>13#include <chain.h>14#include <chainparams.h>15#include <common/bloom.h>16#include <consensus/amount.h>17#include <consensus/params.h>18#include <consensus/validation.h>19#include <core_memusage.h>20#include <crypto/siphash.h>21#include <deploymentstatus.h>22#include <flatfile.h>23#include <headerssync.h>24#include <index/blockfilterindex.h>25#include <kernel/types.h>26#include <logging.h>27#include <merkleblock.h>28#include <net.h>29#include <net_permissions.h>30#include <netaddress.h>31#include <netbase.h>32#include <netmessagemaker.h>33#include <node/blockstorage.h>34#include <node/connection_types.h>35#include <node/protocol_version.h>36#include <node/timeoffsets.h>37#include <node/txdownloadman.h>38#include <node/txorphanage.h>39#include <node/txreconciliation.h>40#include <node/warnings.h>41#include <policy/feerate.h>42#include <policy/fees/block_policy_estimator.h>43#include <policy/packages.h>44#include <policy/policy.h>45#include <primitives/block.h>46#include <primitives/transaction.h>47#include <private_broadcast.h>48#include <protocol.h>49#include <random.h>50#include <scheduler.h>51#include <script/script.h>52#include <serialize.h>53#include <span.h>54#include <streams.h>55#include <sync.h>56#include <tinyformat.h>57#include <txmempool.h>58#include <uint256.h>59#include <util/check.h>60#include <util/hasher.h>61#include <util/strencodings.h>62#include <util/time.h>63#include <util/tokenbucket.h>64#include <util/trace.h>65#include <validation.h>67#include <algorithm>68#include <array>69#include <atomic>70#include <compare>71#include <cstddef>72#include <deque>73#include <exception>74#include <functional>75#include <future>76#include <initializer_list>77#include <iterator>78#include <limits>79#include <list>80#include <map>81#include <memory>82#include <optional>83#include <queue>84#include <ranges>85#include <ratio>86#include <set>87#include <span>88#include <typeinfo>89#include <unordered_set>90#include <utility>92using kernel::ChainstateRole;93using namespace util::hex_literals;95TRACEPOINT_SEMAPHORE(net, inbound_message);96TRACEPOINT_SEMAPHORE(net, misbehaving_connection);98/** Headers download timeout.99* Timeout = base + per_header * (expected number of headers) */100static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_BASE = 15min;101static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER = 1ms;102/** How long to wait for a peer to respond to a getheaders request */103static constexpr auto HEADERS_RESPONSE_TIME{2min};104/** Protect at least this many outbound peers from disconnection due to slow/105* behind headers chain.106*/107static constexpr int32_t MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT = 4;108/** Timeout for (unprotected) outbound peers to sync to our chainwork */109static constexpr auto CHAIN_SYNC_TIMEOUT{20min};110/** How frequently to check for stale tips */111static constexpr auto STALE_CHECK_INTERVAL{10min};112/** How frequently to check for extra outbound peers and disconnect */113static constexpr auto EXTRA_PEER_CHECK_INTERVAL{45s};114/** Minimum time an outbound-peer-eviction candidate must be connected for, in order to evict */115static constexpr auto MINIMUM_CONNECT_TIME{30s};116/** SHA256("main address relay")[0:8] */117static constexpr uint64_t RANDOMIZER_ID_ADDRESS_RELAY = 0x3cac0035b5866b90ULL;118/// Age after which a stale block will no longer be served if requested as119/// protection against fingerprinting. Set to one month, denominated in seconds.120static constexpr int STALE_RELAY_AGE_LIMIT = 30 * 24 * 60 * 60;121/// Age after which a block is considered historical for purposes of rate122/// limiting block relay. Set to one week, denominated in seconds.123static constexpr int HISTORICAL_BLOCK_AGE = 7 * 24 * 60 * 60;124/** Time between pings automatically sent out for latency probing and keepalive */125static constexpr auto PING_INTERVAL{2min};126/** The maximum number of entries in a locator */127static const unsigned int MAX_LOCATOR_SZ = 101;128/** The maximum number of entries in an 'inv' protocol message */129static const unsigned int MAX_INV_SZ = 50000;130/** Limit to avoid sending big packets. Not used in processing incoming GETDATA for compatibility */131static const unsigned int MAX_GETDATA_SZ = 1000;132/** Number of blocks that can be requested at any given time from a single peer. */133static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16;134/** Default time during which a peer must stall block download progress before being disconnected.135* the actual timeout is increased temporarily if peers are disconnected for hitting the timeout */136static constexpr auto BLOCK_STALLING_TIMEOUT_DEFAULT{2s};137/** Maximum timeout for stalling block download. */138static constexpr auto BLOCK_STALLING_TIMEOUT_MAX{64s};139/** Maximum depth of blocks we're willing to serve as compact blocks to peers140* when requested. For older blocks, a regular BLOCK response will be sent. */141static const int MAX_CMPCTBLOCK_DEPTH = 5;142/** Maximum depth of blocks we're willing to respond to GETBLOCKTXN requests for. */143static const int MAX_BLOCKTXN_DEPTH = 10;144static_assert(MAX_BLOCKTXN_DEPTH <= MIN_BLOCKS_TO_KEEP, "MAX_BLOCKTXN_DEPTH too high");145/** Size of the "block download window": how far ahead of our current height do we fetch?146* Larger windows tolerate larger download speed differences between peer, but increase the potential147* degree of disordering of blocks on disk (which make reindexing and pruning harder). We'll probably148* want to make this a per-peer adaptive value at some point. */149static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024;150/** Block download timeout base, expressed in multiples of the block interval (i.e. 10 min) */151static constexpr double BLOCK_DOWNLOAD_TIMEOUT_BASE = 1;152/** Additional block download timeout per parallel downloading peer (i.e. 5 min) */153static constexpr double BLOCK_DOWNLOAD_TIMEOUT_PER_PEER = 0.5;154/** Maximum number of headers to announce when relaying blocks with headers message.*/155static const unsigned int MAX_BLOCKS_TO_ANNOUNCE = 8;156/** Minimum blocks required to signal NODE_NETWORK_LIMITED */157static const unsigned int NODE_NETWORK_LIMITED_MIN_BLOCKS = 288;158/** Window, in blocks, for connecting to NODE_NETWORK_LIMITED peers */159static const unsigned int NODE_NETWORK_LIMITED_ALLOW_CONN_BLOCKS = 144;160/** Average delay between local address broadcasts */161static constexpr auto AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL{24h};162/** Average delay between peer address broadcasts */163static constexpr auto AVG_ADDRESS_BROADCAST_INTERVAL{30s};164/** Delay between rotating the peers we relay a particular address to */165static constexpr auto ROTATE_ADDR_RELAY_DEST_INTERVAL{24h};166/** Average delay between trickled inventory transmissions for inbound peers.167* Blocks and peers with NetPermissionFlags::NoBan permission bypass this. */168static constexpr auto INBOUND_INVENTORY_BROADCAST_INTERVAL{5s};169/** Average delay between trickled inventory transmissions for outbound peers.170* Use a smaller delay as there is less privacy concern for them.171* Blocks and peers with NetPermissionFlags::NoBan permission bypass this. */172static constexpr auto OUTBOUND_INVENTORY_BROADCAST_INTERVAL{2s};173/** Multiplier for the inventory bucket rate for outbounds */174static constexpr double OUTBOUND_INVENTORY_BUCKET_MULTIPLIER{Ticks<SecondsDouble>(INBOUND_INVENTORY_BROADCAST_INTERVAL) / Ticks<SecondsDouble>(OUTBOUND_INVENTORY_BROADCAST_INTERVAL)};175/** Delay between checking inventory bucket and backlog */176static constexpr auto INVENTORY_BUCKET_CHECK_DELAY{100ms};177/** Empty backlog target capacity */178static constexpr size_t INVENTORY_BUCKET_BACKLOG_CAPACITY{300};179/** Delay between inventory bucket backlog heartbeat log entries */180static constexpr auto INVENTORY_BUCKET_BACKLOG_HEARTBEAT{2000ms};181/** Minimum backlog to trigger heartbeat log entries */182static constexpr size_t INVENTORY_BUCKET_BACKLOG_HEARTBEAT_MIN{100};183/** Average delay between feefilter broadcasts in seconds. */184static constexpr auto AVG_FEEFILTER_BROADCAST_INTERVAL{10min};185/** Maximum feefilter broadcast delay after significant change. */186static constexpr auto MAX_FEEFILTER_CHANGE_DELAY{5min};187/** Maximum number of compact filters that may be requested with one getcfilters. See BIP 157. */188static constexpr uint32_t MAX_GETCFILTERS_SIZE = 1000;189/** Maximum number of cf hashes that may be requested with one getcfheaders. See BIP 157. */190static constexpr uint32_t MAX_GETCFHEADERS_SIZE = 2000;191/** the maximum percentage of addresses from our addrman to return in response to a getaddr message. */192static constexpr size_t MAX_PCT_ADDR_TO_SEND = 23;193/** The maximum number of address records permitted in an ADDR message. */194static constexpr size_t MAX_ADDR_TO_SEND{1000};195/** The maximum rate of address records we're willing to process on average. Can be bypassed using196* the NetPermissionFlags::Addr permission. */197static constexpr double MAX_ADDR_RATE_PER_SECOND{0.1};198/** The soft limit of the address processing token bucket (the regular MAX_ADDR_RATE_PER_SECOND199* based increments won't go above this, but the MAX_ADDR_TO_SEND increment following GETADDR200* is exempt from this limit). */201static constexpr size_t MAX_ADDR_PROCESSING_TOKEN_BUCKET{MAX_ADDR_TO_SEND};202/** Private broadcast connections must complete within this time. Disconnect the peer if it takes longer. */203static constexpr auto PRIVATE_BROADCAST_MAX_CONNECTION_LIFETIME{3min};205// Internal stuff206namespace {207/** Blocks that are in flight, and that are in the queue to be downloaded. */208struct QueuedBlock {209/** BlockIndex. We must have this since we only request blocks when we've already validated the header. */210const CBlockIndex* pindex;211/** Optional, used for CMPCTBLOCK downloads */212std::unique_ptr<PartiallyDownloadedBlock> partialBlock;213};215/**216* Data structure for an individual peer. This struct is not protected by217* cs_main since it does not contain validation-critical data.218*219* Memory is owned by shared pointers and this object is destructed when220* the refcount drops to zero.221*222* Mutexes inside this struct must not be held when locking m_peer_mutex.223*224* TODO: move most members from CNodeState to this structure.225* TODO: move remaining application-layer data members from CNode to this structure.226*/227struct Peer {228/** Same id as the CNode object for this peer */229const NodeId m_id{0};231/** Services we offered to this peer.232*233* This is supplied by CConnman during peer initialization. It's const234* because there is no protocol defined for renegotiating services235* initially offered to a peer. The set of local services we offer should236* not change after initialization.237*238* An interesting example of this is NODE_NETWORK and initial block239* download: a node which starts up from scratch doesn't have any blocks240* to serve, but still advertises NODE_NETWORK because it will eventually241* fulfill this role after IBD completes. P2P code is written in such a242* way that it can gracefully handle peers who don't make good on their243* service advertisements. */244const ServiceFlags m_our_services;245/** Services this peer offered to us. */246std::atomic<ServiceFlags> m_their_services{NODE_NONE};248//! Whether this peer is an inbound connection249const bool m_is_inbound;