Bitcoin Core  0.15.99
P2P Digital Currency
chain.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2018 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 <primitives/block.h>
12 #include <tinyformat.h>
13 #include <uint256.h>
14 
15 #include <vector>
16 
21 static constexpr int64_t MAX_FUTURE_BLOCK_TIME = 2 * 60 * 60;
22 
29 static constexpr int64_t TIMESTAMP_WINDOW = MAX_FUTURE_BLOCK_TIME;
30 
37 static constexpr int64_t MAX_BLOCK_TIME_GAP = 90 * 60;
38 
40 {
41 public:
42  unsigned int nBlocks;
43  unsigned int nSize;
44  unsigned int nUndoSize;
45  unsigned int nHeightFirst;
46  unsigned int nHeightLast;
47  uint64_t nTimeFirst;
48  uint64_t nTimeLast;
49 
51 
52  template <typename Stream, typename Operation>
53  inline void SerializationOp(Stream& s, Operation ser_action) {
54  READWRITE(VARINT(nBlocks));
55  READWRITE(VARINT(nSize));
56  READWRITE(VARINT(nUndoSize));
57  READWRITE(VARINT(nHeightFirst));
58  READWRITE(VARINT(nHeightLast));
59  READWRITE(VARINT(nTimeFirst));
60  READWRITE(VARINT(nTimeLast));
61  }
62 
63  void SetNull() {
64  nBlocks = 0;
65  nSize = 0;
66  nUndoSize = 0;
67  nHeightFirst = 0;
68  nHeightLast = 0;
69  nTimeFirst = 0;
70  nTimeLast = 0;
71  }
72 
74  SetNull();
75  }
76 
77  std::string ToString() const;
78 
80  void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn) {
81  if (nBlocks==0 || nHeightFirst > nHeightIn)
82  nHeightFirst = nHeightIn;
83  if (nBlocks==0 || nTimeFirst > nTimeIn)
84  nTimeFirst = nTimeIn;
85  nBlocks++;
86  if (nHeightIn > nHeightLast)
87  nHeightLast = nHeightIn;
88  if (nTimeIn > nTimeLast)
89  nTimeLast = nTimeIn;
90  }
91 };
92 
94 {
95  int nFile;
96  unsigned int nPos;
97 
99 
100  template <typename Stream, typename Operation>
101  inline void SerializationOp(Stream& s, Operation ser_action) {
103  READWRITE(VARINT(nPos));
104  }
105 
107  SetNull();
108  }
109 
110  CDiskBlockPos(int nFileIn, unsigned int nPosIn) {
111  nFile = nFileIn;
112  nPos = nPosIn;
113  }
114 
115  friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
116  return (a.nFile == b.nFile && a.nPos == b.nPos);
117  }
118 
119  friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
120  return !(a == b);
121  }
122 
123  void SetNull() { nFile = -1; nPos = 0; }
124  bool IsNull() const { return (nFile == -1); }
125 
126  std::string ToString() const
127  {
128  return strprintf("CDiskBlockPos(nFile=%i, nPos=%i)", nFile, nPos);
129  }
130 
131 };
132 
133 enum BlockStatus: uint32_t {
136 
139 
143 
150 
154 
157 
161 
165 
169 
171 };
172 
179 {
180 public:
183 
186 
189 
191  int nHeight;
192 
194  int nFile;
195 
197  unsigned int nDataPos;
198 
200  unsigned int nUndoPos;
201 
204 
207  unsigned int nTx;
208 
212  unsigned int nChainTx;
213 
215  uint32_t nStatus;
216 
218  int32_t nVersion;
220  uint32_t nTime;
221  uint32_t nBits;
222  uint32_t nNonce;
223 
225  int32_t nSequenceId;
226 
228  unsigned int nTimeMax;
229 
230  void SetNull()
231  {
232  phashBlock = nullptr;
233  pprev = nullptr;
234  pskip = nullptr;
235  nHeight = 0;
236  nFile = 0;
237  nDataPos = 0;
238  nUndoPos = 0;
239  nChainWork = arith_uint256();
240  nTx = 0;
241  nChainTx = 0;
242  nStatus = 0;
243  nSequenceId = 0;
244  nTimeMax = 0;
245 
246  nVersion = 0;
247  hashMerkleRoot = uint256();
248  nTime = 0;
249  nBits = 0;
250  nNonce = 0;
251  }
252 
254  {
255  SetNull();
256  }
257 
258  explicit CBlockIndex(const CBlockHeader& block)
259  {
260  SetNull();
261 
262  nVersion = block.nVersion;
263  hashMerkleRoot = block.hashMerkleRoot;
264  nTime = block.nTime;
265  nBits = block.nBits;
266  nNonce = block.nNonce;
267  }
268 
270  CDiskBlockPos ret;
271  if (nStatus & BLOCK_HAVE_DATA) {
272  ret.nFile = nFile;
273  ret.nPos = nDataPos;
274  }
275  return ret;
276  }
277 
279  CDiskBlockPos ret;
280  if (nStatus & BLOCK_HAVE_UNDO) {
281  ret.nFile = nFile;
282  ret.nPos = nUndoPos;
283  }
284  return ret;
285  }
286 
288  {
289  CBlockHeader block;
290  block.nVersion = nVersion;
291  if (pprev)
292  block.hashPrevBlock = pprev->GetBlockHash();
293  block.hashMerkleRoot = hashMerkleRoot;
294  block.nTime = nTime;
295  block.nBits = nBits;
296  block.nNonce = nNonce;
297  return block;
298  }
299 
301  {
302  return *phashBlock;
303  }
304 
312  bool HaveTxsDownloaded() const { return nChainTx != 0; }
313 
314  int64_t GetBlockTime() const
315  {
316  return (int64_t)nTime;
317  }
318 
319  int64_t GetBlockTimeMax() const
320  {
321  return (int64_t)nTimeMax;
322  }
323 
324  static constexpr int nMedianTimeSpan = 11;
325 
326  int64_t GetMedianTimePast() const
327  {
328  int64_t pmedian[nMedianTimeSpan];
329  int64_t* pbegin = &pmedian[nMedianTimeSpan];
330  int64_t* pend = &pmedian[nMedianTimeSpan];
331 
332  const CBlockIndex* pindex = this;
333  for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
334  *(--pbegin) = pindex->GetBlockTime();
335 
336  std::sort(pbegin, pend);
337  return pbegin[(pend - pbegin)/2];
338  }
339 
340  std::string ToString() const
341  {
342  return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
343  pprev, nHeight,
344  hashMerkleRoot.ToString(),
345  GetBlockHash().ToString());
346  }
347 
350  {
351  assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
352  if (nStatus & BLOCK_FAILED_MASK)
353  return false;
354  return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
355  }
356 
359  bool RaiseValidity(enum BlockStatus nUpTo)
360  {
361  assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
362  if (nStatus & BLOCK_FAILED_MASK)
363  return false;
364  if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
365  nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
366  return true;
367  }
368  return false;
369  }
370 
372  void BuildSkip();
373 
375  CBlockIndex* GetAncestor(int height);
376  const CBlockIndex* GetAncestor(int height) const;
377 };
378 
381 int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params&);
383 const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb);
384 
385 
388 {
389 public:
391 
393  hashPrev = uint256();
394  }
395 
396  explicit CDiskBlockIndex(const CBlockIndex* pindex) : CBlockIndex(*pindex) {
397  hashPrev = (pprev ? pprev->GetBlockHash() : uint256());
398  }
399 
401 
402  template <typename Stream, typename Operation>
403  inline void SerializationOp(Stream& s, Operation ser_action) {
404  int _nVersion = s.GetVersion();
405  if (!(s.GetType() & SER_GETHASH))
407 
409  READWRITE(VARINT(nStatus));
410  READWRITE(VARINT(nTx));
411  if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
413  if (nStatus & BLOCK_HAVE_DATA)
414  READWRITE(VARINT(nDataPos));
415  if (nStatus & BLOCK_HAVE_UNDO)
416  READWRITE(VARINT(nUndoPos));
417 
418  // block header
419  READWRITE(this->nVersion);
420  READWRITE(hashPrev);
421  READWRITE(hashMerkleRoot);
422  READWRITE(nTime);
423  READWRITE(nBits);
424  READWRITE(nNonce);
425  }
426 
428  {
429  CBlockHeader block;
430  block.nVersion = nVersion;
431  block.hashPrevBlock = hashPrev;
432  block.hashMerkleRoot = hashMerkleRoot;
433  block.nTime = nTime;
434  block.nBits = nBits;
435  block.nNonce = nNonce;
436  return block.GetHash();
437  }
438 
439 
440  std::string ToString() const
441  {
442  std::string str = "CDiskBlockIndex(";
443  str += CBlockIndex::ToString();
444  str += strprintf("\n hashBlock=%s, hashPrev=%s)",
445  GetBlockHash().ToString(),
446  hashPrev.ToString());
447  return str;
448  }
449 };
450 
452 class CChain {
453 private:
454  std::vector<CBlockIndex*> vChain;
455 
456 public:
458  CBlockIndex *Genesis() const {
459  return vChain.size() > 0 ? vChain[0] : nullptr;
460  }
461 
463  CBlockIndex *Tip() const {
464  return vChain.size() > 0 ? vChain[vChain.size() - 1] : nullptr;
465  }
466 
469  if (nHeight < 0 || nHeight >= (int)vChain.size())
470  return nullptr;
471  return vChain[nHeight];
472  }
473 
475  friend bool operator==(const CChain &a, const CChain &b) {
476  return a.vChain.size() == b.vChain.size() &&
477  a.vChain[a.vChain.size() - 1] == b.vChain[b.vChain.size() - 1];
478  }
479 
481  bool Contains(const CBlockIndex *pindex) const {
482  return (*this)[pindex->nHeight] == pindex;
483  }
484 
486  CBlockIndex *Next(const CBlockIndex *pindex) const {
487  if (Contains(pindex))
488  return (*this)[pindex->nHeight + 1];
489  else
490  return nullptr;
491  }
492 
494  int Height() const {
495  return vChain.size() - 1;
496  }
497 
499  void SetTip(CBlockIndex *pindex);
500 
502  CBlockLocator GetLocator(const CBlockIndex *pindex = nullptr) const;
503 
505  const CBlockIndex *FindFork(const CBlockIndex *pindex) const;
506 
508  CBlockIndex* FindEarliestAtLeast(int64_t nTime) const;
509 };
510 
511 #endif // BITCOIN_CHAIN_H
uint32_t nNonce
Definition: block.h:29
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:203
ADD_SERIALIZE_METHODS
Definition: chain.h:400
CDiskBlockPos GetBlockPos() const
Definition: chain.h:269
std::string ToString() const
Definition: chain.h:340
int32_t nSequenceId
(memory only) Sequential id assigned to distinguish order in which blocks are received.
Definition: chain.h:225
ADD_SERIALIZE_METHODS
Definition: chain.h:50
CBlockIndex * pskip
pointer to the index of some further predecessor of this block
Definition: chain.h:188
std::vector< CBlockIndex * > vChain
Definition: chain.h:454
CDiskBlockPos(int nFileIn, unsigned int nPosIn)
Definition: chain.h:110
int64_t GetBlockTime() const
Definition: chain.h:314
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:126
descends from failed block
Definition: chain.h:167
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:185
uint32_t nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:215
void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn)
update statistics (does not update nSize)
Definition: chain.h:80
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the forking point between two chain tips.
Definition: chain.cpp:155
#define strprintf
Definition: tinyformat.h:1066
An in-memory indexed chain of blocks.
Definition: chain.h:452
CBlockIndex()
Definition: chain.h:253
unsigned int nHeight
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
Definition: chain.h:142
CBlockHeader GetBlockHeader() const
Definition: chain.h:287
int Height() const
Return the maximal height in the chain.
Definition: chain.h:494
stage after last reached validness failed
Definition: chain.h:166
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid...
Definition: chain.h:149
unsigned int nSize
number of used bytes of block file
Definition: chain.h:43
friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b)
Definition: chain.h:115
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
Definition: chain.h:458
uint32_t nTime
Definition: chain.h:220
undo data available in rev*.dat
Definition: chain.h:163
int nFile
Which # file this block is stored in (blk?????.dat)
Definition: chain.h:194
Unused.
Definition: chain.h:135
unsigned int nHeightLast
highest height of block in file
Definition: chain.h:46
uint32_t nTime
Definition: block.h:27
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block. ...
Definition: chain.h:212
unsigned int nUndoSize
number of used bytes in the undo file
Definition: chain.h:44
friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b)
Definition: chain.h:119
uint256 GetBlockHash() const
Definition: chain.h:300
void SetNull()
Definition: chain.h:63
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:349
arith_uint256 GetBlockProof(const CBlockIndex &block)
Definition: chain.cpp:121
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends...
Definition: chain.h:153
unsigned int nTimeMax
(memory only) Maximum nTime in the chain up to and including this block.
Definition: chain.h:228
uint64_t nTimeFirst
earliest time of block in file
Definition: chain.h:47
ADD_SERIALIZE_METHODS
Definition: chain.h:98
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:468
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
Definition: chain.h:156
uint256 hashMerkleRoot
Definition: block.h:26
void SerializationOp(Stream &s, Operation ser_action)
Definition: chain.h:101
uint32_t nNonce
Definition: chain.h:222
unsigned int nDataPos
Byte offset within blk?????.dat where this block&#39;s data is stored.
Definition: chain.h:197
CBlockFileInfo()
Definition: chain.h:73
Parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future...
Definition: chain.h:138
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:481
CBlockIndex(const CBlockHeader &block)
Definition: chain.h:258
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:486
uint256 hashPrevBlock
Definition: block.h:25
int64_t GetBlockTimeMax() const
Definition: chain.h:319
CDiskBlockIndex()
Definition: chain.h:392
CDiskBlockPos()
Definition: chain.h:106
uint256 hashMerkleRoot
Definition: chain.h:219
friend bool operator==(const CChain &a, const CChain &b)
Compare two chains efficiently.
Definition: chain.h:475
unsigned int nHeightFirst
lowest height of block in file
Definition: chain.h:45
std::string ToString() const
Definition: chain.h:126
Used to marshal pointers into hashes for db storage.
Definition: chain.h:387
std::string ToString() const
Definition: uint256.cpp:62
Parameters that influence chain consensus.
Definition: params.h:49
bool IsNull() const
Definition: chain.h:124
256-bit unsigned big integer.
int64_t GetMedianTimePast() const
Definition: chain.h:326
block data in blk*.data was received with a witness-enforcing client
Definition: chain.h:170
unsigned int nPos
Definition: chain.h:96
void SerializationOp(Stream &s, Operation ser_action)
Definition: chain.h:53
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:136
unsigned int nUndoPos
Byte offset within rev?????.dat where this block&#39;s undo data is stored.
Definition: chain.h:200
uint256 GetHash() const
Definition: block.cpp:13
int32_t nVersion
block header
Definition: chain.h:218
256-bit opaque blob.
Definition: uint256.h:121
uint256 hashPrev
Definition: chain.h:390
void SerializationOp(Stream &s, Operation ser_action)
Definition: chain.h:403
CDiskBlockIndex(const CBlockIndex *pindex)
Definition: chain.h:396
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:178
CDiskBlockPos GetUndoPos() const
Definition: chain.h:278
void SetNull()
Definition: chain.h:123
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:463
unsigned int nBlocks
number of blocks stored in file
Definition: chain.h:42
std::string ToString() const
Definition: chain.h:440
bool RaiseValidity(enum BlockStatus nUpTo)
Raise the validity level of this block index entry.
Definition: chain.h:359
BlockStatus
Definition: chain.h:133
All validity bits.
Definition: chain.h:159
uint64_t nTimeLast
latest time of block in file
Definition: chain.h:48
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:191
full block available in blk*.dat
Definition: chain.h:162
uint256 GetBlockHash() const
Definition: chain.h:427
#define READWRITE(...)
Definition: serialize.h:173
int nFile
Definition: chain.h:95
std::string ToString() const
int32_t nVersion
Definition: block.h:24
bool HaveTxsDownloaded() const
Check whether this block&#39;s and all previous blocks&#39; transactions have been downloaded (and stored to ...
Definition: chain.h:312
uint32_t nBits
Definition: chain.h:221
#define VARINT(obj,...)
Definition: serialize.h:411
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:207
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
void SetNull()
Definition: chain.h:230
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Definition: chain.h:182