Coverage Report

Created: 2026-10-07 13:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/net_processing.h
Line
Count
Source
1
// Copyright (c) 2009-2010 Satoshi Nakamoto
2
// Copyright (c) 2009-present The Bitcoin Core developers
3
// Distributed under the MIT software license, see the accompanying
4
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6
#ifndef BITCOIN_NET_PROCESSING_H
7
#define BITCOIN_NET_PROCESSING_H
8
9
#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>
18
19
#include <atomic>
20
#include <chrono>
21
#include <cstdint>
22
#include <memory>
23
#include <optional>
24
#include <string>
25
#include <vector>
26
27
class AddrMan;
28
class CTxMemPool;
29
class ChainstateManager;
30
class BanMan;
31
class CBlockIndex;
32
class CScheduler;
33
class DataStream;
34
class uint256;
35
36
namespace node {
37
class Warnings;
38
} // namespace node
39
40
/** Whether transaction reconciliation protocol should be enabled by default. */
41
inline constexpr bool DEFAULT_TXRECONCILIATION_ENABLE{false};
42
/** Default number of non-mempool transactions to keep around for block reconstruction. Includes
43
    orphan, replaced, and rejected transactions. */
44
inline constexpr uint32_t DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN{100};
45
/** Default maximum per-second rate for sending transaction inventory to peers. */
46
inline constexpr unsigned int DEFAULT_TX_SEND_RATE{14};
47
inline constexpr bool DEFAULT_PEERBLOOMFILTERS = false;
48
inline constexpr bool DEFAULT_PEERBLOCKFILTERS = false;
49
/** Maximum number of outstanding CMPCTBLOCK requests for the same block. */
50
inline 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 sends
52
 *  less than this number, we reached its tip. Changing this value is a protocol upgrade. */
53
inline constexpr unsigned int MAX_HEADERS_RESULTS = 2000;
54
/** The compactblocks version we support. See BIP 152. */
55
inline constexpr uint64_t CMPCTBLOCKS_VERSION{2};
56
57
struct CNodeStateStats {
58
    int nSyncHeight = -1;
59
    int nCommonHeight = -1;
60
    NodeClock::duration m_ping_wait;
61
    std::vector<int> vHeightInFlight;
62
    bool m_relay_txs;
63
    int m_inv_to_send = 0;
64
    uint64_t m_last_inv_seq{0};
65
    CAmount m_fee_filter_received;
66
    uint64_t m_addr_processed = 0;
67
    uint64_t m_addr_rate_limited = 0;
68
    bool m_addr_relay_enabled{false};
69
    ServiceFlags their_services;
70
    int64_t presync_height{-1};
71
    std::chrono::seconds time_offset{0};
72
    NodeClock::time_point m_last_block_announcement;
73
};
74
75
struct PeerManagerInfo {
76
    struct InvBucketInfo {
77
        size_t backlog_count{0};
78
        double count_bucket{0};
79
        double size_bucket{0};
80
    };
81
82
    std::chrono::seconds median_outbound_time_offset{0s};
83
    bool ignores_incoming_txs{false};
84
    bool private_broadcast{DEFAULT_PRIVATE_BROADCAST};
85
    unsigned int tx_send_rate{0};
86
    InvBucketInfo inbound_bucket;
87
    InvBucketInfo outbound_bucket;
88
};
89
90
class PeerManager : public CValidationInterface, public NetEventsInterface
91
{
92
public:
93
    struct Options {
94
        //! Whether this node is running in -blocksonly mode
95
        bool ignore_incoming_txs{DEFAULT_BLOCKSONLY};
96
        //! Whether transaction reconciliation protocol is enabled
97
        bool reconcile_txs{DEFAULT_TXRECONCILIATION_ENABLE};
98
        //! Number of non-mempool transactions to keep around for block reconstruction. Includes
99
        //! orphan, replaced, and rejected transactions.
100
        uint32_t max_extra_txs{DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN};
101
        //! Whether all P2P messages are captured to disk
102
        bool capture_messages{false};
103
        //! Whether or not the internal RNG behaves deterministically (this is
104
        //! a test-only option).
105
        bool deterministic_rng{false};
106
        //! Number of headers sent in one getheaders message result (this is
107
        //! a test-only option).
108
        uint32_t max_headers_result{MAX_HEADERS_RESULTS};
109
        //! Whether private broadcast is used for sending transactions.
110
        bool private_broadcast{DEFAULT_PRIVATE_BROADCAST};
111
        //! Maximum per-second rate for sending transaction inventory to peers.
112
        unsigned int tx_send_rate{DEFAULT_TX_SEND_RATE};
113
    };
114
115
    static std::unique_ptr<PeerManager> make(CConnman& connman, AddrMan& addrman,
116
                                             BanMan* banman, ChainstateManager& chainman,
117
                                             CTxMemPool& pool, node::Warnings& warnings, Options opts);
118
1.30k
    virtual ~PeerManager() = default;
119
120
    /**
121
     * Attempt to manually fetch block from a given peer. We must already have the header.
122
     *
123
     * @param[in]  peer_id      The peer id
124
     * @param[in]  block_index  The blockindex
125
     */
126
    virtual util::Expected<void, std::string> FetchBlock(NodeId peer_id, const CBlockIndex& block_index) = 0;
127
128
    /** Begin running background tasks, should only be called once */
129
    virtual void StartScheduledTasks(CScheduler& scheduler) = 0;
130
131
    /** Get statistics from node state */
132
    virtual bool GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) const = 0;
133
134
    virtual std::vector<node::TxOrphanage::OrphanInfo> GetOrphanTransactions() = 0;
135
136
    /** Get peer manager info. */
137
    virtual PeerManagerInfo GetInfo() const = 0;
138
139
    /** Get info about transactions currently being privately broadcast. */
140
    virtual std::vector<PrivateBroadcast::TxBroadcastInfo> GetPrivateBroadcastInfo() const = 0;
141
142
    /**
143
     * Abort private broadcast attempts for transactions currently being privately broadcast.
144
     *
145
     * @param[in] id A transaction identifier. It will be matched against both txid and wtxid for
146
     *               all transactions in the private broadcast queue.
147
     *
148
     * @return Transactions removed from the private broadcast queue. If the provided id matches a
149
     *         txid that corresponds to multiple transactions with different wtxids, multiple
150
     *         transactions may be returned.
151
     */
152
    virtual std::vector<CTransactionRef> AbortPrivateBroadcast(const uint256& id) = 0;
153
154
    /**
155
     * Initiate a transaction broadcast to eligible peers.
156
     * Queue the witness transaction id to the inbound and outbound inv backlogs.
157
     * Later, depending on `-txsendrate`, `Peer::TxRelay::m_next_inv_send_time` and if
158
     * the transaction is in the mempool, an `INV` about it may be sent to the peer.
159
     */
160
    virtual void InitiateTxBroadcastToAll(const Wtxid& wtxid) = 0;
161
162
    /**
163
     * Initiate a private transaction broadcast. This is done
164
     * asynchronously via short-lived connections to peers on privacy networks.
165
     * @retval node::TransactionError::OK The transaction is scheduled for private broadcast (or was already scheduled).
166
     * @retval node::TransactionError::PRIVATE_BROADCAST_FULL Rejected because the private broadcast queue is full.
167
     */
168
    [[nodiscard]] virtual node::TransactionError InitiateTxBroadcastPrivate(const CTransactionRef& tx) = 0;
169
170
    /** Send ping message to all peers */
171
    virtual void SendPings() = 0;
172
173
    /** Set the height of the best block and its time (seconds since epoch). */
174
    virtual void SetBestBlock(int height, std::chrono::seconds time) = 0;
175
176
    /* Public for unit testing. */
177
    virtual void UnitTestMisbehaving(NodeId peer_id) = 0;
178
179
    /**
180
     * Evict extra outbound peers. If we think our tip may be stale, connect to an extra outbound.
181
     * Public for unit testing.
182
     */
183
    virtual void CheckForStaleTipAndEvictPeers() = 0;
184
185
    /** This function is used for testing the stale tip eviction logic, see denialofservice_tests.cpp */
186
    virtual void UpdateLastBlockAnnounceTime(NodeId node, NodeClock::time_point time) = 0;
187
188
    /**
189
     * Gets the set of service flags which are "desirable" for a given peer.
190
     *
191
     * These are the flags which are required for a peer to support for them
192
     * to be "interesting" to us, ie for us to wish to use one of our few
193
     * outbound connection slots for or for us to wish to prioritize keeping
194
     * their connection around.
195
     *
196
     * Relevant service flags may be peer- and state-specific in that the
197
     * version of the peer may determine which flags are required (eg in the
198
     * case of NODE_NETWORK_LIMITED where we seek out NODE_NETWORK peers
199
     * unless they set NODE_NETWORK_LIMITED and we are out of IBD, in which
200
     * case NODE_NETWORK_LIMITED suffices).
201
     *
202
     * Thus, generally, avoid calling with 'services' == NODE_NONE, unless
203
     * state-specific flags must absolutely be avoided. When called with
204
     * 'services' == NODE_NONE, the returned desirable service flags are
205
     * guaranteed to not change dependent on state - ie they are suitable for
206
     * use when describing peers which we know to be desirable, but for which
207
     * we do not have a confirmed set of service flags.
208
    */
209
    virtual ServiceFlags GetDesirableServiceFlags(ServiceFlags services) const = 0;
210
};
211
212
#endif // BITCOIN_NET_PROCESSING_H