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