Bitcoin ABC 0.26.3
P2P Digital Currency
Loading...
Searching...
No Matches
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
11// The two constants below are computed using the simulation script on
12// https://gist.github.com/sipa/016ae445c132cdf65a2791534dfb7ae1
13// with MINCHAINWORK_HEADERS = 826150 and TIME = datetime(2027, 1, 1)
14
16constexpr size_t HEADER_COMMITMENT_PERIOD{610};
17
20// 14521/610 = ~23.8 commitments
21constexpr size_t REDOWNLOAD_BUFFER_SIZE{14521};
22
23// Our memory analysis assumes 48 bytes for a CompressedHeader (so we should
24// re-calculate parameters if we compress further)
25static_assert(sizeof(CompressedHeader) == 48);
26
31 : m_id(id), m_consensus_params(consensus_params),
32 m_chain_start(chain_start),
33 m_minimum_required_work(minimum_required_work),
34 m_current_chain_work(chain_start->nChainWork),
35 m_commit_offset(GetRand<unsigned>(HEADER_COMMITMENT_PERIOD)),
36 m_last_header_received(m_chain_start->GetBlockHeader()),
37 m_current_height(chain_start->nHeight) {
38 // Estimate the number of blocks that could possibly exist on the peer's
39 // chain *right now* using 6 blocks/second (fastest blockrate given the MTP
40 // rule) times the number of seconds from the last allowed block until
41 // today. This serves as a memory bound on how many commitments we might
42 // store from this peer, and we can safely give up syncing if the peer
43 // exceeds this bound, because it's not possible for a consensus-valid
44 // chain to be longer than this (at the current time -- in the future we
45 // could try again, if necessary, to sync a longer chain).
47 6 *
49 NodeSeconds{std::chrono::seconds{
50 chain_start->GetMedianTimePast()}}) +
53
55 "Initial headers sync started with peer=%d: height=%i, "
56 "max_commitments=%i, min_work=%s\n",
59}
60
78
85 const std::vector<CBlockHeader> &received_headers,
86 const bool full_headers_message) {
88
89 Assume(!received_headers.empty());
90 if (received_headers.empty()) {
91 return ret;
92 }
93
96 return ret;
97 }
98
100 // During PRESYNC, we minimally validate block headers and
101 // occasionally add commitments to them, until we reach our work
102 // threshold (at which point m_download_state is updated to REDOWNLOAD).
104 if (ret.success) {
106 // A full headers message means the peer may have more to give
107 // us; also if we just switched to REDOWNLOAD then we need to
108 // re-request headers from the beginning.
109 ret.request_more = true;
110 } else {
112 // If we're in PRESYNC and we get a non-full headers
113 // message, then the peer's chain has ended and definitely
114 // doesn't have enough work, so we can stop our sync.
115 LogPrint(
117 "Initial headers sync aborted with peer=%d: incomplete "
118 "headers message at height=%i (presync phase)\n",
120 }
121 }
122 } else if (m_download_state == State::REDOWNLOAD) {
123 // During REDOWNLOAD, we compare our stored commitments to what we
124 // receive, and add headers to our redownload buffer. When the buffer
125 // gets big enough (meaning that we've checked enough commitments),
126 // we'll return a batch of headers to the caller for processing.
127 ret.success = true;
128 for (const auto &hdr : received_headers) {
130 // Something went wrong -- the peer gave us an unexpected chain.
131 // We could consider looking at the reason for failure and
132 // punishing the peer, but for now just give up on sync.
133 ret.success = false;
134 break;
135 }
136 }
137
138 if (ret.success) {
139 // Return any headers that are ready for acceptance.
140 ret.pow_validated_headers = PopHeadersReadyForAcceptance();
141
142 // If we hit our target blockhash, then all remaining headers will
143 // be returned and we can clear any leftover internal state.
144 if (m_redownloaded_headers.empty() &&
147 "Initial headers sync complete with peer=%d: "
148 "releasing all at height=%i (redownload phase)\n",
150 } else if (full_headers_message) {
151 // If the headers message is full, we need to request more.
152 ret.request_more = true;
153 } else {
154 // For some reason our peer gave us a high-work chain, but is
155 // now declining to serve us that full chain again. Give up.
156 // Note that there's no more processing to be done with these
157 // headers, so we can still return success.
158 LogPrint(
160 "Initial headers sync aborted with peer=%d: incomplete "
161 "headers message at height=%i (redownload phase)\n",
163 }
164 }
165 }
166
167 if (!(ret.success && ret.request_more)) {
168 Finalize();
169 }
170 return ret;
171}
172
174 const std::vector<CBlockHeader> &headers) {
175 // The caller should not give us an empty set of headers.
176 Assume(headers.size() > 0);
177 if (headers.size() == 0) {
178 return true;
179 }
180
183 return false;
184 }
185
186 if (headers[0].hashPrevBlock != m_last_header_received.GetHash()) {
187 // Somehow our peer gave us a header that doesn't connect.
188 // This might be benign -- perhaps our peer reorged away from the chain
189 // they were on. Give up on this sync for now (likely we will start a
190 // new sync with a new starting point).
192 "Initial headers sync aborted with peer=%d: non-continuous "
193 "headers at height=%i (presync phase)\n",
195 return false;
196 }
197
198 // If it does connect, (minimally) validate and occasionally store
199 // commitments.
200 for (const auto &hdr : headers) {
202 return false;
203 }
204 }
205
214 "Initial headers sync transition with peer=%d: reached "
215 "sufficient work at height=%i, redownloading from height=%i\n",
217 }
218 return true;
219}
220
222 const CBlockHeader &current) {
225 return false;
226 }
227
229
230 // Verify that the difficulty isn't growing too fast; an adversary with
231 // limited hashing capability has a greater chance of producing a high
232 // work chain if they compress the work into as few blocks as possible,
233 // so don't let anyone give a chain that would violate the difficulty
234 // adjustment maximum.
237 current.nBits)) {
238 LogPrintf("Initial headers sync aborted with peer=%d: invalid "
239 "difficulty transition at height=%i (presync phase)\n",
241 return false;
242 }
243
245 // Add a commitment.
248 // The peer's chain is too long; give up.
249 // It's possible the chain grew since we started the sync; so
250 // potentially we could succeed in syncing the peer's chain if we
251 // try again later.
252 LogPrintf("Initial headers sync aborted with peer=%d: exceeded max "
253 "commitments at height=%i (presync phase)\n",
255 return false;
256 }
257 }
258
262
263 return true;
264}
265
267 const CBlockHeader &header) {
270 return false;
271 }
272
274
275 // Ensure that we're working on a header that connects to the chain we're
276 // downloading.
279 "Initial headers sync aborted with peer=%d: non-continuous "
280 "headers at height=%i (redownload phase)\n",
282 return false;
283 }
284
285 // Check that the difficulty adjustments are within our tolerance:
287 if (!m_redownloaded_headers.empty()) {
289 } else {
291 }
292
294 previous_nBits, header.nBits)) {
296 "Initial headers sync aborted with peer=%d: invalid "
297 "difficulty transition at height=%i (redownload phase)\n",
299 return false;
300 }
301
302 // Track work on the redownloaded chain
304
307 }
308
309 // If we're at a header for which we previously stored a commitment, verify
310 // it is correct. Failure will result in aborting download.
311 // Also, don't check commitments once we've gotten to our target blockhash;
312 // it's possible our peer has extended its chain between our first sync and
313 // our second, and we don't want to return failure after we've seen our
314 // target blockhash just because we ran out of commitments.
317 if (m_header_commitments.size() == 0) {
319 "Initial headers sync aborted with peer=%d: commitment "
320 "overrun at height=%i (redownload phase)\n",
322 // Somehow our peer managed to feed us a different chain and
323 // we've run out of commitments.
324 return false;
325 }
326 bool commitment = m_hasher(header.GetHash()) & 1;
331 "Initial headers sync aborted with peer=%d: commitment "
332 "mismatch at height=%i (redownload phase)\n",
334 return false;
335 }
336 }
337
338 // Store this header for later processing.
339 m_redownloaded_headers.push_back(header);
342
343 return true;
344}
345
347 std::vector<CBlockHeader> ret;
348
351 return ret;
352 }
353
355 (m_redownloaded_headers.size() > 0 &&
357 ret.emplace_back(m_redownloaded_headers.front().GetFullHeader(
359 m_redownloaded_headers.pop_front();
360 m_redownload_buffer_first_prev_hash = ret.back().GetHash();
361 }
362 return ret;
363}
364
368 return {};
369 }
370
372 std::vector<BlockHash> locator;
373
375 // During pre-synchronization, we continue from the last header
376 // received.
378 }
379
381 // During redownload, we will download from the last received header
382 // that we stored.
384 }
385
386 locator.insert(locator.end(), chain_start_locator.begin(),
387 chain_start_locator.end());
388
389 return CBlockLocator{std::move(locator)};
390}
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
uint32_t nBits
Definition blockindex.h:93
BlockHash GetBlockHash() const
Definition blockindex.h:146
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,...
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).
arith_uint256 m_redownload_chain_work
The accumulated work on the redownloaded chain.
@ 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)
BlockHash m_redownload_buffer_last_hash
Hash of last header in m_redownloaded_headers (initialized to m_chain_start).
arith_uint256 m_current_chain_work
Work that we've seen so far on the peer's chain.
int64_t m_current_height
Height of m_last_header_received.
const unsigned m_commit_offset
The (secret) offset on the heights for which to create commitments.
const arith_uint256 m_minimum_required_work
Minimum work that we're looking for on this chain.
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.
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.
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.
BlockHash m_redownload_buffer_first_prev_hash
The hashPrevBlock entry for the first header in m_redownloaded_headers We need this to reconstruct th...
const NodeId m_id
NodeId of the peer (used for log messages)
int64_t m_redownload_buffer_last_height
Height of last header in m_redownloaded_headers.
std::deque< CompressedHeader > m_redownloaded_headers
During phase 2 (REDOWNLOAD), we buffer redownloaded headers in memory until enough commitments have b...
const SaltedBlockHashHasher m_hasher
m_hasher is a salted hasher for making our 1-bit commitments to headers we've seen.
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.
bool m_process_all_remaining_headers
Set this to true once we encounter the target blockheader during phase 2 (REDOWNLOAD).
void Finalize()
Clear out all download state that might be in progress (freeing any used memory), and mark this objec...
const CBlockIndex * m_chain_start
Store the last block in our block index that the peer's chain builds from.
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
constexpr size_t REDOWNLOAD_BUFFER_SIZE
Only feed headers to validation once this many headers on top have been received and validated agains...
constexpr size_t HEADER_COMMITMENT_PERIOD
Store a commitment to a header every HEADER_COMMITMENT_PERIOD blocks.
#define LogPrint(category,...)
Definition logging.h:238
#define LogPrintf(...)
Definition logging.h:227
unsigned int nHeight
@ NET
Definition logging.h:40
int64_t NodeId
Definition nodeid.h:10
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:105
Parameters that influence chain consensus.
Definition params.h:34
Result data structure for ProcessNextHeaders.
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
Definition time.h:25
NodeClock::time_point GetAdjustedTime()
Definition timedata.cpp:35