Bitcoin Core  26.1.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 <sync.h>
15 #include <uint256.h>
16 #include <util/time.h>
17 
18 #include <vector>
19 
24 static constexpr int64_t MAX_FUTURE_BLOCK_TIME = 2 * 60 * 60;
25 
32 static constexpr int64_t TIMESTAMP_WINDOW = MAX_FUTURE_BLOCK_TIME;
33 
40 static constexpr int64_t MAX_BLOCK_TIME_GAP = 90 * 60;
41 
43 {
44 public:
45  unsigned int nBlocks{};
46  unsigned int nSize{};
47  unsigned int nUndoSize{};
48  unsigned int nHeightFirst{};
49  unsigned int nHeightLast{};
50  uint64_t nTimeFirst{};
51  uint64_t nTimeLast{};
52 
54  {
55  READWRITE(VARINT(obj.nBlocks));
56  READWRITE(VARINT(obj.nSize));
57  READWRITE(VARINT(obj.nUndoSize));
58  READWRITE(VARINT(obj.nHeightFirst));
59  READWRITE(VARINT(obj.nHeightLast));
60  READWRITE(VARINT(obj.nTimeFirst));
61  READWRITE(VARINT(obj.nTimeLast));
62  }
63 
65 
66  std::string ToString() const;
67 
69  void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn)
70  {
71  if (nBlocks == 0 || nHeightFirst > nHeightIn)
72  nHeightFirst = nHeightIn;
73  if (nBlocks == 0 || nTimeFirst > nTimeIn)
74  nTimeFirst = nTimeIn;
75  nBlocks++;
76  if (nHeightIn > nHeightLast)
77  nHeightLast = nHeightIn;
78  if (nTimeIn > nTimeLast)
79  nTimeLast = nTimeIn;
80  }
81 };
82 
83 enum BlockStatus : uint32_t {
86 
89 
93 
100 
104 
107 
111 
115 
119 
121 
137 };
138 
145 {
146 public:
148  const uint256* phashBlock{nullptr};
149 
151  CBlockIndex* pprev{nullptr};
152 
154  CBlockIndex* pskip{nullptr};
155 
157  int nHeight{0};
158 
160  int nFile GUARDED_BY(::cs_main){0};
161 
163  unsigned int nDataPos GUARDED_BY(::cs_main){0};
164 
166  unsigned int nUndoPos GUARDED_BY(::cs_main){0};
167 
170 
176  unsigned int nTx{0};
177 
186  unsigned int nChainTx{0};
187 
194  uint32_t nStatus GUARDED_BY(::cs_main){0};
195 
197  int32_t nVersion{0};
199  uint32_t nTime{0};
200  uint32_t nBits{0};
201  uint32_t nNonce{0};
202 
204  int32_t nSequenceId{0};
205 
207  unsigned int nTimeMax{0};
208 
209  explicit CBlockIndex(const CBlockHeader& block)
210  : nVersion{block.nVersion},
211  hashMerkleRoot{block.hashMerkleRoot},
212  nTime{block.nTime},
213  nBits{block.nBits},
214  nNonce{block.nNonce}
215  {
216  }
217 
219  {
222  if (nStatus & BLOCK_HAVE_DATA) {
223  ret.nFile = nFile;
224  ret.nPos = nDataPos;
225  }
226  return ret;
227  }
228 
230  {
233  if (nStatus & BLOCK_HAVE_UNDO) {
234  ret.nFile = nFile;
235  ret.nPos = nUndoPos;
236  }
237  return ret;
238  }
239 
241  {
242  CBlockHeader block;
243  block.nVersion = nVersion;
244  if (pprev)
245  block.hashPrevBlock = pprev->GetBlockHash();
247  block.nTime = nTime;
248  block.nBits = nBits;
249  block.nNonce = nNonce;
250  return block;
251  }
252 
254  {
255  assert(phashBlock != nullptr);
256  return *phashBlock;
257  }
258 
270  bool HaveNumChainTxs() const { return nChainTx != 0; }
271 
273  {
274  return NodeSeconds{std::chrono::seconds{nTime}};
275  }
276 
277  int64_t GetBlockTime() const
278  {
279  return (int64_t)nTime;
280  }
281 
282  int64_t GetBlockTimeMax() const
283  {
284  return (int64_t)nTimeMax;
285  }
286 
287  static constexpr int nMedianTimeSpan = 11;
288 
289  int64_t GetMedianTimePast() const
290  {
291  int64_t pmedian[nMedianTimeSpan];
292  int64_t* pbegin = &pmedian[nMedianTimeSpan];
293  int64_t* pend = &pmedian[nMedianTimeSpan];
294 
295  const CBlockIndex* pindex = this;
296  for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
297  *(--pbegin) = pindex->GetBlockTime();
298 
299  std::sort(pbegin, pend);
300  return pbegin[(pend - pbegin) / 2];
301  }
302 
303  std::string ToString() const;
304 
308  {
310  assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
311  if (nStatus & BLOCK_FAILED_MASK)
312  return false;
313  return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
314  }
315 
319  {
321  return nStatus & BLOCK_ASSUMED_VALID;
322  }
323 
327  {
329  assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
330  if (nStatus & BLOCK_FAILED_MASK) return false;
331 
332  if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
333  // If this block had been marked assumed-valid and we're raising
334  // its validity to a certain point, there is no longer an assumption.
335  if (nStatus & BLOCK_ASSUMED_VALID && nUpTo >= BLOCK_VALID_SCRIPTS) {
336  nStatus &= ~BLOCK_ASSUMED_VALID;
337  }
338 
339  nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
340  return true;
341  }
342  return false;
343  }
344 
346  void BuildSkip();
347 
349  CBlockIndex* GetAncestor(int height);
350  const CBlockIndex* GetAncestor(int height) const;
351 
352  CBlockIndex() = default;
353  ~CBlockIndex() = default;
354 
355 protected:
365  CBlockIndex(const CBlockIndex&) = default;
366  CBlockIndex& operator=(const CBlockIndex&) = delete;
367  CBlockIndex(CBlockIndex&&) = delete;
368  CBlockIndex& operator=(CBlockIndex&&) = delete;
369 };
370 
373 int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params&);
375 const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb);
376 
377 
380 {
387  static constexpr int DUMMY_VERSION = 259900;
388 
389 public:
391 
393  {
394  hashPrev = uint256();
395  }
396 
397  explicit CDiskBlockIndex(const CBlockIndex* pindex) : CBlockIndex(*pindex)
398  {
399  hashPrev = (pprev ? pprev->GetBlockHash() : uint256());
400  }
401 
403  {
404  LOCK(::cs_main);
405  int _nVersion = DUMMY_VERSION;
407 
409  READWRITE(VARINT(obj.nStatus));
410  READWRITE(VARINT(obj.nTx));
412  if (obj.nStatus & BLOCK_HAVE_DATA) READWRITE(VARINT(obj.nDataPos));
413  if (obj.nStatus & BLOCK_HAVE_UNDO) READWRITE(VARINT(obj.nUndoPos));
414 
415  // block header
416  READWRITE(obj.nVersion);
417  READWRITE(obj.hashPrev);
418  READWRITE(obj.hashMerkleRoot);
419  READWRITE(obj.nTime);
420  READWRITE(obj.nBits);
421  READWRITE(obj.nNonce);
422  }
423 
425  {
426  CBlockHeader block;
427  block.nVersion = nVersion;
428  block.hashPrevBlock = hashPrev;
430  block.nTime = nTime;
431  block.nBits = nBits;
432  block.nNonce = nNonce;
433  return block.GetHash();
434  }
435 
436  uint256 GetBlockHash() = delete;
437  std::string ToString() = delete;
438 };
439 
441 class CChain
442 {
443 private:
444  std::vector<CBlockIndex*> vChain;
445 
446 public:
447  CChain() = default;
448  CChain(const CChain&) = delete;
449  CChain& operator=(const CChain&) = delete;
450 
453  {
454  return vChain.size() > 0 ? vChain[0] : nullptr;
455  }
456 
458  CBlockIndex* Tip() const
459  {
460  return vChain.size() > 0 ? vChain[vChain.size() - 1] : nullptr;
461  }
462 
465  {
466  if (nHeight < 0 || nHeight >= (int)vChain.size())
467  return nullptr;
468  return vChain[nHeight];
469  }
470 
472  bool Contains(const CBlockIndex* pindex) const
473  {
474  return (*this)[pindex->nHeight] == pindex;
475  }
476 
478  CBlockIndex* Next(const CBlockIndex* pindex) const
479  {
480  if (Contains(pindex))
481  return (*this)[pindex->nHeight + 1];
482  else
483  return nullptr;
484  }
485 
487  int Height() const
488  {
489  return int(vChain.size()) - 1;
490  }
491 
493  void SetTip(CBlockIndex& block);
494 
496  CBlockLocator GetLocator() const;
497 
499  const CBlockIndex* FindFork(const CBlockIndex* pindex) const;
500 
502  CBlockIndex* FindEarliestAtLeast(int64_t nTime, int height) const;
503 };
504 
506 CBlockLocator GetLocator(const CBlockIndex* index);
507 
509 std::vector<uint256> LocatorEntries(const CBlockIndex* index);
510 
511 #endif // BITCOIN_CHAIN_H
uint32_t nNonce
Definition: block.h:30
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:169
#define VARINT(obj)
Definition: serialize.h:522
int ret
std::string ToString() const
Definition: chain.cpp:15
int32_t nSequenceId
(memory only) Sequential id assigned to distinguish order in which blocks are received.
Definition: chain.h:204
bool HaveNumChainTxs() const
Check whether this block&#39;s and all previous blocks&#39; transactions have been downloaded (and stored to ...
Definition: chain.h:270
CBlockIndex * pskip
pointer to the index of some further predecessor of this block
Definition: chain.h:154
std::vector< CBlockIndex * > vChain
Definition: chain.h:444
AssertLockHeld(pool.cs)
int64_t GetBlockTime() const
Definition: chain.h:277
assert(!tx.IsCoinBase())
NodeSeconds Time() const
Definition: chain.h:272
Describes a place in the block chain to another node such that if the other node doesn&#39;t have the sam...
Definition: block.h:123
descends from failed block
Definition: chain.h:117
Reserved (was BLOCK_VALID_HEADER).
Definition: chain.h:88
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:151
void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn)
update statistics (does not update nSize)
Definition: chain.h:69
CBlockLocator GetLocator(const CBlockIndex *index)
Get a locator for a block index entry.
Definition: chain.cpp:50
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the forking point between two chain tips.
Definition: chain.cpp:165
An in-memory indexed chain of blocks.
Definition: chain.h:441
int nFile GUARDED_BY(::cs_main)
Which # file this block is stored in (blk?????.dat)
Definition: chain.h:160
unsigned int nHeight
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
Definition: chain.h:92
CBlockHeader GetBlockHeader() const
Definition: chain.h:240
int Height() const
Return the maximal height in the chain.
Definition: chain.h:487
stage after last reached validness failed
Definition: chain.h:116
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid...
Definition: chain.h:99
unsigned int nSize
number of used bytes of block file
Definition: chain.h:46
~CBlockIndex()=default
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
Definition: chain.h:452
CChain()=default
uint32_t nTime
Definition: chain.h:199
undo data available in rev*.dat
Definition: chain.h:113
Unused.
Definition: chain.h:85
SERIALIZE_METHODS(CDiskBlockIndex, obj)
Definition: chain.h:402
void SetTip(CBlockIndex &block)
Set/initialize a chain with a given tip.
Definition: chain.cpp:21
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:32
unsigned int nHeightLast
highest height of block in file
Definition: chain.h:49
uint32_t nTime
Definition: block.h:28
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block. ...
Definition: chain.h:186
unsigned int nUndoSize
number of used bytes in the undo file
Definition: chain.h:47
CBlockIndex()=default
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
Definition: time.h:23
static constexpr int nMedianTimeSpan
Definition: chain.h:287
uint256 GetBlockHash() const
Definition: chain.h:253
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:71
CBlockLocator GetLocator() const
Return a CBlockLocator that refers to the tip in of this chain.
Definition: chain.cpp:55
#define VARINT_MODE(obj, mode)
Definition: serialize.h:521
arith_uint256 GetBlockProof(const CBlockIndex &block)
Definition: chain.cpp:131
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends...
Definition: chain.h:103
unsigned int nTimeMax
(memory only) Maximum nTime in the chain up to and including this block.
Definition: chain.h:207
uint64_t nTimeFirst
earliest time of block in file
Definition: chain.h:50
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:464
Scripts & signatures ok. Implies all parents are either at least VALID_SCRIPTS, or are ASSUMED_VALID...
Definition: chain.h:106
uint256 hashMerkleRoot
Definition: block.h:27
std::string ToString()=delete
uint32_t nNonce
Definition: chain.h:201
#define LOCK(cs)
Definition: sync.h:258
CBlockFileInfo()
Definition: chain.h:64
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:472
CBlockIndex(const CBlockHeader &block)
Definition: chain.h:209
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:478
uint256 hashPrevBlock
Definition: block.h:26
std::vector< uint256 > LocatorEntries(const CBlockIndex *index)
Construct a list of hash entries to put in a locator.
Definition: chain.cpp:31
int64_t GetBlockTimeMax() const
Definition: chain.h:282
static constexpr int DUMMY_VERSION
Historically CBlockLocator&#39;s version field has been written to disk streams as the client version...
Definition: chain.h:387
CDiskBlockIndex()
Definition: chain.h:392
uint256 hashMerkleRoot
Definition: chain.h:198
CChain & operator=(const CChain &)=delete
unsigned int nHeightFirst
lowest height of block in file
Definition: chain.h:48
void BuildSkip()
Build the skiplist pointer for this entry.
Definition: chain.cpp:125
Used to marshal pointers into hashes for db storage.
Definition: chain.h:379
Parameters that influence chain consensus.
Definition: params.h:74
256-bit unsigned big integer.
int64_t GetMedianTimePast() const
Definition: chain.h:289
block data in blk*.dat was received with a witness-enforcing client
Definition: chain.h:120
FlatFilePos GetUndoPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: chain.h:229
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:146
unsigned int nDataPos GUARDED_BY(::cs_main)
Byte offset within blk?????.dat where this block&#39;s data is stored.
Definition: chain.h:163
uint32_t nStatus GUARDED_BY(::cs_main)
Verification status of this block.
Definition: chain.h:194
bool IsValid(enum BlockStatus nUpTo=BLOCK_VALID_TRANSACTIONS) const EXCLUSIVE_LOCKS_REQUIRED(
Check whether this block index entry is valid up to the passed validity level.
Definition: chain.h:306
uint256 GetHash() const
Definition: block.cpp:11
int32_t nVersion
block header
Definition: chain.h:197
256-bit opaque blob.
Definition: uint256.h:106
uint256 ConstructBlockHash() const
Definition: chain.h:424
uint256 hashPrev
Definition: chain.h:390
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
unsigned int nUndoPos GUARDED_BY(::cs_main)
Byte offset within rev?????.dat where this block&#39;s undo data is stored.
Definition: chain.h:166
CDiskBlockIndex(const CBlockIndex *pindex)
Definition: chain.h:397
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:144
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:458
bool RaiseValidity(enum BlockStatus nUpTo) EXCLUSIVE_LOCKS_REQUIRED(
Raise the validity level of this block index entry.
Definition: chain.h:326
bool IsAssumedValid() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: chain.h:318
unsigned int nBlocks
number of blocks stored in file
Definition: chain.h:45
BlockStatus
Definition: chain.h:83
All validity bits.
Definition: chain.h:109
uint64_t nTimeLast
latest time of block in file
Definition: chain.h:51
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:24
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:157
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: chain.h:218
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: chain.cpp:120
full block available in blk*.dat
Definition: chain.h:112
SERIALIZE_METHODS(CBlockFileInfo, obj)
Definition: chain.h:53
#define READWRITE(...)
Definition: serialize.h:169
std::string ToString() const
Definition: chain.cpp:10
If ASSUMED_VALID is set, it means that this block has not been validated and has validity status less...
Definition: chain.h:136
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: cs_main.cpp:8
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
Definition: chain.cpp:60
int32_t nVersion
Definition: block.h:25
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:40
uint32_t nBits
Definition: chain.h:200
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:176
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:21
uint32_t nBits
Definition: block.h:29
uint256 GetBlockHash()=delete
CBlockIndex & operator=(const CBlockIndex &)=delete
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Definition: chain.h:148