Bitcoin Core 32.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 <pow.h>
8#include <util/check.h>
9#include <util/log.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 Consensus::Params& consensus_params,
19 const HeadersSyncParams& params,
20 const CBlockIndex& chain_start,
21 const arith_uint256& minimum_required_work)
22 : m_commit_offset((assert(params.commitment_period > 0), // HeadersSyncParams field must be initialized to non-zero.
23 FastRandomContext().randrange(params.commitment_period))),
24 m_id(id),
25 m_consensus_params(consensus_params),
26 m_params(params),
27 m_chain_start(chain_start),
28 m_minimum_required_work(minimum_required_work),
29 m_current_chain_work(chain_start.nChainWork),
30 m_last_header_received(m_chain_start.GetBlockHeader()),
31 m_current_height(chain_start.nHeight)
32{
33 // Estimate the number of blocks that could possibly exist on the peer's
34 // chain *right now* using 6 blocks/second (fastest blockrate given the MTP
35 // rule) times the number of seconds from the last allowed block until
36 // today. This serves as a memory bound on how many commitments we might
37 // store from this peer, and we can safely give up syncing if the peer
38 // exceeds this bound, because it's not possible for a consensus-valid
39 // chain to be longer than this (at the current time -- in the future we
40 // could try again, if necessary, to sync a longer chain).
41 const auto now{NodeClock::now()};
42 const int64_t max_seconds_since_start{Ticks<std::chrono::seconds>(now - NodeSeconds{std::chrono::seconds{chain_start.GetMedianTimePast()}})
44 if (max_seconds_since_start < 0) {
46 "System clock is more than %d minutes behind chain start MTP (%s vs %s).",
48 FormatISO8601DateTime(TicksSinceEpoch<std::chrono::seconds>(now)),
50 }
51 m_max_commitments = 6 * max_seconds_since_start / m_params.commitment_period;
52
53 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());
54}
55
60{
69
71}
72
77 std::span<const CBlockHeader> received_headers, const bool full_headers_message)
78{
80
81 Assume(!received_headers.empty());
82 if (received_headers.empty()) return ret;
83
85 if (m_download_state == State::FINAL) return ret;
86
88 // During PRESYNC, we minimally validate block headers and
89 // occasionally add commitments to them, until we reach our work
90 // threshold (at which point m_download_state is updated to REDOWNLOAD).
91 ret.success = ValidateAndStoreHeadersCommitments(received_headers);
92 if (ret.success) {
93 if (full_headers_message || m_download_state == State::REDOWNLOAD) {
94 // A full headers message means the peer may have more to give us;
95 // also if we just switched to REDOWNLOAD then we need to re-request
96 // headers from the beginning.
97 ret.request_more = true;
98 } else {
100 // If we're in PRESYNC and we get a non-full headers
101 // message, then the peer's chain has ended and definitely doesn't
102 // have enough work, so we can stop our sync.
103 LogDebug(BCLog::NET, "Initial headers sync aborted with peer=%d: incomplete headers message at height=%i (presync phase)\n", m_id, m_current_height);
104 }
105 }
106 } else if (m_download_state == State::REDOWNLOAD) {
107 // During REDOWNLOAD, we compare our stored commitments to what we
108 // receive, and add headers to our redownload buffer. When the buffer
109 // gets big enough (meaning that we've checked enough commitments),
110 // we'll return a batch of headers to the caller for processing.
111 ret.success = true;
112 for (const auto& hdr : received_headers) {
114 // Something went wrong -- the peer gave us an unexpected chain.
115 // We could consider looking at the reason for failure and
116 // punishing the peer, but for now just give up on sync.
117 ret.success = false;
118 break;
119 }
120 }
121
122 if (ret.success) {
123 // Return any headers that are ready for acceptance.
124 ret.pow_validated_headers = PopHeadersReadyForAcceptance();
125
126 // If we hit our target blockhash, then all remaining headers will be
127 // returned and we can clear any leftover internal state.
129 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);
130 } else if (full_headers_message) {
131 // If the headers message is full, we need to request more.
132 ret.request_more = true;
133 } else {
134 // For some reason our peer gave us a high-work chain, but is now
135 // declining to serve us that full chain again. Give up.
136 // Note that there's no more processing to be done with these
137 // headers, so we can still return success.
138 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);
139 }
140 }
141 }
142
143 if (!(ret.success && ret.request_more)) Finalize();
144 return ret;
145}
146
148{
149 // The caller should not give us an empty set of headers.
150 Assume(headers.size() > 0);
151 if (headers.size() == 0) return true;
152
154 if (m_download_state != State::PRESYNC) return false;
155
156 if (headers[0].hashPrevBlock != m_last_header_received.GetHash()) {
157 // Somehow our peer gave us a header that doesn't connect.
158 // This might be benign -- perhaps our peer reorged away from the chain
159 // they were on. Give up on this sync for now (likely we will start a
160 // new sync with a new starting point).
161 LogDebug(BCLog::NET, "Initial headers sync aborted with peer=%d: non-continuous headers at height=%i (presync phase)\n", m_id, m_current_height);
162 return false;
163 }
164
165 // If it does connect, (minimally) validate and occasionally store
166 // commitments.
167 for (const auto& hdr : headers) {
169 return false;
170 }
171 }
172
180 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);
181 }
182 return true;
183}
184
186{
188 if (m_download_state != State::PRESYNC) return false;
189
190 int next_height = m_current_height + 1;
191
192 // Verify that the difficulty isn't growing too fast; an adversary with
193 // limited hashing capability has a greater chance of producing a high
194 // work chain if they compress the work into as few blocks as possible,
195 // so don't let anyone give a chain that would violate the difficulty
196 // adjustment maximum.
199 LogDebug(BCLog::NET, "Initial headers sync aborted with peer=%d: invalid difficulty transition at height=%i (presync phase)\n", m_id, next_height);
200 return false;
201 }
202
203 if (next_height % m_params.commitment_period == m_commit_offset) {
204 // Add a commitment.
207 // The peer's chain is too long; give up.
208 // It's possible the chain grew since we started the sync; so
209 // potentially we could succeed in syncing the peer's chain if we
210 // try again later.
211 LogDebug(BCLog::NET, "Initial headers sync aborted with peer=%d: exceeded max commitments at height=%i (presync phase)\n", m_id, next_height);
212 return false;
213 }
214 }
215
217 m_last_header_received = current;
218 m_current_height = next_height;
219
220 return true;
221}
222
224{
226 if (m_download_state != State::REDOWNLOAD) return false;
227
228 int64_t next_height = m_redownload_buffer_last_height + 1;
229
230 // Ensure that we're working on a header that connects to the chain we're
231 // downloading.
233 LogDebug(BCLog::NET, "Initial headers sync aborted with peer=%d: non-continuous headers at height=%i (redownload phase)\n", m_id, next_height);
234 return false;
235 }
236
237 // Check that the difficulty adjustments are within our tolerance:
238 uint32_t previous_nBits{0};
239 if (!m_redownloaded_headers.empty()) {
240 previous_nBits = m_redownloaded_headers.back().nBits;
241 } else {
242 previous_nBits = m_chain_start.nBits;
243 }
244
246 previous_nBits, header.nBits)) {
247 LogDebug(BCLog::NET, "Initial headers sync aborted with peer=%d: invalid difficulty transition at height=%i (redownload phase)\n", m_id, next_height);
248 return false;
249 }
250
251 // Track work on the redownloaded chain
253
256 }
257
258 // If we're at a header for which we previously stored a commitment, verify
259 // it is correct. Failure will result in aborting download.
260 // Also, don't check commitments once we've gotten to our target blockhash;
261 // it's possible our peer has extended its chain between our first sync and
262 // our second, and we don't want to return failure after we've seen our
263 // target blockhash just because we ran out of commitments.
265 if (m_header_commitments.size() == 0) {
266 LogDebug(BCLog::NET, "Initial headers sync aborted with peer=%d: commitment overrun at height=%i (redownload phase)\n", m_id, next_height);
267 // Somehow our peer managed to feed us a different chain and
268 // we've run out of commitments.
269 return false;
270 }
271 bool commitment = m_hasher(header.GetHash()) & 1;
272 bool expected_commitment = m_header_commitments.front();
274 if (commitment != expected_commitment) {
275 LogDebug(BCLog::NET, "Initial headers sync aborted with peer=%d: commitment mismatch at height=%i (redownload phase)\n", m_id, next_height);
276 return false;
277 }
278 }
279
280 // Store this header for later processing.
281 m_redownloaded_headers.emplace_back(header);
284
285 return true;
286}
287
289{
290 std::vector<CBlockHeader> ret;
291
294
297 ret.emplace_back(m_redownloaded_headers.front().GetFullHeader(m_redownload_buffer_first_prev_hash));
298 m_redownloaded_headers.pop_front();
299 m_redownload_buffer_first_prev_hash = ret.back().GetHash();
300 }
301 return ret;
302}
303
305{
307 if (m_download_state == State::FINAL) return {};
308
309 auto chain_start_locator = LocatorEntries(&m_chain_start);
310 std::vector<uint256> locator;
311
313 // During pre-synchronization, we continue from the last header received.
314 locator.push_back(m_last_header_received.GetHash());
315 }
316
318 // During redownload, we will download from the last received header that we stored.
319 locator.push_back(m_redownload_buffer_last_hash);
320 }
321
322 locator.insert(locator.end(), chain_start_locator.begin(), chain_start_locator.end());
323
324 return CBlockLocator{std::move(locator)};
325}
int ret
std::vector< uint256 > LocatorEntries(const CBlockIndex *index)
Construct a list of hash entries to put in a locator.
Definition: chain.cpp:26
arith_uint256 GetBlockProof(const CBlockIndex &block)
Compute how much work a block index entry corresponds to.
Definition: chain.h:305
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:128
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:27
uint32_t nBits
Definition: block.h:34
uint256 hashPrevBlock
Definition: block.h:31
void SetNull()
Definition: block.h:44
uint256 GetHash() const
Definition: block.cpp:14
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:94
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:118
uint256 GetBlockHash() const
Definition: chain.h:198
int64_t GetMedianTimePast() const
Definition: chain.h:233
uint32_t nBits
Definition: chain.h:143
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:106
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:250
arith_uint256 m_redownload_chain_work
The accumulated work on the redownloaded chain.
Definition: headerssync.h:279
@ 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:253
arith_uint256 m_current_chain_work
Work that we've seen so far on the peer's chain.
Definition: headerssync.h:237
int64_t m_current_height
Height of m_last_header_received.
Definition: headerssync.h:256
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:234
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:225
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:288
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:243
const NodeId m_id
NodeId of the peer (used for log messages)
Definition: headerssync.h:222
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:76
int64_t m_redownload_buffer_last_height
Height of last header in m_redownloaded_headers.
Definition: headerssync.h:264
std::deque< CompressedHeader > m_redownloaded_headers
During phase 2 (REDOWNLOAD), we buffer redownloaded headers in memory until enough commitments have b...
Definition: headerssync.h:261
bool m_process_all_remaining_headers
Set this to true once we encounter the target blockheader during phase 2 (REDOWNLOAD).
Definition: headerssync.h:285
const HeadersSyncParams m_params
Parameters that impact memory usage for a given chain, especially when attacked.
Definition: headerssync.h:228
void Finalize()
Clear out all download state that might be in progress (freeing any used memory), and mark this objec...
Definition: headerssync.cpp:59
uint256 m_redownload_buffer_last_hash
Hash of last header in m_redownloaded_headers (initialized to m_chain_start).
Definition: headerssync.h:270
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:276
const CBlockIndex & m_chain_start
Store the last block in our block index that the peer's chain builds from.
Definition: headerssync.h:231
const size_t m_commit_offset
The (secret) offset on the heights for which to create commitments.
Definition: headerssync.h:193
const SaltedUint256Hasher m_hasher
m_hasher is a salted hasher for making our 1-bit commitments to headers we've seen.
Definition: headerssync.h:240
CBlockLocator NextHeadersRequestLocator() const
Issue the next GETHEADERS message to our peer.
256-bit unsigned big integer.
constexpr void SetNull()
Definition: uint256.h:57
std::string ToString() const
size_type size() const noexcept
Count the number of bits in the container.
Definition: bitdeque.h:259
reference front()
Definition: bitdeque.h:329
void pop_front()
Definition: bitdeque.h:382
void push_back(bool val)
Definition: bitdeque.h:348
HTTPHeaders headers
#define LogDebug(category,...)
Definition: log.h:143
unsigned int nHeight
@ NET
Definition: categories.h:16
int64_t NodeId
Definition: net.h:105
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:117
Parameters that influence chain consensus.
Definition: params.h:88
Configuration for headers sync memory usage.
Definition: chainparams.h:64
size_t redownload_buffer_size
Minimum number of validated headers to accumulate in the redownload buffer before feeding them into t...
Definition: chainparams.h:69
size_t commitment_period
Distance in blocks between header commitments.
Definition: chainparams.h:66
Result data structure for ProcessNextHeaders.
Definition: headerssync.h:152
static time_point now() noexcept
Return current system time or mocked time, if set.
Definition: time.cpp:38
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
Definition: time.cpp:90
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
Definition: time.h:35
assert(!tx.IsCoinBase())
void ClearShrink(V &v) noexcept
Clear a vector (or std::deque) and release its allocated memory.
Definition: vector.h:56