Bitcoin ABC 0.32.4
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(GetRand<unsigned>(HEADER_COMMITMENT_PERIOD)),
37 m_last_header_received(m_chain_start->GetBlockHeader()),
38 m_current_height(chain_start->nHeight) {
39 // Estimate the number of blocks that could possibly exist on the peer's
40 // chain *right now* using 6 blocks/second (fastest blockrate given the MTP
41 // rule) times the number of seconds from the last allowed block until
42 // today. This serves as a memory bound on how many commitments we might
43 // store from this peer, and we can safely give up syncing if the peer
44 // exceeds this bound, because it's not possible for a consensus-valid
45 // chain to be longer than this (at the current time -- in the future we
46 // could try again, if necessary, to sync a longer chain).
48 6 *
49 (Ticks<std::chrono::seconds>(GetAdjustedTime() -
50 NodeSeconds{std::chrono::seconds{
51 chain_start->GetMedianTimePast()}}) +
54
56 "Initial headers sync started with peer=%d: height=%i, "
57 "max_commitments=%i, min_work=%s\n",
60}
61
76
78}
79
86 const std::vector<CBlockHeader> &received_headers,
87 const bool full_headers_message) {
89
90 Assume(!received_headers.empty());
91 if (received_headers.empty()) {
92 return ret;
93 }
94
97 return ret;
98 }
99
101 // During PRESYNC, we minimally validate block headers and
102 // occasionally add commitments to them, until we reach our work
103 // threshold (at which point m_download_state is updated to REDOWNLOAD).
104 ret.success = ValidateAndStoreHeadersCommitments(received_headers);
105 if (ret.success) {
106 if (full_headers_message || m_download_state == State::REDOWNLOAD) {
107 // A full headers message means the peer may have more to give
108 // us; also if we just switched to REDOWNLOAD then we need to
109 // re-request headers from the beginning.
110 ret.request_more = true;
111 } else {
113 // If we're in PRESYNC and we get a non-full headers
114 // message, then the peer's chain has ended and definitely
115 // doesn't have enough work, so we can stop our sync.
116 LogPrint(
118 "Initial headers sync aborted with peer=%d: incomplete "
119 "headers message at height=%i (presync phase)\n",
121 }
122 }
123 } else if (m_download_state == State::REDOWNLOAD) {
124 // During REDOWNLOAD, we compare our stored commitments to what we
125 // receive, and add headers to our redownload buffer. When the buffer
126 // gets big enough (meaning that we've checked enough commitments),
127 // we'll return a batch of headers to the caller for processing.
128 ret.success = true;
129 for (const auto &hdr : received_headers) {
131 // Something went wrong -- the peer gave us an unexpected chain.
132 // We could consider looking at the reason for failure and
133 // punishing the peer, but for now just give up on sync.
134 ret.success = false;
135 break;
136 }
137 }
138
139 if (ret.success) {
140 // Return any headers that are ready for acceptance.
142
143 // If we hit our target blockhash, then all remaining headers will
144 // be returned and we can clear any leftover internal state.
145 if (m_redownloaded_headers.empty() &&
148 "Initial headers sync complete with peer=%d: "
149 "releasing all at height=%i (redownload phase)\n",
151 } else if (full_headers_message) {
152 // If the headers message is full, we need to request more.
153 ret.request_more = true;
154 } else {
155 // For some reason our peer gave us a high-work chain, but is
156 // now declining to serve us that full chain again. Give up.
157 // Note that there's no more processing to be done with these
158 // headers, so we can still return success.
159 LogPrint(
161 "Initial headers sync aborted with peer=%d: incomplete "
162 "headers message at height=%i (redownload phase)\n",
164 }
165 }
166 }
167
168 if (!(ret.success && ret.request_more)) {
169 Finalize();
170 }
171 return ret;
172}
173
175 const std::vector<CBlockHeader> &headers) {
176 // The caller should not give us an empty set of headers.
177 Assume(headers.size() > 0);
178 if (headers.size() == 0) {
179 return true;
180 }
181
184 return false;
185 }
186
187 if (headers[0].hashPrevBlock != m_last_header_received.GetHash()) {
188 // Somehow our peer gave us a header that doesn't connect.
189 // This might be benign -- perhaps our peer reorged away from the chain
190 // they were on. Give up on this sync for now (likely we will start a
191 // new sync with a new starting point).
193 "Initial headers sync aborted with peer=%d: non-continuous "
194 "headers at height=%i (presync phase)\n",
196 return false;
197 }
198
199 // If it does connect, (minimally) validate and occasionally store
200 // commitments.
201 for (const auto &hdr : headers) {
203 return false;
204 }
205 }
206
215 "Initial headers sync transition with peer=%d: reached "
216 "sufficient work at height=%i, redownloading from height=%i\n",
218 }
219 return true;
220}
221
223 const CBlockHeader &current) {
226 return false;
227 }
228
229 int next_height = m_current_height + 1;
230
231 // Verify that the difficulty isn't growing too fast; an adversary with
232 // limited hashing capability has a greater chance of producing a high
233 // work chain if they compress the work into as few blocks as possible,
234 // so don't let anyone give a chain that would violate the difficulty
235 // adjustment maximum.
238 current.nBits)) {
239 LogPrintf("Initial headers sync aborted with peer=%d: invalid "
240 "difficulty transition at height=%i (presync phase)\n",
241 m_id, next_height);
242 return false;
243 }
244
245 if (next_height % HEADER_COMMITMENT_PERIOD == m_commit_offset) {
246 // Add a commitment.
249 // The peer's chain is too long; give up.
250 // It's possible the chain grew since we started the sync; so
251 // potentially we could succeed in syncing the peer's chain if we
252 // try again later.
253 LogPrintf("Initial headers sync aborted with peer=%d: exceeded max "
254 "commitments at height=%i (presync phase)\n",
255 m_id, next_height);
256 return false;
257 }
258 }
259
261 m_last_header_received = current;
262 m_current_height = next_height;
263
264 return true;
265}
266
268 const CBlockHeader &header) {
271 return false;
272 }
273
274 int64_t next_height = m_redownload_buffer_last_height + 1;
275
276 // Ensure that we're working on a header that connects to the chain we're
277 // downloading.
280 "Initial headers sync aborted with peer=%d: non-continuous "
281 "headers at height=%i (redownload phase)\n",
282 m_id, next_height);
283 return false;
284 }
285
286 // Check that the difficulty adjustments are within our tolerance:
287 uint32_t previous_nBits{0};
288 if (!m_redownloaded_headers.empty()) {
289 previous_nBits = m_redownloaded_headers.back().nBits;
290 } else {
291 previous_nBits = m_chain_start->nBits;
292 }
293
295 previous_nBits, header.nBits)) {
297 "Initial headers sync aborted with peer=%d: invalid "
298 "difficulty transition at height=%i (redownload phase)\n",
299 m_id, next_height);
300 return false;
301 }
302
303 // Track work on the redownloaded chain
305
308 }
309
310 // If we're at a header for which we previously stored a commitment, verify
311 // it is correct. Failure will result in aborting download.
312 // Also, don't check commitments once we've gotten to our target blockhash;
313 // it's possible our peer has extended its chain between our first sync and
314 // our second, and we don't want to return failure after we've seen our
315 // target blockhash just because we ran out of commitments.
317 next_height % HEADER_COMMITMENT_PERIOD == m_commit_offset) {
318 if (m_header_commitments.size() == 0) {
320 "Initial headers sync aborted with peer=%d: commitment "
321 "overrun at height=%i (redownload phase)\n",
322 m_id, next_height);
323 // Somehow our peer managed to feed us a different chain and
324 // we've run out of commitments.
325 return false;
326 }
327 bool commitment = m_hasher(header.GetHash()) & 1;
328 bool expected_commitment = m_header_commitments.front();
330 if (commitment != expected_commitment) {
332 "Initial headers sync aborted with peer=%d: commitment "
333 "mismatch at height=%i (redownload phase)\n",
334 m_id, next_height);
335 return false;
336 }
337 }
338
339 // Store this header for later processing.
340 m_redownloaded_headers.push_back(header);
343
344 return true;
345}
346
348 std::vector<CBlockHeader> ret;
349
352 return ret;
353 }
354
356 (m_redownloaded_headers.size() > 0 &&
358 ret.emplace_back(m_redownloaded_headers.front().GetFullHeader(
360 m_redownloaded_headers.pop_front();
361 m_redownload_buffer_first_prev_hash = ret.back().GetHash();
362 }
363 return ret;
364}
365
369 return {};
370 }
371
372 auto chain_start_locator = LocatorEntries(m_chain_start);
373 std::vector<BlockHash> locator;
374
376 // During pre-synchronization, we continue from the last header
377 // received.
378 locator.push_back(m_last_header_received.GetHash());
379 }
380
382 // During redownload, we will download from the last received header
383 // that we stored.
384 locator.push_back(m_redownload_buffer_last_hash);
385 }
386
387 locator.insert(locator.end(), chain_start_locator.begin(),
388 chain_start_locator.end());
389
390 return CBlockLocator{std::move(locator)};
391}
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
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:85
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:67
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
T GetRand(T nMax=std::numeric_limits< T >::max()) noexcept
Generate a uniform random integer of type T in the range [0..nMax) nMax defaults to std::numeric_limi...
Definition: random.h:85
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:109
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