Bitcoin Core 22.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-2020 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 <primitives/block.h>
13#include <tinyformat.h>
14#include <uint256.h>
15
16#include <vector>
17
22static constexpr int64_t MAX_FUTURE_BLOCK_TIME = 2 * 60 * 60;
23
30static constexpr int64_t TIMESTAMP_WINDOW = MAX_FUTURE_BLOCK_TIME;
31
38static constexpr int64_t MAX_BLOCK_TIME_GAP = 90 * 60;
39
41{
42public:
43 unsigned int nBlocks;
44 unsigned int nSize;
45 unsigned int nUndoSize;
46 unsigned int nHeightFirst;
47 unsigned int nHeightLast;
48 uint64_t nTimeFirst;
49 uint64_t nTimeLast;
50
52 {
53 READWRITE(VARINT(obj.nBlocks));
54 READWRITE(VARINT(obj.nSize));
55 READWRITE(VARINT(obj.nUndoSize));
56 READWRITE(VARINT(obj.nHeightFirst));
57 READWRITE(VARINT(obj.nHeightLast));
58 READWRITE(VARINT(obj.nTimeFirst));
59 READWRITE(VARINT(obj.nTimeLast));
60 }
61
62 void SetNull() {
63 nBlocks = 0;
64 nSize = 0;
65 nUndoSize = 0;
66 nHeightFirst = 0;
67 nHeightLast = 0;
68 nTimeFirst = 0;
69 nTimeLast = 0;
70 }
71
73 SetNull();
74 }
75
76 std::string ToString() const;
77
79 void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn) {
80 if (nBlocks==0 || nHeightFirst > nHeightIn)
81 nHeightFirst = nHeightIn;
82 if (nBlocks==0 || nTimeFirst > nTimeIn)
83 nTimeFirst = nTimeIn;
84 nBlocks++;
85 if (nHeightIn > nHeightLast)
86 nHeightLast = nHeightIn;
87 if (nTimeIn > nTimeLast)
88 nTimeLast = nTimeIn;
89 }
90};
91
92enum BlockStatus: uint32_t {
95
98
102
109
113
116
120
124
128
130
138};
139
146{
147public:
149 const uint256* phashBlock{nullptr};
150
153
156
158 int nHeight{0};
159
161 int nFile{0};
162
164 unsigned int nDataPos{0};
165
167 unsigned int nUndoPos{0};
168
171
177 unsigned int nTx{0};
178
187 unsigned int nChainTx{0};
188
195 uint32_t nStatus{0};
196
198 int32_t nVersion{0};
200 uint32_t nTime{0};
201 uint32_t nBits{0};
202 uint32_t nNonce{0};
203
205 int32_t nSequenceId{0};
206
208 unsigned int nTimeMax{0};
209
211 {
212 }
213
214 explicit CBlockIndex(const CBlockHeader& block)
215 : nVersion{block.nVersion},
217 nTime{block.nTime},
218 nBits{block.nBits},
219 nNonce{block.nNonce}
220 {
221 }
222
224 FlatFilePos ret;
225 if (nStatus & BLOCK_HAVE_DATA) {
226 ret.nFile = nFile;
227 ret.nPos = nDataPos;
228 }
229 return ret;
230 }
231
233 FlatFilePos ret;
234 if (nStatus & BLOCK_HAVE_UNDO) {
235 ret.nFile = nFile;
236 ret.nPos = nUndoPos;
237 }
238 return ret;
239 }
240
242 {
243 CBlockHeader block;
244 block.nVersion = nVersion;
245 if (pprev)
248 block.nTime = nTime;
249 block.nBits = nBits;
250 block.nNonce = nNonce;
251 return block;
252 }
253
255 {
256 return *phashBlock;
257 }
258
266 bool HaveTxsDownloaded() const { return nChainTx != 0; }
267
268 int64_t GetBlockTime() const
269 {
270 return (int64_t)nTime;
271 }
272
273 int64_t GetBlockTimeMax() const
274 {
275 return (int64_t)nTimeMax;
276 }
277
278 static constexpr int nMedianTimeSpan = 11;
279
280 int64_t GetMedianTimePast() const
281 {
282 int64_t pmedian[nMedianTimeSpan];
283 int64_t* pbegin = &pmedian[nMedianTimeSpan];
284 int64_t* pend = &pmedian[nMedianTimeSpan];
285
286 const CBlockIndex* pindex = this;
287 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
288 *(--pbegin) = pindex->GetBlockTime();
289
290 std::sort(pbegin, pend);
291 return pbegin[(pend - pbegin)/2];
292 }
293
294 std::string ToString() const
295 {
296 return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
297 pprev, nHeight,
300 }
301
304 {
305 assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
307 return false;
308 return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
309 }
310
313 bool IsAssumedValid() const { return nStatus & BLOCK_ASSUMED_VALID; }
314
317 bool RaiseValidity(enum BlockStatus nUpTo)
318 {
319 assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
320 if (nStatus & BLOCK_FAILED_MASK) return false;
321
322 if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
323 // If this block had been marked assumed-valid and we're raising
324 // its validity to a certain point, there is no longer an assumption.
326 nStatus &= ~BLOCK_ASSUMED_VALID;
327 }
328
329 nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
330 return true;
331 }
332 return false;
333 }
334
336 void BuildSkip();
337
339 CBlockIndex* GetAncestor(int height);
340 const CBlockIndex* GetAncestor(int height) const;
341};
342
345int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params&);
347const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb);
348
349
352{
353public:
355
357 hashPrev = uint256();
358 }
359
360 explicit CDiskBlockIndex(const CBlockIndex* pindex) : CBlockIndex(*pindex) {
362 }
363
365 {
366 int _nVersion = s.GetVersion();
367 if (!(s.GetType() & SER_GETHASH)) READWRITE(VARINT_MODE(_nVersion, VarIntMode::NONNEGATIVE_SIGNED));
368
370 READWRITE(VARINT(obj.nStatus));
371 READWRITE(VARINT(obj.nTx));
373 if (obj.nStatus & BLOCK_HAVE_DATA) READWRITE(VARINT(obj.nDataPos));
374 if (obj.nStatus & BLOCK_HAVE_UNDO) READWRITE(VARINT(obj.nUndoPos));
375
376 // block header
377 READWRITE(obj.nVersion);
378 READWRITE(obj.hashPrev);
379 READWRITE(obj.hashMerkleRoot);
380 READWRITE(obj.nTime);
381 READWRITE(obj.nBits);
382 READWRITE(obj.nNonce);
383 }
384
386 {
387 CBlockHeader block;
388 block.nVersion = nVersion;
389 block.hashPrevBlock = hashPrev;
391 block.nTime = nTime;
392 block.nBits = nBits;
393 block.nNonce = nNonce;
394 return block.GetHash();
395 }
396
397
398 std::string ToString() const
399 {
400 std::string str = "CDiskBlockIndex(";
401 str += CBlockIndex::ToString();
402 str += strprintf("\n hashBlock=%s, hashPrev=%s)",
405 return str;
406 }
407};
408
410class CChain {
411private:
412 std::vector<CBlockIndex*> vChain;
413
414public:
417 return vChain.size() > 0 ? vChain[0] : nullptr;
418 }
419
421 CBlockIndex *Tip() const {
422 return vChain.size() > 0 ? vChain[vChain.size() - 1] : nullptr;
423 }
424
427 if (nHeight < 0 || nHeight >= (int)vChain.size())
428 return nullptr;
429 return vChain[nHeight];
430 }
431
433 bool Contains(const CBlockIndex *pindex) const {
434 return (*this)[pindex->nHeight] == pindex;
435 }
436
438 CBlockIndex *Next(const CBlockIndex *pindex) const {
439 if (Contains(pindex))
440 return (*this)[pindex->nHeight + 1];
441 else
442 return nullptr;
443 }
444
446 int Height() const {
447 return vChain.size() - 1;
448 }
449
451 void SetTip(CBlockIndex *pindex);
452
454 CBlockLocator GetLocator(const CBlockIndex *pindex = nullptr) const;
455
457 const CBlockIndex *FindFork(const CBlockIndex *pindex) const;
458
460 CBlockIndex* FindEarliestAtLeast(int64_t nTime, int height) const;
461};
462
463#endif // BITCOIN_CHAIN_H
BlockStatus
Definition: chain.h:92
@ BLOCK_VALID_CHAIN
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends,...
Definition: chain.h:112
@ BLOCK_VALID_MASK
All validity bits.
Definition: chain.h:118
@ BLOCK_ASSUMED_VALID
If set, this indicates that the block index entry is assumed-valid.
Definition: chain.h:137
@ BLOCK_VALID_TRANSACTIONS
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid,...
Definition: chain.h:108
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
Definition: chain.h:115
@ BLOCK_VALID_RESERVED
Reserved (was BLOCK_VALID_HEADER).
Definition: chain.h:97
@ BLOCK_VALID_TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
Definition: chain.h:101
@ BLOCK_HAVE_UNDO
undo data available in rev*.dat
Definition: chain.h:122
@ BLOCK_HAVE_DATA
full block available in blk*.dat
Definition: chain.h:121
@ BLOCK_FAILED_CHILD
descends from failed block
Definition: chain.h:126
@ BLOCK_FAILED_MASK
Definition: chain.h:127
@ BLOCK_FAILED_VALID
stage after last reached validness failed
Definition: chain.h:125
@ BLOCK_OPT_WITNESS
block data in blk*.dat was received with a witness-enforcing client
Definition: chain.h:129
@ BLOCK_HAVE_MASK
Definition: chain.h:123
@ BLOCK_VALID_UNKNOWN
Unused.
Definition: chain.h:94
arith_uint256 GetBlockProof(const CBlockIndex &block)
Definition: chain.cpp:122
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:137
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:38
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:22
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:30
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the forking point between two chain tips.
Definition: chain.cpp:156
uint64_t nTimeFirst
earliest time of block in file
Definition: chain.h:48
uint64_t nTimeLast
latest time of block in file
Definition: chain.h:49
void SetNull()
Definition: chain.h:62
std::string ToString() const
CBlockFileInfo()
Definition: chain.h:72
void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn)
update statistics (does not update nSize)
Definition: chain.h:79
unsigned int nHeightFirst
lowest height of block in file
Definition: chain.h:46
unsigned int nHeightLast
highest height of block in file
Definition: chain.h:47
unsigned int nUndoSize
number of used bytes in the undo file
Definition: chain.h:45
unsigned int nBlocks
number of blocks stored in file
Definition: chain.h:43
SERIALIZE_METHODS(CBlockFileInfo, obj)
Definition: chain.h:51
unsigned int nSize
number of used bytes of block file
Definition: chain.h:44
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:21
uint32_t nNonce
Definition: block.h:29
uint32_t nBits
Definition: block.h:28
uint32_t nTime
Definition: block.h:27
int32_t nVersion
Definition: block.h:24
uint256 hashPrevBlock
Definition: block.h:25
uint256 hashMerkleRoot
Definition: block.h:26
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:146
uint256 hashMerkleRoot
Definition: chain.h:199
bool RaiseValidity(enum BlockStatus nUpTo)
Raise the validity level of this block index entry.
Definition: chain.h:317
CBlockIndex()
Definition: chain.h:210
std::string ToString() const
Definition: chain.h:294
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:152
void BuildSkip()
Build the skiplist pointer for this entry.
Definition: chain.cpp:116
CBlockHeader GetBlockHeader() const
Definition: chain.h:241
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:170
int nFile
Which # file this block is stored in (blk?????.dat)
Definition: chain.h:161
FlatFilePos GetBlockPos() const
Definition: chain.h:223
bool HaveTxsDownloaded() const
Check whether this block's and all previous blocks' transactions have been downloaded (and stored to ...
Definition: chain.h:266
uint32_t nTime
Definition: chain.h:200
unsigned int nTimeMax
(memory only) Maximum nTime in the chain up to and including this block.
Definition: chain.h:208
int32_t nSequenceId
(memory only) Sequential id assigned to distinguish order in which blocks are received.
Definition: chain.h:205
uint32_t nNonce
Definition: chain.h:202
unsigned int nUndoPos
Byte offset within rev?????.dat where this block's undo data is stored.
Definition: chain.h:167
uint256 GetBlockHash() const
Definition: chain.h:254
int64_t GetBlockTime() const
Definition: chain.h:268
int64_t GetMedianTimePast() const
Definition: chain.h:280
uint32_t nBits
Definition: chain.h:201
CBlockIndex * pskip
pointer to the index of some further predecessor of this block
Definition: chain.h:155
bool IsAssumedValid() const
Definition: chain.h:313
int64_t GetBlockTimeMax() const
Definition: chain.h:273
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:177
CBlockIndex(const CBlockHeader &block)
Definition: chain.h:214
FlatFilePos GetUndoPos() const
Definition: chain.h:232
bool IsValid(enum BlockStatus nUpTo=BLOCK_VALID_TRANSACTIONS) const
Check whether this block index entry is valid up to the passed validity level.
Definition: chain.h:303
int32_t nVersion
block header
Definition: chain.h:198
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: chain.cpp:111
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:158
uint32_t nStatus
Verification status of this block.
Definition: chain.h:195
unsigned int nDataPos
Byte offset within blk?????.dat where this block's data is stored.
Definition: chain.h:164
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block.
Definition: chain.h:187
static constexpr int nMedianTimeSpan
Definition: chain.h:278
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Definition: chain.h:149
An in-memory indexed chain of blocks.
Definition: chain.h:410
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:421
CBlockLocator GetLocator(const CBlockIndex *pindex=nullptr) const
Return a CBlockLocator that refers to a block in this chain (by default the tip).
Definition: chain.cpp:23
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
Definition: chain.h:416
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:426
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:438
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:62
int Height() const
Return the maximal height in the chain.
Definition: chain.h:446
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
Definition: chain.cpp:51
std::vector< CBlockIndex * > vChain
Definition: chain.h:412
void SetTip(CBlockIndex *pindex)
Set/initialize a chain with a given tip.
Definition: chain.cpp:11
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:433
Used to marshal pointers into hashes for db storage.
Definition: chain.h:352
std::string ToString() const
Definition: chain.h:398
uint256 hashPrev
Definition: chain.h:354
SERIALIZE_METHODS(CDiskBlockIndex, obj)
Definition: chain.h:364
CDiskBlockIndex()
Definition: chain.h:356
CDiskBlockIndex(const CBlockIndex *pindex)
Definition: chain.h:360
uint256 GetBlockHash() const
Definition: chain.h:385
256-bit unsigned big integer.
std::string ToString() const
Definition: uint256.cpp:64
256-bit opaque blob.
Definition: uint256.h:124
unsigned int nHeight
#define VARINT(obj)
Definition: serialize.h:443
#define VARINT_MODE(obj, mode)
Definition: serialize.h:442
@ SER_GETHASH
Definition: serialize.h:140
@ NONNEGATIVE_SIGNED
#define READWRITE(...)
Definition: serialize.h:147
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:115
Parameters that influence chain consensus.
Definition: params.h:70
int nFile
Definition: flatfile.h:16
unsigned int nPos
Definition: flatfile.h:17
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
assert(!tx.IsCoinBase())