Bitcoin Core  0.20.99
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 
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  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 
92 enum BlockStatus: uint32_t {
95 
98 
102 
109 
113 
116 
120 
124 
128 
130 };
131 
138 {
139 public:
141  const uint256* phashBlock{nullptr};
142 
144  CBlockIndex* pprev{nullptr};
145 
147  CBlockIndex* pskip{nullptr};
148 
150  int nHeight{0};
151 
153  int nFile{0};
154 
156  unsigned int nDataPos{0};
157 
159  unsigned int nUndoPos{0};
160 
162  arith_uint256 nChainWork{};
163 
166  unsigned int nTx{0};
167 
171  unsigned int nChainTx{0};
172 
174  uint32_t nStatus{0};
175 
177  int32_t nVersion{0};
178  uint256 hashMerkleRoot{};
179  uint32_t nTime{0};
180  uint32_t nBits{0};
181  uint32_t nNonce{0};
182 
184  int32_t nSequenceId{0};
185 
187  unsigned int nTimeMax{0};
188 
190  {
191  }
192 
193  explicit CBlockIndex(const CBlockHeader& block)
194  : nVersion{block.nVersion},
195  hashMerkleRoot{block.hashMerkleRoot},
196  nTime{block.nTime},
197  nBits{block.nBits},
198  nNonce{block.nNonce}
199  {
200  }
201 
203  FlatFilePos ret;
204  if (nStatus & BLOCK_HAVE_DATA) {
205  ret.nFile = nFile;
206  ret.nPos = nDataPos;
207  }
208  return ret;
209  }
210 
212  FlatFilePos ret;
213  if (nStatus & BLOCK_HAVE_UNDO) {
214  ret.nFile = nFile;
215  ret.nPos = nUndoPos;
216  }
217  return ret;
218  }
219 
221  {
222  CBlockHeader block;
223  block.nVersion = nVersion;
224  if (pprev)
225  block.hashPrevBlock = pprev->GetBlockHash();
226  block.hashMerkleRoot = hashMerkleRoot;
227  block.nTime = nTime;
228  block.nBits = nBits;
229  block.nNonce = nNonce;
230  return block;
231  }
232 
234  {
235  return *phashBlock;
236  }
237 
245  bool HaveTxsDownloaded() const { return nChainTx != 0; }
246 
247  int64_t GetBlockTime() const
248  {
249  return (int64_t)nTime;
250  }
251 
252  int64_t GetBlockTimeMax() const
253  {
254  return (int64_t)nTimeMax;
255  }
256 
257  static constexpr int nMedianTimeSpan = 11;
258 
259  int64_t GetMedianTimePast() const
260  {
261  int64_t pmedian[nMedianTimeSpan];
262  int64_t* pbegin = &pmedian[nMedianTimeSpan];
263  int64_t* pend = &pmedian[nMedianTimeSpan];
264 
265  const CBlockIndex* pindex = this;
266  for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
267  *(--pbegin) = pindex->GetBlockTime();
268 
269  std::sort(pbegin, pend);
270  return pbegin[(pend - pbegin)/2];
271  }
272 
273  std::string ToString() const
274  {
275  return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
276  pprev, nHeight,
277  hashMerkleRoot.ToString(),
278  GetBlockHash().ToString());
279  }
280 
283  {
284  assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
285  if (nStatus & BLOCK_FAILED_MASK)
286  return false;
287  return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
288  }
289 
292  bool RaiseValidity(enum BlockStatus nUpTo)
293  {
294  assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
295  if (nStatus & BLOCK_FAILED_MASK)
296  return false;
297  if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
298  nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
299  return true;
300  }
301  return false;
302  }
303 
305  void BuildSkip();
306 
308  CBlockIndex* GetAncestor(int height);
309  const CBlockIndex* GetAncestor(int height) const;
310 };
311 
314 int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params&);
316 const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb);
317 
318 
321 {
322 public:
324 
326  hashPrev = uint256();
327  }
328 
329  explicit CDiskBlockIndex(const CBlockIndex* pindex) : CBlockIndex(*pindex) {
330  hashPrev = (pprev ? pprev->GetBlockHash() : uint256());
331  }
332 
334  {
335  int _nVersion = s.GetVersion();
336  if (!(s.GetType() & SER_GETHASH)) READWRITE(VARINT_MODE(_nVersion, VarIntMode::NONNEGATIVE_SIGNED));
337 
339  READWRITE(VARINT(obj.nStatus));
340  READWRITE(VARINT(obj.nTx));
342  if (obj.nStatus & BLOCK_HAVE_DATA) READWRITE(VARINT(obj.nDataPos));
343  if (obj.nStatus & BLOCK_HAVE_UNDO) READWRITE(VARINT(obj.nUndoPos));
344 
345  // block header
346  READWRITE(obj.nVersion);
347  READWRITE(obj.hashPrev);
348  READWRITE(obj.hashMerkleRoot);
349  READWRITE(obj.nTime);
350  READWRITE(obj.nBits);
351  READWRITE(obj.nNonce);
352  }
353 
355  {
356  CBlockHeader block;
357  block.nVersion = nVersion;
358  block.hashPrevBlock = hashPrev;
359  block.hashMerkleRoot = hashMerkleRoot;
360  block.nTime = nTime;
361  block.nBits = nBits;
362  block.nNonce = nNonce;
363  return block.GetHash();
364  }
365 
366 
367  std::string ToString() const
368  {
369  std::string str = "CDiskBlockIndex(";
370  str += CBlockIndex::ToString();
371  str += strprintf("\n hashBlock=%s, hashPrev=%s)",
372  GetBlockHash().ToString(),
373  hashPrev.ToString());
374  return str;
375  }
376 };
377 
379 class CChain {
380 private:
381  std::vector<CBlockIndex*> vChain;
382 
383 public:
385  CBlockIndex *Genesis() const {
386  return vChain.size() > 0 ? vChain[0] : nullptr;
387  }
388 
390  CBlockIndex *Tip() const {
391  return vChain.size() > 0 ? vChain[vChain.size() - 1] : nullptr;
392  }
393 
396  if (nHeight < 0 || nHeight >= (int)vChain.size())
397  return nullptr;
398  return vChain[nHeight];
399  }
400 
402  bool Contains(const CBlockIndex *pindex) const {
403  return (*this)[pindex->nHeight] == pindex;
404  }
405 
407  CBlockIndex *Next(const CBlockIndex *pindex) const {
408  if (Contains(pindex))
409  return (*this)[pindex->nHeight + 1];
410  else
411  return nullptr;
412  }
413 
415  int Height() const {
416  return vChain.size() - 1;
417  }
418 
420  void SetTip(CBlockIndex *pindex);
421 
423  CBlockLocator GetLocator(const CBlockIndex *pindex = nullptr) const;
424 
426  const CBlockIndex *FindFork(const CBlockIndex *pindex) const;
427 
429  CBlockIndex* FindEarliestAtLeast(int64_t nTime, int height) const;
430 };
431 
432 #endif // BITCOIN_CHAIN_H
uint32_t nNonce
Definition: block.h:29
#define VARINT(obj)
Definition: serialize.h:479
std::string ToString() const
Definition: chain.h:273
std::vector< CBlockIndex * > vChain
Definition: chain.h:381
int64_t GetBlockTime() const
Definition: chain.h:247
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:114
descends from failed block
Definition: chain.h:126
Reserved (was BLOCK_VALID_HEADER).
Definition: chain.h:97
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:144
void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn)
update statistics (does not update nSize)
Definition: chain.h:79
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the forking point between two chain tips.
Definition: chain.cpp:156
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
An in-memory indexed chain of blocks.
Definition: chain.h:379
CBlockIndex()
Definition: chain.h:189
unsigned int nHeight
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
Definition: chain.h:101
CBlockHeader GetBlockHeader() const
Definition: chain.h:220
int Height() const
Return the maximal height in the chain.
Definition: chain.h:415
stage after last reached validness failed
Definition: chain.h:125
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid...
Definition: chain.h:108
unsigned int nSize
number of used bytes of block file
Definition: chain.h:44
FlatFilePos GetBlockPos() const
Definition: chain.h:202
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
Definition: chain.h:385
undo data available in rev*.dat
Definition: chain.h:122
int nFile
Definition: flatfile.h:16
Unused.
Definition: chain.h:94
SERIALIZE_METHODS(CDiskBlockIndex, obj)
Definition: chain.h:333
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
unsigned int nHeightLast
highest height of block in file
Definition: chain.h:47
uint32_t nTime
Definition: block.h:27
unsigned int nUndoSize
number of used bytes in the undo file
Definition: chain.h:45
uint256 GetBlockHash() const
Definition: chain.h:233
void SetNull()
Definition: chain.h:62
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:282
#define VARINT_MODE(obj, mode)
Definition: serialize.h:478
arith_uint256 GetBlockProof(const CBlockIndex &block)
Definition: chain.cpp:122
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends...
Definition: chain.h:112
uint64_t nTimeFirst
earliest time of block in file
Definition: chain.h:48
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
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
Definition: chain.h:115
uint256 hashMerkleRoot
Definition: block.h:26
CBlockFileInfo()
Definition: chain.h:72
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:402
CBlockIndex(const CBlockHeader &block)
Definition: chain.h:193
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:407
uint256 hashPrevBlock
Definition: block.h:25
int64_t GetBlockTimeMax() const
Definition: chain.h:252
CDiskBlockIndex()
Definition: chain.h:325
unsigned int nHeightFirst
lowest height of block in file
Definition: chain.h:46
Used to marshal pointers into hashes for db storage.
Definition: chain.h:320
std::string ToString() const
Definition: uint256.cpp:64
Parameters that influence chain consensus.
Definition: params.h:46
256-bit unsigned big integer.
int64_t GetMedianTimePast() const
Definition: chain.h:259
block data in blk*.data was received with a witness-enforcing client
Definition: chain.h:129
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
uint256 GetHash() const
Definition: block.cpp:11
256-bit opaque blob.
Definition: uint256.h:124
uint256 hashPrev
Definition: chain.h:323
CDiskBlockIndex(const CBlockIndex *pindex)
Definition: chain.h:329
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:137
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:390
unsigned int nBlocks
number of blocks stored in file
Definition: chain.h:43
std::string ToString() const
Definition: chain.h:367
bool RaiseValidity(enum BlockStatus nUpTo)
Raise the validity level of this block index entry.
Definition: chain.h:292
FlatFilePos GetUndoPos() const
Definition: chain.h:211
BlockStatus
Definition: chain.h:92
All validity bits.
Definition: chain.h:118
uint64_t nTimeLast
latest time of block in file
Definition: chain.h:49
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
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:150
full block available in blk*.dat
Definition: chain.h:121
uint256 GetBlockHash() const
Definition: chain.h:354
SERIALIZE_METHODS(CBlockFileInfo, obj)
Definition: chain.h:51
#define READWRITE(...)
Definition: serialize.h:175
std::string ToString() const
unsigned int nPos
Definition: flatfile.h:17
int32_t nVersion
Definition: block.h:24
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
bool HaveTxsDownloaded() const
Check whether this block&#39;s and all previous blocks&#39; transactions have been downloaded (and stored to ...
Definition: chain.h:245
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:20
uint32_t nBits
Definition: block.h:28