Bitcoin ABC 0.32.5
P2P Digital Currency
headerssync.cpp
Go to the documentation of this file.
1// Copyright (c) 2022 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#include <logging.h>
7#include <pow/pow.h>
8#include <timedata.h>
9#include <util/check.h>
10#include <util/vector.h>
11
12// The two constants below are computed using the simulation script on
13// https://gist.github.com/sipa/016ae445c132cdf65a2791534dfb7ae1
14// with MINCHAINWORK_HEADERS = 826150 and TIME = datetime(2027, 1, 1)
15
17constexpr size_t HEADER_COMMITMENT_PERIOD{610};
18
21// 14521/610 = ~23.8 commitments
22constexpr size_t REDOWNLOAD_BUFFER_SIZE{14521};
23
24// Our memory analysis assumes 48 bytes for a CompressedHeader (so we should
25// re-calculate parameters if we compress further)
26static_assert(sizeof(CompressedHeader) == 48);
27
29 const Consensus::Params &consensus_params,
30 const CBlockIndex *chain_start,
31 const arith_uint256 &minimum_required_work)
32 : m_id(id), m_consensus_params(consensus_params),
33 m_chain_start(chain_start),
34 m_minimum_required_work(minimum_required_work),
35 m_current_chain_work(chain_start->nChainWork),
36 m_commit_offset(
37 FastRandomContext().randrange<unsigned>(HEADER_COMMITMENT_PERIOD)),
38 m_last_header_received(m_chain_start->GetBlockHeader()),
39 m_current_height(chain_start->nHeight) {
40 // Estimate the number of blocks that could possibly exist on the peer's
41 // chain *right now* using 6 blocks/second (fastest blockrate given the MTP
42 // rule) times the number of seconds from the last allowed block until
43 // today. This serves as a memory bound on how many commitments we might
44 // store from this peer, and we can safely give up syncing if the peer
45 // exceeds this bound, because it's not possible for a consensus-valid
46 // chain to be longer than this (at the current time -- in the future we
47 // could try again, if necessary, to sync a longer chain).
49 6 *
50 (Ticks<std::chrono::seconds>(GetAdjustedTime() -
51 NodeSeconds{std::chrono::seconds{
52 chain_start->GetMedianTimePast()}}) +
55
57 "Initial headers sync started with peer=%d: height=%i, "
58 "max_commitments=%i, min_work=%s\n",
61}
62
77
79}
80
87 const std::vector<CBlockHeader> &received_headers,
88 const bool full_headers_message) {
90
91 Assume(!received_headers.empty());
92 if (received_headers.empty()) {
93 return ret;
94 }
95
98 return ret;
99 }
100
102 // During PRESYNC, we minimally validate block headers and
103 // occasionally add commitments to them, until we reach our work
104 // threshold (at which point m_download_state is updated to REDOWNLOAD).
105 ret.success = ValidateAndStoreHeadersCommitments(received_headers);
106 if (ret.success) {
107 if (full_headers_message || m_download_state == State::REDOWNLOAD) {
108 // A full headers message means the peer may have more to give
109 // us; also if we just switched to REDOWNLOAD then we need to
110 // re-request headers from the beginning.
111 ret.request_more = true;
112 } else {
114 // If we're in PRESYNC and we get a non-full headers
115 // message, then the peer's chain has ended and definitely
116 // doesn't have enough work, so we can stop our sync.
117 LogPrint(
119 "Initial headers sync aborted with peer=%d: incomplete "
120 "headers message at height=%i (presync phase)\n",
122 }
123 }
124 } else if (m_download_state == State::REDOWNLOAD) {
125 // During REDOWNLOAD, we compare our stored commitments to what we
126 // receive, and add headers to our redownload buffer. When the buffer
127 // gets big enough (meaning that we've checked enough commitments),
128 // we'll return a batch of headers to the caller for processing.
129 ret.success = true;
130 for (const auto &hdr : received_headers) {
132 // Something went wrong -- the peer gave us an unexpected chain.
133 // We could consider looking at the reason for failure and
134 // punishing the peer, but for now just give up on sync.
135 ret.success = false;
136 break;
137 }
138 }
139
140 if (ret.success) {
141 // Return any headers that are ready for acceptance.
143
144 // If we hit our target blockhash, then all remaining headers will
145 // be returned and we can clear any leftover internal state.
146 if (m_redownloaded_headers.empty() &&
149 "Initial headers sync complete with peer=%d: "
150 "releasing all at height=%i (redownload phase)\n",
152 } else if (full_headers_message) {
153 // If the headers message is full, we need to request more.
154 ret.request_more = true;
155 } else {
156 // For some reason our peer gave us a high-work chain, but is
157 // now declining to serve us that full chain again. Give up.
158 // Note that there's no more processing to be done with these
159 // headers, so we can still return success.
160 LogPrint(
162 "Initial headers sync aborted with peer=%d: incomplete "
163 "headers message at height=%i (redownload phase)\n",
165 }
166 }
167 }
168
169 if (!(ret.success && ret.request_more)) {
170 Finalize();
171 }
172 return ret;
173}
174
176 const std::vector<CBlockHeader> &headers) {
177 // The caller should not give us an empty set of headers.
178 Assume(headers.size() > 0);
179 if (headers.size() == 0) {
180 return true;
181 }
182
185 return false;
186 }
187
188 if (headers[0].hashPrevBlock != m_last_header_received.GetHash()) {
189 // Somehow our peer gave us a header that doesn't connect.
190 // This might be benign -- perhaps our peer reorged away from the chain
191 // they were on. Give up on this sync for now (likely we will start a
192 // new sync with a new starting point).
194 "Initial headers sync aborted with peer=%d: non-continuous "
195 "headers at height=%i (presync phase)\n",
197 return false;
198 }
199
200 // If it does connect, (minimally) validate and occasionally store
201 // commitments.
202 for (const auto &hdr : headers) {
204 return false;
205 }
206 }
207
216 "Initial headers sync transition with peer=%d: reached "
217 "sufficient work at height=%i, redownloading from height=%i\n",
219 }
220 return true;
221}
222
224 const CBlockHeader &current) {
227 return false;
228 }
229
230 int next_height = m_current_height + 1;
231
232 // Verify that the difficulty isn't growing too fast; an adversary with
233 // limited hashing capability has a greater chance of producing a high
234 // work chain if they compress the work into as few blocks as possible,
235 // so don't let anyone give a chain that would violate the difficulty
236 // adjustment maximum.
239 current.nBits)) {
240 LogPrintf("Initial headers sync aborted with peer=%d: invalid "
241 "difficulty transition at height=%i (presync phase)\n",
242 m_id, next_height);
243 return false;
244 }
245
246 if (next_height % HEADER_COMMITMENT_PERIOD == m_commit_offset) {
247 // Add a commitment.
250 // The peer's chain is too long; give up.
251 // It's possible the chain grew since we started the sync; so
252 // potentially we could succeed in syncing the peer's chain if we
253 // try again later.
254 LogPrintf("Initial headers sync aborted with peer=%d: exceeded max "
255 "commitments at height=%i (presync phase)\n",
256 m_id, next_height);
257 return false;
258 }
259 }
260
262 m_last_header_received = current;
263 m_current_height = next_height;
264
265 return true;
266}
267
269 const CBlockHeader &header) {
272 return false;
273 }
274
275 int64_t next_height = m_redownload_buffer_last_height + 1;
276
277 // Ensure that we're working on a header that connects to the chain we're
278 // downloading.
281 "Initial headers sync aborted with peer=%d: non-continuous "
282 "headers at height=%i (redownload phase)\n",
283 m_id, next_height);
284 return false;
285 }
286
287 // Check that the difficulty adjustments are within our tolerance:
288 uint32_t previous_nBits{0};
289 if (!m_redownloaded_headers.empty()) {
290 previous_nBits = m_redownloaded_headers.back().nBits;
291 } else {
292 previous_nBits = m_chain_start->nBits;
293 }
294
296 previous_nBits, header.nBits)) {
298 "Initial headers sync aborted with peer=%d: invalid "
299 "difficulty transition at height=%i (redownload phase)\n",
300 m_id, next_height);
301 return false;
302 }
303
304 // Track work on the redownloaded chain
306
309 }
310
311 // If we're at a header for which we previously stored a commitment, verify
312 // it is correct. Failure will result in aborting download.
313 // Also, don't check commitments once we've gotten to our target blockhash;
314 // it's possible our peer has extended its chain between our first sync and
315 // our second, and we don't want to return failure after we've seen our
316 // target blockhash just because we ran out of commitments.
318 next_height % HEADER_COMMITMENT_PERIOD == m_commit_offset) {
319 if (m_header_commitments.size() == 0) {
321 "Initial headers sync aborted with peer=%d: commitment "
322 "overrun at height=%i (redownload phase)\n",
323 m_id, next_height);
324 // Somehow our peer managed to feed us a different chain and
325 // we've run out of commitments.
326 return false;
327 }
328 bool commitment = m_hasher(header.GetHash()) & 1;
329 bool expected_commitment = m_header_commitments.front();
331 if (commitment != expected_commitment) {
333 "Initial headers sync aborted with peer=%d: commitment "
334 "mismatch at height=%i (redownload phase)\n",
335 m_id, next_height);
336 return false;
337 }
338 }
339
340 // Store this header for later processing.
341 m_redownloaded_headers.push_back(header);
344
345 return true;
346}
347
349 std::vector<CBlockHeader> ret;
350
353 return ret;
354 }
355
357 (m_redownloaded_headers.size() > 0 &&
359 ret.emplace_back(m_redownloaded_headers.front().GetFullHeader(
361 m_redownloaded_headers.pop_front();
362 m_redownload_buffer_first_prev_hash = ret.back().GetHash();
363 }
364 return ret;
365}
366
370 return {};
371 }
372
373 auto chain_start_locator = LocatorEntries(m_chain_start);
374 std::vector<BlockHash> locator;
375
377 // During pre-synchronization, we continue from the last header
378 // received.
379 locator.push_back(m_last_header_received.GetHash());
380 }
381
383 // During redownload, we will download from the last received header
384 // that we stored.
385 locator.push_back(m_redownload_buffer_last_hash);
386 }
387
388 locator.insert(locator.end(), chain_start_locator.begin(),
389 chain_start_locator.end());
390
391 return CBlockLocator{std::move(locator)};
392}
arith_uint256 GetBlockProof(const CBlockIndex &block)
Definition: chain.cpp:74
std::vector< BlockHash > LocatorEntries(const CBlockIndex *index)
Construct a list of hash entries to put in a locator.
Definition: chain.cpp:17
static constexpr int64_t MAX_FUTURE_BLOCK_TIME
Maximum amount of time that a block timestamp is allowed to exceed the current network-adjusted time ...
Definition: chain.h:28
#define Assume(val)
Assume is the identity function.
Definition: check.h:97
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:23
BlockHash GetHash() const
Definition: block.cpp:11
uint32_t nBits
Definition: block.h:30
BlockHash hashPrevBlock
Definition: block.h:27
void SetNull()
Definition: block.h:40
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:25
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: blockindex.h:51
int64_t GetMedianTimePast() const
Definition: blockindex.h:172
uint32_t nBits
Definition: blockindex.h:77
BlockHash GetBlockHash() const
Definition: blockindex.h:130
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:38
Fast randomness source.
Definition: random.h:411
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:270
HeadersSyncState(NodeId id, const Consensus::Params &consensus_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:28
arith_uint256 m_redownload_chain_work
The accumulated work on the redownloaded chain.
Definition: headerssync.h:306
@ 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...
CBlockHeader m_last_header_received
Store the latest header received while in PRESYNC (initialized to m_chain_start)
Definition: headerssync.h:276
BlockHash m_redownload_buffer_last_hash
Hash of last header in m_redownloaded_headers (initialized to m_chain_start).
Definition: headerssync.h:296
arith_uint256 m_current_chain_work
Work that we've seen so far on the peer's chain.
Definition: headerssync.h:241
int64_t m_current_height
Height of m_last_header_received.
Definition: headerssync.h:279
const unsigned m_commit_offset
The (secret) offset on the heights for which to create commitments.
Definition: headerssync.h:261
const arith_uint256 m_minimum_required_work
Minimum work that we're looking for on this chain.
Definition: headerssync.h:238
std::vector< CBlockHeader > PopHeadersReadyForAcceptance()
Return a set of headers that satisfy our proof-of-work threshold.
bool ValidateAndStoreHeadersCommitments(const std::vector< CBlockHeader > &headers)
Only called in PRESYNC.
const Consensus::Params & m_consensus_params
We use the consensus params in our anti-DoS calculations.
Definition: headerssync.h:229
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:316
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:253
BlockHash 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:303
const NodeId m_id
NodeId of the peer (used for log messages)
Definition: headerssync.h:226
int64_t m_redownload_buffer_last_height
Height of last header in m_redownloaded_headers.
Definition: headerssync.h:289
std::deque< CompressedHeader > m_redownloaded_headers
During phase 2 (REDOWNLOAD), we buffer redownloaded headers in memory until enough commitments have b...
Definition: headerssync.h:286
const SaltedBlockHashHasher m_hasher
m_hasher is a salted hasher for making our 1-bit commitments to headers we've seen.
Definition: headerssync.h:247
ProcessingResult ProcessNextHeaders(const std::vector< CBlockHeader > &received_headers, bool full_headers_message)
Process a batch of headers, once a sync via this mechanism has started.
Definition: headerssync.cpp:86
bool m_process_all_remaining_headers
Set this to true once we encounter the target blockheader during phase 2 (REDOWNLOAD).
Definition: headerssync.h:313
void Finalize()
Clear out all download state that might be in progress (freeing any used memory), and mark this objec...
Definition: headerssync.cpp:68
const CBlockIndex * m_chain_start
Store the last block in our block index that the peer's chain builds from.
Definition: headerssync.h:235
CBlockLocator NextHeadersRequestLocator() const
Issue the next GETHEADERS message to our peer.
256-bit unsigned big integer.
void SetNull()
Definition: uint256.h:41
std::string ToString() const
void push_back(bool val)
Definition: bitdeque.h:408
reference front()
Definition: bitdeque.h:393
void pop_front()
Definition: bitdeque.h:435
size_type size() const noexcept
Count the number of bits in the container.
Definition: bitdeque.h:323
int64_t NodeId
Definition: eviction.h:16
constexpr size_t REDOWNLOAD_BUFFER_SIZE
Only feed headers to validation once this many headers on top have been received and validated agains...
Definition: headerssync.cpp:22
constexpr size_t HEADER_COMMITMENT_PERIOD
Store a commitment to a header every HEADER_COMMITMENT_PERIOD blocks.
Definition: headerssync.cpp:17
#define LogPrint(category,...)
Definition: logging.h:452
#define LogPrintf(...)
Definition: logging.h:424
unsigned int nHeight
@ NET
Definition: logging.h:69
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:47
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:108
Parameters that influence chain consensus.
Definition: params.h:34
Result data structure for ProcessNextHeaders.
Definition: headerssync.h:154
std::vector< CBlockHeader > pow_validated_headers
Definition: headerssync.h:155
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
Definition: time.h:25
NodeClock::time_point GetAdjustedTime()
Definition: timedata.cpp:35
void ClearShrink(V &v) noexcept
Clear a vector (or std::deque) and release its allocated memory.
Definition: vector.h:52