Bitcoin Core  27.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 
29 static constexpr int64_t MAX_FUTURE_BLOCK_TIME = 2 * 60 * 60;
30 
37 static constexpr int64_t TIMESTAMP_WINDOW = MAX_FUTURE_BLOCK_TIME;
38 
45 static constexpr int64_t MAX_BLOCK_TIME_GAP = 90 * 60;
46 
48 {
49 public:
50  unsigned int nBlocks{};
51  unsigned int nSize{};
52  unsigned int nUndoSize{};
53  unsigned int nHeightFirst{};
54  unsigned int nHeightLast{};
55  uint64_t nTimeFirst{};
56  uint64_t nTimeLast{};
57 
59  {
60  READWRITE(VARINT(obj.nBlocks));
61  READWRITE(VARINT(obj.nSize));
62  READWRITE(VARINT(obj.nUndoSize));
63  READWRITE(VARINT(obj.nHeightFirst));
64  READWRITE(VARINT(obj.nHeightLast));
65  READWRITE(VARINT(obj.nTimeFirst));
66  READWRITE(VARINT(obj.nTimeLast));
67  }
68 
70 
71  std::string ToString() const;
72 
74  void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn)
75  {
76  if (nBlocks == 0 || nHeightFirst > nHeightIn)
77  nHeightFirst = nHeightIn;
78  if (nBlocks == 0 || nTimeFirst > nTimeIn)
79  nTimeFirst = nTimeIn;
80  nBlocks++;
81  if (nHeightIn > nHeightLast)
82  nHeightLast = nHeightIn;
83  if (nTimeIn > nTimeLast)
84  nTimeLast = nTimeIn;
85  }
86 };
87 
88 enum BlockStatus : uint32_t {
91 
94 
98 
108 
112 
116 
120 
124 
128 
130 
131  BLOCK_STATUS_RESERVED = 256,
133 };
134 
141 {
142 public:
144  const uint256* phashBlock{nullptr};
145 
147  CBlockIndex* pprev{nullptr};
148 
150  CBlockIndex* pskip{nullptr};
151 
153  int nHeight{0};
154 
156  int nFile GUARDED_BY(::cs_main){0};
157 
159  unsigned int nDataPos GUARDED_BY(::cs_main){0};
160 
162  unsigned int nUndoPos GUARDED_BY(::cs_main){0};
163 
166 
170  unsigned int nTx{0};
171 
177  unsigned int nChainTx{0};
178 
185  uint32_t nStatus GUARDED_BY(::cs_main){0};
186 
188  int32_t nVersion{0};
190  uint32_t nTime{0};
191  uint32_t nBits{0};
192  uint32_t nNonce{0};
193 
195  int32_t nSequenceId{0};
196 
198  unsigned int nTimeMax{0};
199 
200  explicit CBlockIndex(const CBlockHeader& block)
201  : nVersion{block.nVersion},
203  nTime{block.nTime},
204  nBits{block.nBits},
205  nNonce{block.nNonce}
206  {
207  }
208 
210  {
213  if (nStatus & BLOCK_HAVE_DATA) {
214  ret.nFile = nFile;
215  ret.nPos = nDataPos;
216  }
217  return ret;
218  }
219 
221  {
224  if (nStatus & BLOCK_HAVE_UNDO) {
225  ret.nFile = nFile;
226  ret.nPos = nUndoPos;
227  }
228  return ret;
229  }
230 
232  {
233  CBlockHeader block;
234  block.nVersion = nVersion;
235  if (pprev)
236  block.hashPrevBlock = pprev->GetBlockHash();
238  block.nTime = nTime;
239  block.nBits = nBits;
240  block.nNonce = nNonce;
241  return block;
242  }
243 
245  {
246  assert(phashBlock != nullptr);
247  return *phashBlock;
248  }
249 
260  bool HaveNumChainTxs() const { return nChainTx != 0; }
261 
263  {
264  return NodeSeconds{std::chrono::seconds{nTime}};
265  }
266 
267  int64_t GetBlockTime() const
268  {
269  return (int64_t)nTime;
270  }
271 
272  int64_t GetBlockTimeMax() const
273  {
274  return (int64_t)nTimeMax;
275  }
276 
277  static constexpr int nMedianTimeSpan = 11;
278 
279  int64_t GetMedianTimePast() const
280  {
281  int64_t pmedian[nMedianTimeSpan];
282  int64_t* pbegin = &pmedian[nMedianTimeSpan];
283  int64_t* pend = &pmedian[nMedianTimeSpan];
284 
285  const CBlockIndex* pindex = this;
286  for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
287  *(--pbegin) = pindex->GetBlockTime();
288 
289  std::sort(pbegin, pend);
290  return pbegin[(pend - pbegin) / 2];
291  }
292 
293  std::string ToString() const;
294 
298  {
300  assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
301  if (nStatus & BLOCK_FAILED_MASK)
302  return false;
303  return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
304  }
305 
309  {
311  assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
312  if (nStatus & BLOCK_FAILED_MASK) return false;
313 
314  if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
315  nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
316  return true;
317  }
318  return false;
319  }
320 
322  void BuildSkip();
323 
325  CBlockIndex* GetAncestor(int height);
326  const CBlockIndex* GetAncestor(int height) const;
327 
328  CBlockIndex() = default;
329  ~CBlockIndex() = default;
330 
331 protected:
341  CBlockIndex(const CBlockIndex&) = default;
342  CBlockIndex& operator=(const CBlockIndex&) = delete;
345 };
346 
349 int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params&);
351 const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb);
352 
353 
356 {
363  static constexpr int DUMMY_VERSION = 259900;
364 
365 public:
367 
369  {
370  hashPrev = uint256();
371  }
372 
373  explicit CDiskBlockIndex(const CBlockIndex* pindex) : CBlockIndex(*pindex)
374  {
375  hashPrev = (pprev ? pprev->GetBlockHash() : uint256());
376  }
377 
379  {
380  LOCK(::cs_main);
381  int _nVersion = DUMMY_VERSION;
383 
385  READWRITE(VARINT(obj.nStatus));
386  READWRITE(VARINT(obj.nTx));
388  if (obj.nStatus & BLOCK_HAVE_DATA) READWRITE(VARINT(obj.nDataPos));
389  if (obj.nStatus & BLOCK_HAVE_UNDO) READWRITE(VARINT(obj.nUndoPos));
390 
391  // block header
392  READWRITE(obj.nVersion);
393  READWRITE(obj.hashPrev);
394  READWRITE(obj.hashMerkleRoot);
395  READWRITE(obj.nTime);
396  READWRITE(obj.nBits);
397  READWRITE(obj.nNonce);
398  }
399 
401  {
402  CBlockHeader block;
403  block.nVersion = nVersion;
404  block.hashPrevBlock = hashPrev;
406  block.nTime = nTime;
407  block.nBits = nBits;
408  block.nNonce = nNonce;
409  return block.GetHash();
410  }
411 
412  uint256 GetBlockHash() = delete;
413  std::string ToString() = delete;
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 int(vChain.size()) - 1;
466  }
467 
469  void SetTip(CBlockIndex& block);
470 
472  CBlockLocator GetLocator() const;
473 
475  const CBlockIndex* FindFork(const CBlockIndex* pindex) const;
476 
478  CBlockIndex* FindEarliestAtLeast(int64_t nTime, int height) const;
479 };
480 
482 CBlockLocator GetLocator(const CBlockIndex* index);
483 
485 std::vector<uint256> LocatorEntries(const CBlockIndex* index);
486 
487 #endif // BITCOIN_CHAIN_H
int ret
BlockStatus
Definition: chain.h:88
@ BLOCK_VALID_CHAIN
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends,...
Definition: chain.h:111
@ BLOCK_VALID_MASK
All validity bits.
Definition: chain.h:118
@ BLOCK_VALID_TRANSACTIONS
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid,...
Definition: chain.h:107
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok.
Definition: chain.h:115
@ BLOCK_VALID_RESERVED
Reserved (was BLOCK_VALID_HEADER).
Definition: chain.h:93
@ BLOCK_STATUS_RESERVED
Unused flag that was previously set on assumeutxo snapshot blocks and their ancestors before they wer...
Definition: chain.h:131
@ BLOCK_VALID_TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
Definition: chain.h:97
@ 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:90
arith_uint256 GetBlockProof(const CBlockIndex &block)
Definition: chain.cpp:131
CBlockLocator GetLocator(const CBlockIndex *index)
Get a locator for a block index entry.
Definition: chain.cpp:50
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
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:45
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
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the forking point between two chain tips.
Definition: chain.cpp:165
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
std::vector< uint256 > LocatorEntries(const CBlockIndex *index)
Construct a list of hash entries to put in a locator.
Definition: chain.cpp:31
uint64_t nTimeFirst
earliest time of block in file
Definition: chain.h:55
uint64_t nTimeLast
latest time of block in file
Definition: chain.h:56
std::string ToString() const
Definition: chain.cpp:10
CBlockFileInfo()
Definition: chain.h:69
void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn)
update statistics (does not update nSize)
Definition: chain.h:74
unsigned int nHeightFirst
lowest height of block in file
Definition: chain.h:53
unsigned int nHeightLast
highest height of block in file
Definition: chain.h:54
unsigned int nUndoSize
number of used bytes in the undo file
Definition: chain.h:52
unsigned int nBlocks
number of blocks stored in file
Definition: chain.h:50
SERIALIZE_METHODS(CBlockFileInfo, obj)
Definition: chain.h:58
unsigned int nSize
number of used bytes of block file
Definition: chain.h:51
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:141
uint256 hashMerkleRoot
Definition: chain.h:189
uint32_t nStatus GUARDED_BY(::cs_main)
Verification status of this block.
Definition: chain.h:185
std::string ToString() const
Definition: chain.cpp:15
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:147
void BuildSkip()
Build the skiplist pointer for this entry.
Definition: chain.cpp:125
CBlockHeader GetBlockHeader() const
Definition: chain.h:231
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:165
CBlockIndex()=default
unsigned int nDataPos GUARDED_BY(::cs_main)
Byte offset within blk?????.dat where this block's data is stored.
Definition: chain.h:159
unsigned int nUndoPos GUARDED_BY(::cs_main)
Byte offset within rev?????.dat where this block's undo data is stored.
Definition: chain.h:162
bool HaveNumChainTxs() const
Check whether this block and all previous blocks back to the genesis block or an assumeutxo snapshot ...
Definition: chain.h:260
uint32_t nTime
Definition: chain.h:190
unsigned int nTimeMax
(memory only) Maximum nTime in the chain up to and including this block.
Definition: chain.h:198
int32_t nSequenceId
(memory only) Sequential id assigned to distinguish order in which blocks are received.
Definition: chain.h:195
CBlockIndex & operator=(const CBlockIndex &)=delete
uint32_t nNonce
Definition: chain.h:192
uint256 GetBlockHash() const
Definition: chain.h:244
~CBlockIndex()=default
int64_t GetBlockTime() const
Definition: chain.h:267
int64_t GetMedianTimePast() const
Definition: chain.h:279
FlatFilePos GetUndoPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: chain.h:220
uint32_t nBits
Definition: chain.h:191
bool RaiseValidity(enum BlockStatus nUpTo) EXCLUSIVE_LOCKS_REQUIRED(
Raise the validity level of this block index entry.
Definition: chain.h:308
CBlockIndex * pskip
pointer to the index of some further predecessor of this block
Definition: chain.h:150
int64_t GetBlockTimeMax() const
Definition: chain.h:272
CBlockIndex(CBlockIndex &&)=delete
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:170
CBlockIndex(const CBlockHeader &block)
Definition: chain.h:200
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:296
CBlockIndex & operator=(CBlockIndex &&)=delete
NodeSeconds Time() const
Definition: chain.h:262
int32_t nVersion
block header
Definition: chain.h:188
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:120
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:153
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: chain.h:209
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block.
Definition: chain.h:177
int nFile GUARDED_BY(::cs_main)
Which # file this block is stored in (blk?????.dat)
Definition: chain.h:156
static constexpr int nMedianTimeSpan
Definition: chain.h:277
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Definition: chain.h:144
An in-memory indexed chain of blocks.
Definition: chain.h:418
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
Definition: chain.h:428
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
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(const CChain &)=delete
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:434
void SetTip(CBlockIndex &block)
Set/initialize a chain with a given tip.
Definition: chain.cpp:21
CChain()=default
CChain & operator=(const CChain &)=delete
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
int Height() const
Return the maximal height in the chain.
Definition: chain.h:463
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
Definition: chain.cpp:60
std::vector< CBlockIndex * > vChain
Definition: chain.h:420
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:448
CBlockLocator GetLocator() const
Return a CBlockLocator that refers to the tip in of this chain.
Definition: chain.cpp:55
Used to marshal pointers into hashes for db storage.
Definition: chain.h:356
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:363
uint256 hashPrev
Definition: chain.h:366
uint256 GetBlockHash()=delete
uint256 ConstructBlockHash() const
Definition: chain.h:400
SERIALIZE_METHODS(CDiskBlockIndex, obj)
Definition: chain.h:378
CDiskBlockIndex()
Definition: chain.h:368
CDiskBlockIndex(const CBlockIndex *pindex)
Definition: chain.h:373
256-bit unsigned big integer.
256-bit opaque blob.
Definition: uint256.h:106
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:513
#define VARINT_MODE(obj, mode)
Definition: serialize.h:512
@ NONNEGATIVE_SIGNED
#define READWRITE(...)
Definition: serialize.h:156
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:74
#define LOCK(cs)
Definition: sync.h:257
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
Definition: time.h:23
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())