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-present 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
42enum BlockStatus : uint32_t {
45
48
52
62
66
70
74
78
82
84
87};
88
95{
96public:
98 const uint256* phashBlock{nullptr};
99
102
105
107 int nHeight{0};
108
110 int nFile GUARDED_BY(::cs_main){0};
111
113 unsigned int nDataPos GUARDED_BY(::cs_main){0};
114
116 unsigned int nUndoPos GUARDED_BY(::cs_main){0};
117
120
124 unsigned int nTx{0};
125
130 uint64_t m_chain_tx_count{0};
131
138 uint32_t nStatus GUARDED_BY(::cs_main){0};
139
141 int32_t nVersion{0};
143 uint32_t nTime{0};
144 uint32_t nBits{0};
145 uint32_t nNonce{0};
146
151
153 unsigned int nTimeMax{0};
154
155 explicit CBlockIndex(const CBlockHeader& block)
156 : nVersion{block.nVersion},
158 nTime{block.nTime},
159 nBits{block.nBits},
160 nNonce{block.nNonce}
161 {
162 }
163
165 {
168 if (nStatus & BLOCK_HAVE_DATA) {
169 ret.nFile = nFile;
170 ret.nPos = nDataPos;
171 }
172 return ret;
173 }
174
176 {
179 if (nStatus & BLOCK_HAVE_UNDO) {
180 ret.nFile = nFile;
181 ret.nPos = nUndoPos;
182 }
183 return ret;
184 }
185
187 {
188 CBlockHeader block;
189 block.nVersion = nVersion;
190 if (pprev)
193 block.nTime = nTime;
194 block.nBits = nBits;
195 block.nNonce = nNonce;
196 return block;
197 }
198
200 {
201 assert(phashBlock != nullptr);
202 return *phashBlock;
203 }
204
215 bool HaveNumChainTxs() const { return m_chain_tx_count != 0; }
216
218 {
219 return NodeSeconds{std::chrono::seconds{nTime}};
220 }
221
222 int64_t GetBlockTime() const
223 {
224 return (int64_t)nTime;
225 }
226
227 int64_t GetBlockTimeMax() const
228 {
229 return (int64_t)nTimeMax;
230 }
231
232 static constexpr int nMedianTimeSpan = 11;
233
234 int64_t GetMedianTimePast() const
235 {
236 int64_t pmedian[nMedianTimeSpan];
237 int64_t* pbegin = &pmedian[nMedianTimeSpan];
238 int64_t* pend = &pmedian[nMedianTimeSpan];
239
240 const CBlockIndex* pindex = this;
241 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
242 *(--pbegin) = pindex->GetBlockTime();
243
244 std::sort(pbegin, pend);
245 return pbegin[(pend - pbegin) / 2];
246 }
247
248 std::string ToString() const;
249
251 bool IsValid(enum BlockStatus nUpTo) const
253 {
255 assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
256 if (nStatus & BLOCK_FAILED_MASK)
257 return false;
258 return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
259 }
260
264 {
266 assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
267 if (nStatus & BLOCK_FAILED_MASK) return false;
268
269 if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
270 nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
271 return true;
272 }
273 return false;
274 }
275
277 void BuildSkip();
278
280 CBlockIndex* GetAncestor(int height);
281 const CBlockIndex* GetAncestor(int height) const;
282
283 CBlockIndex() = default;
284 ~CBlockIndex() = default;
285
286protected:
296 CBlockIndex(const CBlockIndex&) = default;
300};
301
304int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params&);
306const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb);
307
308
311{
318 static constexpr int DUMMY_VERSION = 259900;
319
320public:
322
324 {
325 hashPrev = uint256();
326 }
327
328 explicit CDiskBlockIndex(const CBlockIndex* pindex) : CBlockIndex(*pindex)
329 {
331 }
332
334 {
336 int _nVersion = DUMMY_VERSION;
338
340 READWRITE(VARINT(obj.nStatus));
341 READWRITE(VARINT(obj.nTx));
343 if (obj.nStatus & BLOCK_HAVE_DATA) READWRITE(VARINT(obj.nDataPos));
344 if (obj.nStatus & BLOCK_HAVE_UNDO) READWRITE(VARINT(obj.nUndoPos));
345
346 // block header
347 READWRITE(obj.nVersion);
348 READWRITE(obj.hashPrev);
349 READWRITE(obj.hashMerkleRoot);
350 READWRITE(obj.nTime);
351 READWRITE(obj.nBits);
352 READWRITE(obj.nNonce);
353 }
354
356 {
357 CBlockHeader block;
358 block.nVersion = nVersion;
359 block.hashPrevBlock = hashPrev;
361 block.nTime = nTime;
362 block.nBits = nBits;
363 block.nNonce = nNonce;
364 return block.GetHash();
365 }
366
368 std::string ToString() = delete;
369};
370
373{
374private:
375 std::vector<CBlockIndex*> vChain;
376
377public:
378 CChain() = default;
379 CChain(const CChain&) = delete;
380 CChain& operator=(const CChain&) = delete;
381
384 {
385 return vChain.size() > 0 ? vChain[0] : nullptr;
386 }
387
390 {
391 return vChain.size() > 0 ? vChain[vChain.size() - 1] : nullptr;
392 }
393
396 {
397 if (nHeight < 0 || nHeight >= (int)vChain.size())
398 return nullptr;
399 return vChain[nHeight];
400 }
401
403 bool Contains(const CBlockIndex* pindex) const
404 {
405 return (*this)[pindex->nHeight] == pindex;
406 }
407
409 CBlockIndex* Next(const CBlockIndex* pindex) const
410 {
411 if (Contains(pindex))
412 return (*this)[pindex->nHeight + 1];
413 else
414 return nullptr;
415 }
416
418 int Height() const
419 {
420 return int(vChain.size()) - 1;
421 }
422
424 void SetTip(CBlockIndex& block);
425
427 const CBlockIndex* FindFork(const CBlockIndex* pindex) const;
428
430 CBlockIndex* FindEarliestAtLeast(int64_t nTime, int height) const;
431};
432
435
437std::vector<uint256> LocatorEntries(const CBlockIndex* index);
438
439#endif // BITCOIN_CHAIN_H
int ret
BlockStatus
Definition: chain.h:42
@ BLOCK_VALID_CHAIN
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends,...
Definition: chain.h:65
@ BLOCK_VALID_MASK
All validity bits.
Definition: chain.h:72
@ BLOCK_VALID_TRANSACTIONS
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid,...
Definition: chain.h:61
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok.
Definition: chain.h:69
@ BLOCK_VALID_RESERVED
Reserved (was BLOCK_VALID_HEADER).
Definition: chain.h:47
@ BLOCK_STATUS_RESERVED
Unused flag that was previously set on assumeutxo snapshot blocks and their ancestors before they wer...
Definition: chain.h:85
@ BLOCK_VALID_TREE
All parent headers found, difficulty matches, timestamp >= median previous.
Definition: chain.h:51
@ BLOCK_HAVE_UNDO
undo data available in rev*.dat
Definition: chain.h:76
@ BLOCK_HAVE_DATA
full block available in blk*.dat
Definition: chain.h:75
@ BLOCK_FAILED_CHILD
descends from failed block
Definition: chain.h:80
@ BLOCK_FAILED_MASK
Definition: chain.h:81
@ BLOCK_FAILED_VALID
stage after last reached validness failed
Definition: chain.h:79
@ BLOCK_OPT_WITNESS
block data in blk*.dat was received with a witness-enforcing client
Definition: chain.h:83
@ BLOCK_HAVE_MASK
Definition: chain.h:77
@ BLOCK_VALID_UNKNOWN
Unused.
Definition: chain.h:44
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_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:95
uint256 hashMerkleRoot
Definition: chain.h:142
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:251
uint32_t nStatus GUARDED_BY(::cs_main)
Verification status of this block.
Definition: chain.h:138
std::string ToString() const
Definition: chain.cpp:10
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:101
uint64_t m_chain_tx_count
(memory only) Number of transactions in the chain up to and including this block.
Definition: chain.h:130
void BuildSkip()
Build the skiplist pointer for this entry.
Definition: chain.cpp:115
CBlockHeader GetBlockHeader() const
Definition: chain.h:186
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:119
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:113
unsigned int nUndoPos GUARDED_BY(::cs_main)
Byte offset within rev?????.dat where this block's undo data is stored.
Definition: chain.h:116
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:215
uint32_t nTime
Definition: chain.h:143
unsigned int nTimeMax
(memory only) Maximum nTime in the chain up to and including this block.
Definition: chain.h:153
int32_t nSequenceId
(memory only) Sequential id assigned to distinguish order in which blocks are received.
Definition: chain.h:150
uint32_t nNonce
Definition: chain.h:145
uint256 GetBlockHash() const
Definition: chain.h:199
~CBlockIndex()=default
int64_t GetBlockTime() const
Definition: chain.h:222
int64_t GetMedianTimePast() const
Definition: chain.h:234
FlatFilePos GetUndoPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: chain.h:175
uint32_t nBits
Definition: chain.h:144
bool RaiseValidity(enum BlockStatus nUpTo) EXCLUSIVE_LOCKS_REQUIRED(
Raise the validity level of this block index entry.
Definition: chain.h:263
CBlockIndex * pskip
pointer to the index of some further predecessor of this block
Definition: chain.h:104
int64_t GetBlockTimeMax() const
Definition: chain.h:227
CBlockIndex(CBlockIndex &&)=delete
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:124
CBlockIndex(const CBlockHeader &block)
Definition: chain.h:155
NodeSeconds Time() const
Definition: chain.h:217
int32_t nVersion
block header
Definition: chain.h:141
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:107
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: chain.h:164
int nFile GUARDED_BY(::cs_main)
Which # file this block is stored in (blk?????.dat)
Definition: chain.h:110
static constexpr int nMedianTimeSpan
Definition: chain.h:232
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Definition: chain.h:98
An in-memory indexed chain of blocks.
Definition: chain.h:373
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:389
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:383
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:395
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:409
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:418
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:375
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:403
Used to marshal pointers into hashes for db storage.
Definition: chain.h:311
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:318
uint256 hashPrev
Definition: chain.h:321
uint256 GetBlockHash()=delete
uint256 ConstructBlockHash() const
Definition: chain.h:355
SERIALIZE_METHODS(CDiskBlockIndex, obj)
Definition: chain.h:333
CDiskBlockIndex()
Definition: chain.h:323
CDiskBlockIndex(const CBlockIndex *pindex)
Definition: chain.h:328
256-bit unsigned big integer.
256-bit opaque blob.
Definition: uint256.h:195
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())