Bitcoin Core 30.99.0
P2P Digital Currency
chain.h
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2022 The Bitcoin Core developers
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#ifndef BITCOIN_CHAIN_H
7#define BITCOIN_CHAIN_H
8
9#include <arith_uint256.h>
10#include <consensus/params.h>
11#include <flatfile.h>
12#include <kernel/cs_main.h>
13#include <primitives/block.h>
14#include <serialize.h>
15#include <sync.h>
16#include <uint256.h>
17#include <util/time.h>
18
19#include <algorithm>
20#include <cassert>
21#include <cstdint>
22#include <string>
23#include <vector>
24
29static constexpr int64_t MAX_FUTURE_BLOCK_TIME = 2 * 60 * 60;
30
37static constexpr int64_t TIMESTAMP_WINDOW = MAX_FUTURE_BLOCK_TIME;
39static constexpr int32_t SEQ_ID_BEST_CHAIN_FROM_DISK = 0;
40static constexpr int32_t SEQ_ID_INIT_FROM_DISK = 1;
41
48static constexpr int64_t MAX_BLOCK_TIME_GAP = 90 * 60;
49
50enum BlockStatus : uint32_t {
53
56
60
70
74
78
82
86
90
92
95};
96
103{
104public:
106 const uint256* phashBlock{nullptr};
107
110
113
115 int nHeight{0};
116
118 int nFile GUARDED_BY(::cs_main){0};
119
121 unsigned int nDataPos GUARDED_BY(::cs_main){0};
122
124 unsigned int nUndoPos GUARDED_BY(::cs_main){0};
125
128
132 unsigned int nTx{0};
133
138 uint64_t m_chain_tx_count{0};
139
146 uint32_t nStatus GUARDED_BY(::cs_main){0};
147
149 int32_t nVersion{0};
151 uint32_t nTime{0};
152 uint32_t nBits{0};
153 uint32_t nNonce{0};
154
159
161 unsigned int nTimeMax{0};
162
163 explicit CBlockIndex(const CBlockHeader& block)
164 : nVersion{block.nVersion},
166 nTime{block.nTime},
167 nBits{block.nBits},
168 nNonce{block.nNonce}
169 {
170 }
171
173 {
176 if (nStatus & BLOCK_HAVE_DATA) {
177 ret.nFile = nFile;
178 ret.nPos = nDataPos;
179 }
180 return ret;
181 }
182
184 {
187 if (nStatus & BLOCK_HAVE_UNDO) {
188 ret.nFile = nFile;
189 ret.nPos = nUndoPos;
190 }
191 return ret;
192 }
193
195 {
196 CBlockHeader block;
197 block.nVersion = nVersion;
198 if (pprev)
201 block.nTime = nTime;
202 block.nBits = nBits;
203 block.nNonce = nNonce;
204 return block;
205 }
206
208 {
209 assert(phashBlock != nullptr);
210 return *phashBlock;
211 }
212
223 bool HaveNumChainTxs() const { return m_chain_tx_count != 0; }
224
226 {
227 return NodeSeconds{std::chrono::seconds{nTime}};
228 }
229
230 int64_t GetBlockTime() const
231 {
232 return (int64_t)nTime;
233 }
234
235 int64_t GetBlockTimeMax() const
236 {
237 return (int64_t)nTimeMax;
238 }
239
240 static constexpr int nMedianTimeSpan = 11;
241
242 int64_t GetMedianTimePast() const
243 {
244 int64_t pmedian[nMedianTimeSpan];
245 int64_t* pbegin = &pmedian[nMedianTimeSpan];
246 int64_t* pend = &pmedian[nMedianTimeSpan];
247
248 const CBlockIndex* pindex = this;
249 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
250 *(--pbegin) = pindex->GetBlockTime();
251
252 std::sort(pbegin, pend);
253 return pbegin[(pend - pbegin) / 2];
254 }
255
256 std::string ToString() const;
257
259 bool IsValid(enum BlockStatus nUpTo) const
261 {
263 assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
264 if (nStatus & BLOCK_FAILED_MASK)
265 return false;
266 return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
267 }
268
272 {
274 assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
275 if (nStatus & BLOCK_FAILED_MASK) return false;
276
277 if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
278 nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
279 return true;
280 }
281 return false;
282 }
283
285 void BuildSkip();
286
288 CBlockIndex* GetAncestor(int height);
289 const CBlockIndex* GetAncestor(int height) const;
290
291 CBlockIndex() = default;
292 ~CBlockIndex() = default;
293
294protected:
304 CBlockIndex(const CBlockIndex&) = default;
308};
309
312int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params&);
314const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb);
315
316
319{
326 static constexpr int DUMMY_VERSION = 259900;
327
328public:
330
332 {
333 hashPrev = uint256();
334 }
335
336 explicit CDiskBlockIndex(const CBlockIndex* pindex) : CBlockIndex(*pindex)
337 {
339 }
340
342 {
344 int _nVersion = DUMMY_VERSION;
346
348 READWRITE(VARINT(obj.nStatus));
349 READWRITE(VARINT(obj.nTx));
351 if (obj.nStatus & BLOCK_HAVE_DATA) READWRITE(VARINT(obj.nDataPos));
352 if (obj.nStatus & BLOCK_HAVE_UNDO) READWRITE(VARINT(obj.nUndoPos));
353
354 // block header
355 READWRITE(obj.nVersion);
356 READWRITE(obj.hashPrev);
357 READWRITE(obj.hashMerkleRoot);
358 READWRITE(obj.nTime);
359 READWRITE(obj.nBits);
360 READWRITE(obj.nNonce);
361 }
362
364 {
365 CBlockHeader block;
366 block.nVersion = nVersion;
367 block.hashPrevBlock = hashPrev;
369 block.nTime = nTime;
370 block.nBits = nBits;
371 block.nNonce = nNonce;
372 return block.GetHash();
373 }
374
376 std::string ToString() = delete;
377};
378
381{
382private:
383 std::vector<CBlockIndex*> vChain;
384
385public:
386 CChain() = default;
387 CChain(const CChain&) = delete;
388 CChain& operator=(const CChain&) = delete;
389
392 {
393 return vChain.size() > 0 ? vChain[0] : nullptr;
394 }
395
398 {
399 return vChain.size() > 0 ? vChain[vChain.size() - 1] : nullptr;
400 }
401
404 {
405 if (nHeight < 0 || nHeight >= (int)vChain.size())
406 return nullptr;
407 return vChain[nHeight];
408 }
409
411 bool Contains(const CBlockIndex* pindex) const
412 {
413 return (*this)[pindex->nHeight] == pindex;
414 }
415
417 CBlockIndex* Next(const CBlockIndex* pindex) const
418 {
419 if (Contains(pindex))
420 return (*this)[pindex->nHeight + 1];
421 else
422 return nullptr;
423 }
424
426 int Height() const
427 {
428 return int(vChain.size()) - 1;
429 }
430
432 void SetTip(CBlockIndex& block);
433
435 const CBlockIndex* FindFork(const CBlockIndex* pindex) const;
436
438 CBlockIndex* FindEarliestAtLeast(int64_t nTime, int height) const;
439};
440
443
445std::vector<uint256> LocatorEntries(const CBlockIndex* index);
446
447#endif // BITCOIN_CHAIN_H
int ret
BlockStatus
Definition: chain.h:50
@ BLOCK_VALID_CHAIN
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends,...
Definition: chain.h:73
@ BLOCK_VALID_MASK
All validity bits.
Definition: chain.h:80
@ BLOCK_VALID_TRANSACTIONS
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid,...
Definition: chain.h:69
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok.
Definition: chain.h:77
@ BLOCK_VALID_RESERVED
Reserved (was BLOCK_VALID_HEADER).
Definition: chain.h:55
@ BLOCK_STATUS_RESERVED
Unused flag that was previously set on assumeutxo snapshot blocks and their ancestors before they wer...
Definition: chain.h:93
@ BLOCK_VALID_TREE
All parent headers found, difficulty matches, timestamp >= median previous.
Definition: chain.h:59
@ BLOCK_HAVE_UNDO
undo data available in rev*.dat
Definition: chain.h:84
@ BLOCK_HAVE_DATA
full block available in blk*.dat
Definition: chain.h:83
@ BLOCK_FAILED_CHILD
descends from failed block
Definition: chain.h:88
@ BLOCK_FAILED_MASK
Definition: chain.h:89
@ BLOCK_FAILED_VALID
stage after last reached validness failed
Definition: chain.h:87
@ BLOCK_OPT_WITNESS
block data in blk*.dat was received with a witness-enforcing client
Definition: chain.h:91
@ BLOCK_HAVE_MASK
Definition: chain.h:85
@ BLOCK_VALID_UNKNOWN
Unused.
Definition: chain.h:52
static constexpr int32_t SEQ_ID_BEST_CHAIN_FROM_DISK
Init values for CBlockIndex nSequenceId when loaded from disk.
Definition: chain.h:39
arith_uint256 GetBlockProof(const CBlockIndex &block)
Definition: chain.cpp:121
std::vector< uint256 > LocatorEntries(const CBlockIndex *index)
Construct a list of hash entries to put in a locator.
Definition: chain.cpp:26
static constexpr int32_t SEQ_ID_INIT_FROM_DISK
Definition: chain.h:40
CBlockLocator GetLocator(const CBlockIndex *index)
Get a locator for a block index entry.
Definition: chain.cpp:45
int64_t GetBlockProofEquivalentTime(const CBlockIndex &to, const CBlockIndex &from, const CBlockIndex &tip, const Consensus::Params &)
Return the time it would take to redo the work difference between from and to, assuming the current h...
Definition: chain.cpp:136
static constexpr int64_t MAX_BLOCK_TIME_GAP
Maximum gap between node time and block time used for the "Catching up..." mode in GUI.
Definition: chain.h:48
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
static constexpr int64_t TIMESTAMP_WINDOW
Timestamp window used as a grace period by code that compares external timestamps (such as timestamps...
Definition: chain.h:37
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the forking point between two chain tips.
Definition: chain.cpp:155
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:22
uint32_t nNonce
Definition: block.h:30
uint32_t nBits
Definition: block.h:29
uint32_t nTime
Definition: block.h:28
int32_t nVersion
Definition: block.h:25
uint256 hashPrevBlock
Definition: block.h:26
uint256 hashMerkleRoot
Definition: block.h:27
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:103
uint256 hashMerkleRoot
Definition: chain.h:150
bool IsValid(enum BlockStatus nUpTo) const EXCLUSIVE_LOCKS_REQUIRED(
Check whether this block index entry is valid up to the passed validity level.
Definition: chain.h:259
uint32_t nStatus GUARDED_BY(::cs_main)
Verification status of this block.
Definition: chain.h:146
std::string ToString() const
Definition: chain.cpp:10
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:109
uint64_t m_chain_tx_count
(memory only) Number of transactions in the chain up to and including this block.
Definition: chain.h:138
void BuildSkip()
Build the skiplist pointer for this entry.
Definition: chain.cpp:115
CBlockHeader GetBlockHeader() const
Definition: chain.h:194
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:127
CBlockIndex()=default
CBlockIndex & operator=(const CBlockIndex &)=delete
unsigned int nDataPos GUARDED_BY(::cs_main)
Byte offset within blk?????.dat where this block's data is stored.
Definition: chain.h:121
unsigned int nUndoPos GUARDED_BY(::cs_main)
Byte offset within rev?????.dat where this block's undo data is stored.
Definition: chain.h:124
CBlockIndex & operator=(CBlockIndex &&)=delete
bool HaveNumChainTxs() const
Check whether this block and all previous blocks back to the genesis block or an assumeutxo snapshot ...
Definition: chain.h:223
uint32_t nTime
Definition: chain.h:151
unsigned int nTimeMax
(memory only) Maximum nTime in the chain up to and including this block.
Definition: chain.h:161
int32_t nSequenceId
(memory only) Sequential id assigned to distinguish order in which blocks are received.
Definition: chain.h:158
uint32_t nNonce
Definition: chain.h:153
uint256 GetBlockHash() const
Definition: chain.h:207
~CBlockIndex()=default
int64_t GetBlockTime() const
Definition: chain.h:230
int64_t GetMedianTimePast() const
Definition: chain.h:242
FlatFilePos GetUndoPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: chain.h:183
uint32_t nBits
Definition: chain.h:152
bool RaiseValidity(enum BlockStatus nUpTo) EXCLUSIVE_LOCKS_REQUIRED(
Raise the validity level of this block index entry.
Definition: chain.h:271
CBlockIndex * pskip
pointer to the index of some further predecessor of this block
Definition: chain.h:112
int64_t GetBlockTimeMax() const
Definition: chain.h:235
CBlockIndex(CBlockIndex &&)=delete
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:132
CBlockIndex(const CBlockHeader &block)
Definition: chain.h:163
NodeSeconds Time() const
Definition: chain.h:225
int32_t nVersion
block header
Definition: chain.h:149
CBlockIndex(const CBlockIndex &)=default
CBlockIndex should not allow public copy construction because equality comparison via pointer is very...
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: chain.cpp:110
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:115
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: chain.h:172
int nFile GUARDED_BY(::cs_main)
Which # file this block is stored in (blk?????.dat)
Definition: chain.h:118
static constexpr int nMedianTimeSpan
Definition: chain.h:240
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Definition: chain.h:106
An in-memory indexed chain of blocks.
Definition: chain.h:381
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:397
CChain(const CChain &)=delete
CChain & operator=(const CChain &)=delete
void SetTip(CBlockIndex &block)
Set/initialize a chain with a given tip.
Definition: chain.cpp:16
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
Definition: chain.h:391
CChain()=default
CBlockIndex * operator[](int nHeight) const
Returns the index entry at a particular height in this chain, or nullptr if no such height exists.
Definition: chain.h:403
CBlockIndex * Next(const CBlockIndex *pindex) const
Find the successor of a block in this chain, or nullptr if the given index is not found or is the tip...
Definition: chain.h:417
CBlockIndex * FindEarliestAtLeast(int64_t nTime, int height) const
Find the earliest block with timestamp equal or greater than the given time and height equal or great...
Definition: chain.cpp:61
int Height() const
Return the maximal height in the chain.
Definition: chain.h:426
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
Definition: chain.cpp:50
std::vector< CBlockIndex * > vChain
Definition: chain.h:383
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:411
Used to marshal pointers into hashes for db storage.
Definition: chain.h:319
std::string ToString()=delete
static constexpr int DUMMY_VERSION
Historically CBlockLocator's version field has been written to disk streams as the client version,...
Definition: chain.h:326
uint256 hashPrev
Definition: chain.h:329
uint256 GetBlockHash()=delete
uint256 ConstructBlockHash() const
Definition: chain.h:363
SERIALIZE_METHODS(CDiskBlockIndex, obj)
Definition: chain.h:341
CDiskBlockIndex()
Definition: chain.h:331
CDiskBlockIndex(const CBlockIndex *pindex)
Definition: chain.h:336
256-bit unsigned big integer.
256-bit opaque blob.
Definition: uint256.h:196
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
unsigned int nHeight
#define VARINT(obj)
Definition: serialize.h:491
#define VARINT_MODE(obj, mode)
Definition: serialize.h:490
@ NONNEGATIVE_SIGNED
#define READWRITE(...)
Definition: serialize.h:145
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
#define LOCK(cs)
Definition: sync.h:259
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:51
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
Definition: time.h:25
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())