Bitcoin Core 30.99.0
P2P Digital Currency
headerssync.cpp
Go to the documentation of this file.
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#include <headerssync.h>
6
7#include <logging.h>
8#include <pow.h>
9#include <util/check.h>
10#include <util/time.h>
11#include <util/vector.h>
12
13// Our memory analysis in headerssync-params.py assumes this many bytes for a
14// CompressedHeader (we should re-calculate parameters if we compress further).
15static_assert(sizeof(CompressedHeader) == 48);
16
18 const HeadersSyncParams& params, const CBlockIndex* chain_start,
19 const arith_uint256& minimum_required_work) :
20 m_commit_offset((assert(params.commitment_period > 0), // HeadersSyncParams field must be initialized to non-zero.
21 FastRandomContext().randrange(params.commitment_period))),
22 m_id(id), m_consensus_params(consensus_params),
23 m_params(params),
24 m_chain_start(chain_start),
25 m_minimum_required_work(minimum_required_work),
26 m_current_chain_work(chain_start->nChainWork),
27 m_last_header_received(m_chain_start->GetBlockHeader()),
28 m_current_height(chain_start->nHeight)
29{
30 // Estimate the number of blocks that could possibly exist on the peer's
31 // chain *right now* using 6 blocks/second (fastest blockrate given the MTP
32 // rule) times the number of seconds from the last allowed block until
33 // today. This serves as a memory bound on how many commitments we might
34 // store from this peer, and we can safely give up syncing if the peer
35 // exceeds this bound, because it's not possible for a consensus-valid
36 // chain to be longer than this (at the current time -- in the future we
37 // could try again, if necessary, to sync a longer chain).
38 const auto max_seconds_since_start{(Ticks<std::chrono::seconds>(NodeClock::now() - NodeSeconds{std::chrono::seconds{chain_start->GetMedianTimePast()}}))
40 m_max_commitments = 6 * max_seconds_since_start / m_params.commitment_period;
41
42 LogDebug(BCLog::NET, "Initial headers sync started with peer=%d: height=%i, max_commitments=%i, min_work=%s\n", m_id, m_current_height, m_max_commitments, m_minimum_required_work.ToString());
43}
44
49{
58
60}
61
66 std::span<const CBlockHeader> received_headers, const bool full_headers_message)
67{
69
70 Assume(!received_headers.empty());
71 if (received_headers.empty()) return ret;
72
74 if (m_download_state == State::FINAL) return ret;
75
77 // During PRESYNC, we minimally validate block headers and
78 // occasionally add commitments to them, until we reach our work
79 // threshold (at which point m_download_state is updated to REDOWNLOAD).
80 ret.success = ValidateAndStoreHeadersCommitments(received_headers);
81 if (ret.success) {
82 if (full_headers_message || m_download_state == State::REDOWNLOAD) {
83 // A full headers message means the peer may have more to give us;
84 // also if we just switched to REDOWNLOAD then we need to re-request
85 // headers from the beginning.
86 ret.request_more = true;
87 } else {
89 // If we're in PRESYNC and we get a non-full headers
90 // message, then the peer's chain has ended and definitely doesn't
91 // have enough work, so we can stop our sync.
92 LogDebug(BCLog::NET, "Initial headers sync aborted with peer=%d: incomplete headers message at height=%i (presync phase)\n", m_id, m_current_height);
93 }
94 }
95 } else if (m_download_state == State::REDOWNLOAD) {
96 // During REDOWNLOAD, we compare our stored commitments to what we
97 // receive, and add headers to our redownload buffer. When the buffer
98 // gets big enough (meaning that we've checked enough commitments),
99 // we'll return a batch of headers to the caller for processing.
100 ret.success = true;
101 for (const auto& hdr : received_headers) {
103 // Something went wrong -- the peer gave us an unexpected chain.
104 // We could consider looking at the reason for failure and
105 // punishing the peer, but for now just give up on sync.
106 ret.success = false;
107 break;
108 }
109 }
110
111 if (ret.success) {
112 // Return any headers that are ready for acceptance.
113 ret.pow_validated_headers = PopHeadersReadyForAcceptance();
114
115 // If we hit our target blockhash, then all remaining headers will be
116 // returned and we can clear any leftover internal state.
118 LogDebug(BCLog::NET, "Initial headers sync complete with peer=%d: releasing all at height=%i (redownload phase)\n", m_id, m_redownload_buffer_last_height);
119 } else if (full_headers_message) {
120 // If the headers message is full, we need to request more.
121 ret.request_more = true;
122 } else {
123 // For some reason our peer gave us a high-work chain, but is now
124 // declining to serve us that full chain again. Give up.
125 // Note that there's no more processing to be done with these
126 // headers, so we can still return success.
127 LogDebug(BCLog::NET, "Initial headers sync aborted with peer=%d: incomplete headers message at height=%i (redownload phase)\n", m_id, m_redownload_buffer_last_height);
128 }
129 }
130 }
131
132 if (!(ret.success && ret.request_more)) Finalize();
133 return ret;
134}
135
136bool HeadersSyncState::ValidateAndStoreHeadersCommitments(std::span<const CBlockHeader> headers)
137{
138 // The caller should not give us an empty set of headers.
139 Assume(headers.size() > 0);
140 if (headers.size() == 0) return true;
141
143 if (m_download_state != State::PRESYNC) return false;
144
145 if (headers[0].hashPrevBlock != m_last_header_received.GetHash()) {
146 // Somehow our peer gave us a header that doesn't connect.
147 // This might be benign -- perhaps our peer reorged away from the chain
148 // they were on. Give up on this sync for now (likely we will start a
149 // new sync with a new starting point).
150 LogDebug(BCLog::NET, "Initial headers sync aborted with peer=%d: non-continuous headers at height=%i (presync phase)\n", m_id, m_current_height);
151 return false;
152 }
153
154 // If it does connect, (minimally) validate and occasionally store
155 // commitments.
156 for (const auto& hdr : headers) {
158 return false;
159 }
160 }
161
169 LogDebug(BCLog::NET, "Initial headers sync transition with peer=%d: reached sufficient work at height=%i, redownloading from height=%i\n", m_id, m_current_height, m_redownload_buffer_last_height);
170 }
171 return true;
172}
173
175{
177 if (m_download_state != State::PRESYNC) return false;
178
179 int next_height = m_current_height + 1;
180
181 // Verify that the difficulty isn't growing too fast; an adversary with
182 // limited hashing capability has a greater chance of producing a high
183 // work chain if they compress the work into as few blocks as possible,
184 // so don't let anyone give a chain that would violate the difficulty
185 // adjustment maximum.
188 LogDebug(BCLog::NET, "Initial headers sync aborted with peer=%d: invalid difficulty transition at height=%i (presync phase)\n", m_id, next_height);
189 return false;
190 }
191
192 if (next_height % m_params.commitment_period == m_commit_offset) {
193 // Add a commitment.
196 // The peer's chain is too long; give up.
197 // It's possible the chain grew since we started the sync; so
198 // potentially we could succeed in syncing the peer's chain if we
199 // try again later.
200 LogDebug(BCLog::NET, "Initial headers sync aborted with peer=%d: exceeded max commitments at height=%i (presync phase)\n", m_id, next_height);
201 return false;
202 }
203 }
204
206 m_last_header_received = current;
207 m_current_height = next_height;
208
209 return true;
210}
211
213{
215 if (m_download_state != State::REDOWNLOAD) return false;
216
217 int64_t next_height = m_redownload_buffer_last_height + 1;
218
219 // Ensure that we're working on a header that connects to the chain we're
220 // downloading.
222 LogDebug(BCLog::NET, "Initial headers sync aborted with peer=%d: non-continuous headers at height=%i (redownload phase)\n", m_id, next_height);
223 return false;
224 }
225
226 // Check that the difficulty adjustments are within our tolerance:
227 uint32_t previous_nBits{0};
228 if (!m_redownloaded_headers.empty()) {
229 previous_nBits = m_redownloaded_headers.back().nBits;
230 } else {
231 previous_nBits = m_chain_start->nBits;
232 }
233
235 previous_nBits, header.nBits)) {
236 LogDebug(BCLog::NET, "Initial headers sync aborted with peer=%d: invalid difficulty transition at height=%i (redownload phase)\n", m_id, next_height);
237 return false;
238 }
239
240 // Track work on the redownloaded chain
242
245 }
246
247 // If we're at a header for which we previously stored a commitment, verify
248 // it is correct. Failure will result in aborting download.
249 // Also, don't check commitments once we've gotten to our target blockhash;
250 // it's possible our peer has extended its chain between our first sync and
251 // our second, and we don't want to return failure after we've seen our
252 // target blockhash just because we ran out of commitments.
254 if (m_header_commitments.size() == 0) {
255 LogDebug(BCLog::NET, "Initial headers sync aborted with peer=%d: commitment overrun at height=%i (redownload phase)\n", m_id, next_height);
256 // Somehow our peer managed to feed us a different chain and
257 // we've run out of commitments.
258 return false;
259 }
260 bool commitment = m_hasher(header.GetHash()) & 1;
261 bool expected_commitment = m_header_commitments.front();
263 if (commitment != expected_commitment) {
264 LogDebug(BCLog::NET, "Initial headers sync aborted with peer=%d: commitment mismatch at height=%i (redownload phase)\n", m_id, next_height);
265 return false;
266 }
267 }
268
269 // Store this header for later processing.
270 m_redownloaded_headers.emplace_back(header);
273
274 return true;
275}
276
278{
279 std::vector<CBlockHeader> ret;
280
283
286 ret.emplace_back(m_redownloaded_headers.front().GetFullHeader(m_redownload_buffer_first_prev_hash));
287 m_redownloaded_headers.pop_front();
288 m_redownload_buffer_first_prev_hash = ret.back().GetHash();
289 }
290 return ret;
291}
292
294{
296 if (m_download_state == State::FINAL) return {};
297
298 auto chain_start_locator = LocatorEntries(m_chain_start);
299 std::vector<uint256> locator;
300
302 // During pre-synchronization, we continue from the last header received.
303 locator.push_back(m_last_header_received.GetHash());
304 }
305
307 // During redownload, we will download from the last received header that we stored.
308 locator.push_back(m_redownload_buffer_last_hash);
309 }
310
311 locator.insert(locator.end(), chain_start_locator.begin(), chain_start_locator.end());
312
313 return CBlockLocator{std::move(locator)};
314}
int ret
arith_uint256 GetBlockProof(const CBlockIndex &block)
Definition: chain.cpp:127
std::vector< uint256 > LocatorEntries(const CBlockIndex *index)
Construct a list of hash entries to put in a locator.
Definition: chain.cpp:32
static constexpr int64_t MAX_FUTURE_BLOCK_TIME
Maximum amount of time that a block timestamp is allowed to exceed the current time before the block ...
Definition: chain.h:29
#define Assume(val)
Assume is the identity function.
Definition: check.h:127
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:22
uint32_t nBits
Definition: block.h:29
uint256 hashPrevBlock
Definition: block.h:26
void SetNull()
Definition: block.h:39
uint256 GetHash() const
Definition: block.cpp:11
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:144
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:168
uint256 GetBlockHash() const
Definition: chain.h:248
int64_t GetMedianTimePast() const
Definition: chain.h:283
uint32_t nBits
Definition: chain.h:193
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:156
Fast randomness source.
Definition: random.h:386
uint64_t m_max_commitments
m_max_commitments is a bound we calculate on how long an honest peer's chain could be,...
Definition: headerssync.h:241
arith_uint256 m_redownload_chain_work
The accumulated work on the redownloaded chain.
Definition: headerssync.h:270
@ FINAL
We're done syncing with this peer and can discard any remaining state.
@ PRESYNC
PRESYNC means the peer has not yet demonstrated their chain has sufficient work and we're only buildi...
@ REDOWNLOAD
REDOWNLOAD means the peer has given us a high-enough-work chain, and now we're redownloading the head...
bool ValidateAndStoreHeadersCommitments(std::span< const CBlockHeader > headers)
Only called in PRESYNC.
CBlockHeader m_last_header_received
Store the latest header received while in PRESYNC (initialized to m_chain_start)
Definition: headerssync.h:244
arith_uint256 m_current_chain_work
Work that we've seen so far on the peer's chain.
Definition: headerssync.h:228
int64_t m_current_height
Height of m_last_header_received.
Definition: headerssync.h:247
HeadersSyncState(NodeId id, const Consensus::Params &consensus_params, const HeadersSyncParams &params, const CBlockIndex *chain_start, const arith_uint256 &minimum_required_work)
Construct a HeadersSyncState object representing a headers sync via this download-twice mechanism).
Definition: headerssync.cpp:17
const arith_uint256 m_minimum_required_work
Minimum work that we're looking for on this chain.
Definition: headerssync.h:225
std::vector< CBlockHeader > PopHeadersReadyForAcceptance()
Return a set of headers that satisfy our proof-of-work threshold.
const Consensus::Params & m_consensus_params
We use the consensus params in our anti-DoS calculations.
Definition: headerssync.h:216
bool ValidateAndProcessSingleHeader(const CBlockHeader &current)
In PRESYNC, process and update state for a single header.
State m_download_state
Current state of our headers sync.
Definition: headerssync.h:279
bool ValidateAndStoreRedownloadedHeader(const CBlockHeader &header)
In REDOWNLOAD, check a header's commitment (if applicable) and add to buffer for later processing.
bitdeque m_header_commitments
A queue of commitment bits, created during the 1st phase, and verified during the 2nd.
Definition: headerssync.h:234
const NodeId m_id
NodeId of the peer (used for log messages)
Definition: headerssync.h:213
ProcessingResult ProcessNextHeaders(std::span< const CBlockHeader > received_headers, bool full_headers_message)
Process a batch of headers, once a sync via this mechanism has started.
Definition: headerssync.cpp:65
int64_t m_redownload_buffer_last_height
Height of last header in m_redownloaded_headers.
Definition: headerssync.h:255
std::deque< CompressedHeader > m_redownloaded_headers
During phase 2 (REDOWNLOAD), we buffer redownloaded headers in memory until enough commitments have b...
Definition: headerssync.h:252
bool m_process_all_remaining_headers
Set this to true once we encounter the target blockheader during phase 2 (REDOWNLOAD).
Definition: headerssync.h:276
const HeadersSyncParams m_params
Parameters that impact memory usage for a given chain, especially when attacked.
Definition: headerssync.h:219
void Finalize()
Clear out all download state that might be in progress (freeing any used memory), and mark this objec...
Definition: headerssync.cpp:48
uint256 m_redownload_buffer_last_hash
Hash of last header in m_redownloaded_headers (initialized to m_chain_start).
Definition: headerssync.h:261
uint256 m_redownload_buffer_first_prev_hash
The hashPrevBlock entry for the first header in m_redownloaded_headers We need this to reconstruct th...
Definition: headerssync.h:267
const CBlockIndex * m_chain_start
Store the last block in our block index that the peer's chain builds from.
Definition: headerssync.h:222
const size_t m_commit_offset
The (secret) offset on the heights for which to create commitments.
Definition: headerssync.h:184
const SaltedUint256Hasher m_hasher
m_hasher is a salted hasher for making our 1-bit commitments to headers we've seen.
Definition: headerssync.h:231
CBlockLocator NextHeadersRequestLocator() const
Issue the next GETHEADERS message to our peer.
256-bit unsigned big integer.
constexpr void SetNull()
Definition: uint256.h:55
std::string ToString() const
size_type size() const noexcept
Count the number of bits in the container.
Definition: bitdeque.h:262
reference front()
Definition: bitdeque.h:332
void pop_front()
Definition: bitdeque.h:385
void push_back(bool val)
Definition: bitdeque.h:351
#define LogDebug(category,...)
Definition: logging.h:393
unsigned int nHeight
@ NET
Definition: logging.h:66
int64_t NodeId
Definition: net.h:99
bool PermittedDifficultyTransition(const Consensus::Params &params, int64_t height, uint32_t old_nbits, uint32_t new_nbits)
Return false if the proof-of-work requirement specified by new_nbits at a given height is not possibl...
Definition: pow.cpp:89
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:124
Parameters that influence chain consensus.
Definition: params.h:84
Configuration for headers sync memory usage.
Definition: chainparams.h:65
size_t redownload_buffer_size
Minimum number of validated headers to accumulate in the redownload buffer before feeding them into t...
Definition: chainparams.h:70
size_t commitment_period
Distance in blocks between header commitments.
Definition: chainparams.h:67
Result data structure for ProcessNextHeaders.
Definition: headerssync.h:143
static time_point now() noexcept
Return current system time or mocked time, if set.
Definition: time.cpp:26
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
Definition: time.h:25
assert(!tx.IsCoinBase())
void ClearShrink(V &v) noexcept
Clear a vector (or std::deque) and release its allocated memory.
Definition: vector.h:56