Coverage Report

Created: 2026-11-13 17:38

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/headerssync.h
Line
Count
Source
1
// Copyright (c) 2022-present The Bitcoin Core developers
2
// Distributed under the MIT software license, see the accompanying
3
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5
#ifndef BITCOIN_HEADERSSYNC_H
6
#define BITCOIN_HEADERSSYNC_H
7
8
#include <arith_uint256.h>
9
#include <chain.h>
10
#include <consensus/params.h>
11
#include <kernel/chainparams.h>
12
#include <net.h>
13
#include <primitives/block.h>
14
#include <uint256.h>
15
#include <util/bitdeque.h>
16
#include <util/hasher.h>
17
18
#include <deque>
19
#include <stdexcept>
20
#include <vector>
21
22
// A compressed CBlockHeader, which leaves out the prevhash
23
struct CompressedHeader {
24
    // header
25
    int32_t nVersion{0};
26
    uint256 hashMerkleRoot;
27
    uint32_t nTime{0};
28
    uint32_t nBits{0};
29
    uint32_t nNonce{0};
30
31
    CompressedHeader()
32
0
    {
33
0
        hashMerkleRoot.SetNull();
34
0
    }
35
36
    explicit CompressedHeader(const CBlockHeader& header)
37
38.5k
        : nVersion{header.nVersion},
38
38.5k
          hashMerkleRoot{header.hashMerkleRoot},
39
38.5k
          nTime{header.nTime},
40
38.5k
          nBits{header.nBits},
41
38.5k
          nNonce{header.nNonce}
42
38.5k
    {
43
38.5k
    }
44
45
    CBlockHeader GetFullHeader(const uint256& hash_prev_block) const
46
36.2k
    {
47
36.2k
        CBlockHeader ret;
48
36.2k
        ret.nVersion = nVersion;
49
36.2k
        ret.hashPrevBlock = hash_prev_block;
50
36.2k
        ret.hashMerkleRoot = hashMerkleRoot;
51
36.2k
        ret.nTime = nTime;
52
36.2k
        ret.nBits = nBits;
53
36.2k
        ret.nNonce = nNonce;
54
36.2k
        return ret;
55
36.2k
    };
56
};
57
58
/** HeadersSyncState:
59
 *
60
 * We wish to download a peer's headers chain in a DoS-resistant way.
61
 *
62
 * The Bitcoin protocol does not offer an easy way to determine the work on a
63
 * peer's chain. Currently, we can query a peer's headers by using a GETHEADERS
64
 * message, and our peer can return a set of up to 2000 headers that connect to
65
 * something we know. If a peer's chain has more than 2000 blocks, then we need
66
 * a way to verify that the chain actually has enough work on it to be useful to
67
 * us -- by being above our anti-DoS minimum-chain-work threshold -- before we
68
 * commit to storing those headers in memory. Otherwise, it would be cheap for
69
 * an attacker to waste all our memory by serving us low-work headers
70
 * (particularly for a new node coming online for the first time).
71
 *
72
 * To prevent memory-DoS with low-work headers, while still always being
73
 * able to reorg to whatever the most-work chain is, we require that a chain
74
 * meet a work threshold before committing it to memory. We can do this by
75
 * downloading a peer's headers twice, whenever we are not sure that the chain
76
 * has sufficient work:
77
 *
78
 * - In the first download phase, called pre-synchronization, we can calculate
79
 * the work on the chain as we go (just by checking the nBits value on each
80
 * header, and validating the proof-of-work).
81
 *
82
 * - Once we have reached a header where the cumulative chain work is
83
 * sufficient, we switch to downloading the headers a second time, this time
84
 * processing them fully, and possibly storing them in memory.
85
 *
86
 * To prevent an attacker from using (eg) the honest chain to convince us that
87
 * they have a high-work chain, but then feeding us an alternate set of
88
 * low-difficulty headers in the second phase, we store commitments to the
89
 * chain we see in the first download phase that we check in the second phase,
90
 * as follows:
91
 *
92
 * - In phase 1 (presync), store 1 bit (using a salted hash function) for every
93
 * N headers that we see. With a reasonable choice of N, this uses relatively
94
 * little memory even for a very long chain.
95
 *
96
 * - In phase 2 (redownload), keep a lookahead buffer and only accept headers
97
 * from that buffer into the block index (permanent memory usage) once they
98
 * have some target number of verified commitments on top of them. With this
99
 * parametrization, we can achieve a given security target for potential
100
 * permanent memory usage, while choosing N to minimize memory use during the
101
 * sync (temporary, per-peer storage).
102
 */
103
104
class HeadersSyncState
105
{
106
public:
107
    struct SystemClockError : std::runtime_error {
108
        using std::runtime_error::runtime_error;
109
    };
110
111
10
    ~HeadersSyncState() = default;
112
113
    enum class State {
114
        /** PRESYNC means the peer has not yet demonstrated their chain has
115
         * sufficient work and we're only building commitments to the chain they
116
         * serve us. */
117
        PRESYNC,
118
        /** REDOWNLOAD means the peer has given us a high-enough-work chain,
119
         * and now we're redownloading the headers we saw before and trying to
120
         * accept them */
121
        REDOWNLOAD,
122
        /** We're done syncing with this peer and can discard any remaining state */
123
        FINAL
124
    };
125
126
    /** Return the current state of our download */
127
40
    State GetState() const { return m_download_state; }
128
129
    /** Return the height reached during the PRESYNC phase */
130
8
    int64_t GetPresyncHeight() const { return m_current_height; }
131
132
    /** Return the block timestamp of the last header received during the PRESYNC phase. */
133
6
    uint32_t GetPresyncTime() const { return m_last_header_received.nTime; }
134
135
    /** Return the amount of work in the chain received during the PRESYNC phase. */
136
11
    arith_uint256 GetPresyncWork() const { return m_current_chain_work; }
137
138
    /** Construct a HeadersSyncState object representing a headers sync via this
139
     *  download-twice mechanism).
140
     *
141
     * id: node id (for logging)
142
     * consensus_params: parameters needed for difficulty adjustment validation
143
     * chain_start: best known fork point that the peer's headers branch from
144
     * minimum_required_work: amount of chain work required to accept the chain
145
     *
146
     * @throws SystemClockError if system clock is too far behind chain_start MTP.
147
     */
148
    HeadersSyncState(NodeId id, const Consensus::Params& consensus_params,
149
                     const HeadersSyncParams& params, const CBlockIndex& chain_start,
150
                     const arith_uint256& minimum_required_work);
151
152
    /** Result data structure for ProcessNextHeaders. */
153
    struct ProcessingResult {
154
        std::vector<CBlockHeader> pow_validated_headers;
155
        bool success{false};
156
        bool request_more{false};
157
    };
158
159
    /** Process a batch of headers, once a sync via this mechanism has started
160
     *
161
     * received_headers: headers that were received over the network for processing.
162
     *                   Assumes the caller has already verified the headers
163
     *                   are continuous, and has checked that each header
164
     *                   satisfies the proof-of-work target included in the
165
     *                   header (but not necessarily verified that the
166
     *                   proof-of-work target is correct and passes consensus
167
     *                   rules).
168
     * full_headers_message: true if the message was at max capacity,
169
     *                       indicating more headers may be available
170
     * ProcessingResult.pow_validated_headers: will be filled in with any
171
     *                       headers that the caller can fully process and
172
     *                       validate now (because these returned headers are
173
     *                       on a chain with sufficient work)
174
     * ProcessingResult.success: set to false if an error is detected and the sync is
175
     *                       aborted; true otherwise.
176
     * ProcessingResult.request_more: if true, the caller is suggested to call
177
     *                       NextHeadersRequestLocator and send a getheaders message using it.
178
     */
179
    ProcessingResult ProcessNextHeaders(std::span<const CBlockHeader>
180
            received_headers, bool full_headers_message);
181
182
    /** Issue the next GETHEADERS message to our peer.
183
     *
184
     * This will return a locator appropriate for the current sync object, to continue the
185
     * synchronization phase it is in.
186
     */
187
    CBlockLocator NextHeadersRequestLocator() const;
188
189
protected:
190
    /** The (secret) offset on the heights for which to create commitments.
191
     *
192
     * m_header_commitments entries are created at any height h for which
193
     * (h % m_params.commitment_period) == m_commit_offset. */
194
    const size_t m_commit_offset;
195
196
private:
197
    /** Clear out all download state that might be in progress (freeing any used
198
     * memory), and mark this object as no longer usable.
199
     */
200
    void Finalize();
201
202
    /**
203
     *  Only called in PRESYNC.
204
     *  Validate the work on the headers we received from the network, and
205
     *  store commitments for later. Update overall state with successfully
206
     *  processed headers.
207
     *  On failure, this invokes Finalize() and returns false.
208
     */
209
    bool ValidateAndStoreHeadersCommitments(std::span<const CBlockHeader> headers);
210
211
    /** In PRESYNC, process and update state for a single header */
212
    bool ValidateAndProcessSingleHeader(const CBlockHeader& current);
213
214
    /** In REDOWNLOAD, check a header's commitment (if applicable) and add to
215
     * buffer for later processing */
216
    bool ValidateAndStoreRedownloadedHeader(const CBlockHeader& header);
217
218
    /** Return a set of headers that satisfy our proof-of-work threshold */
219
    std::vector<CBlockHeader> PopHeadersReadyForAcceptance();
220
221
private:
222
    /** NodeId of the peer (used for log messages) **/
223
    const NodeId m_id;
224
225
    /** We use the consensus params in our anti-DoS calculations */
226
    const Consensus::Params& m_consensus_params;
227
228
    /** Parameters that impact memory usage for a given chain, especially when attacked. */
229
    const HeadersSyncParams m_params;
230
231
    /** Store the last block in our block index that the peer's chain builds from */
232
    const CBlockIndex& m_chain_start;
233
234
    /** Minimum work that we're looking for on this chain. */
235
    const arith_uint256 m_minimum_required_work;
236
237
    /** Work that we've seen so far on the peer's chain */
238
    arith_uint256 m_current_chain_work;
239
240
    /** m_hasher is a salted hasher for making our 1-bit commitments to headers we've seen. */
241
    const SaltedUint256Hasher m_hasher;
242
243
    /** A queue of commitment bits, created during the 1st phase, and verified during the 2nd. */
244
    bitdeque<> m_header_commitments;
245
246
    /** m_max_commitments is a bound we calculate on how long an honest peer's chain could be,
247
     * given the MTP rule.
248
     *
249
     * Any peer giving us more headers than this will have its sync aborted. This serves as a
250
     * memory bound on m_header_commitments. */
251
    uint64_t m_max_commitments{0};
252
253
    /** Store the latest header received while in PRESYNC (initialized to m_chain_start) */
254
    CBlockHeader m_last_header_received;
255
256
    /** Height of m_last_header_received */
257
    int64_t m_current_height{0};
258
259
    /** During phase 2 (REDOWNLOAD), we buffer redownloaded headers in memory
260
     *  until enough commitments have been verified; those are stored in
261
     *  m_redownloaded_headers */
262
    std::deque<CompressedHeader> m_redownloaded_headers;
263
264
    /** Height of last header in m_redownloaded_headers */
265
    int64_t m_redownload_buffer_last_height{0};
266
267
    /** Hash of last header in m_redownloaded_headers (initialized to
268
     * m_chain_start). We have to cache it because we don't have hashPrevBlock
269
     * available in a CompressedHeader.
270
     */
271
    uint256 m_redownload_buffer_last_hash;
272
273
    /** The hashPrevBlock entry for the first header in m_redownloaded_headers
274
     * We need this to reconstruct the full header when it's time for
275
     * processing.
276
     */
277
    uint256 m_redownload_buffer_first_prev_hash;
278
279
    /** The accumulated work on the redownloaded chain. */
280
    arith_uint256 m_redownload_chain_work;
281
282
    /** Set this to true once we encounter the target blockheader during phase
283
     * 2 (REDOWNLOAD). At this point, we can process and store all remaining
284
     * headers still in m_redownloaded_headers.
285
     */
286
    bool m_process_all_remaining_headers{false};
287
288
    /** Current state of our headers sync. */
289
    State m_download_state{State::PRESYNC};
290
};
291
292
#endif // BITCOIN_HEADERSSYNC_H