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-2017 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 const int64_t MAX_FUTURE_BLOCK_TIME = 2 * 60 * 60;
22 
29 static const int64_t TIMESTAMP_WINDOW = MAX_FUTURE_BLOCK_TIME;
30 
32 {
33 public:
34  unsigned int nBlocks;
35  unsigned int nSize;
36  unsigned int nUndoSize;
37  unsigned int nHeightFirst;
38  unsigned int nHeightLast;
39  uint64_t nTimeFirst;
40  uint64_t nTimeLast;
41 
43 
44  template <typename Stream, typename Operation>
45  inline void SerializationOp(Stream& s, Operation ser_action) {
46  READWRITE(VARINT(nBlocks));
47  READWRITE(VARINT(nSize));
48  READWRITE(VARINT(nUndoSize));
49  READWRITE(VARINT(nHeightFirst));
50  READWRITE(VARINT(nHeightLast));
51  READWRITE(VARINT(nTimeFirst));
52  READWRITE(VARINT(nTimeLast));
53  }
54 
55  void SetNull() {
56  nBlocks = 0;
57  nSize = 0;
58  nUndoSize = 0;
59  nHeightFirst = 0;
60  nHeightLast = 0;
61  nTimeFirst = 0;
62  nTimeLast = 0;
63  }
64 
66  SetNull();
67  }
68 
69  std::string ToString() const;
70 
72  void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn) {
73  if (nBlocks==0 || nHeightFirst > nHeightIn)
74  nHeightFirst = nHeightIn;
75  if (nBlocks==0 || nTimeFirst > nTimeIn)
76  nTimeFirst = nTimeIn;
77  nBlocks++;
78  if (nHeightIn > nHeightLast)
79  nHeightLast = nHeightIn;
80  if (nTimeIn > nTimeLast)
81  nTimeLast = nTimeIn;
82  }
83 };
84 
86 {
87  int nFile;
88  unsigned int nPos;
89 
91 
92  template <typename Stream, typename Operation>
93  inline void SerializationOp(Stream& s, Operation ser_action) {
95  READWRITE(VARINT(nPos));
96  }
97 
99  SetNull();
100  }
101 
102  CDiskBlockPos(int nFileIn, unsigned int nPosIn) {
103  nFile = nFileIn;
104  nPos = nPosIn;
105  }
106 
107  friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
108  return (a.nFile == b.nFile && a.nPos == b.nPos);
109  }
110 
111  friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
112  return !(a == b);
113  }
114 
115  void SetNull() { nFile = -1; nPos = 0; }
116  bool IsNull() const { return (nFile == -1); }
117 
118  std::string ToString() const
119  {
120  return strprintf("CBlockDiskPos(nFile=%i, nPos=%i)", nFile, nPos);
121  }
122 
123 };
124 
125 enum BlockStatus: uint32_t {
128 
131 
135 
142 
146 
149 
153 
157 
161 
163 };
164 
171 {
172 public:
175 
178 
181 
183  int nHeight;
184 
186  int nFile;
187 
189  unsigned int nDataPos;
190 
192  unsigned int nUndoPos;
193 
196 
199  unsigned int nTx;
200 
204  unsigned int nChainTx;
205 
207  uint32_t nStatus;
208 
210  int32_t nVersion;
212  uint32_t nTime;
213  uint32_t nBits;
214  uint32_t nNonce;
215 
217  int32_t nSequenceId;
218 
220  unsigned int nTimeMax;
221 
222  void SetNull()
223  {
224  phashBlock = nullptr;
225  pprev = nullptr;
226  pskip = nullptr;
227  nHeight = 0;
228  nFile = 0;
229  nDataPos = 0;
230  nUndoPos = 0;
231  nChainWork = arith_uint256();
232  nTx = 0;
233  nChainTx = 0;
234  nStatus = 0;
235  nSequenceId = 0;
236  nTimeMax = 0;
237 
238  nVersion = 0;
239  hashMerkleRoot = uint256();
240  nTime = 0;
241  nBits = 0;
242  nNonce = 0;
243  }
244 
246  {
247  SetNull();
248  }
249 
250  explicit CBlockIndex(const CBlockHeader& block)
251  {
252  SetNull();
253 
254  nVersion = block.nVersion;
255  hashMerkleRoot = block.hashMerkleRoot;
256  nTime = block.nTime;
257  nBits = block.nBits;
258  nNonce = block.nNonce;
259  }
260 
262  CDiskBlockPos ret;
263  if (nStatus & BLOCK_HAVE_DATA) {
264  ret.nFile = nFile;
265  ret.nPos = nDataPos;
266  }
267  return ret;
268  }
269 
271  CDiskBlockPos ret;
272  if (nStatus & BLOCK_HAVE_UNDO) {
273  ret.nFile = nFile;
274  ret.nPos = nUndoPos;
275  }
276  return ret;
277  }
278 
280  {
281  CBlockHeader block;
282  block.nVersion = nVersion;
283  if (pprev)
284  block.hashPrevBlock = pprev->GetBlockHash();
285  block.hashMerkleRoot = hashMerkleRoot;
286  block.nTime = nTime;
287  block.nBits = nBits;
288  block.nNonce = nNonce;
289  return block;
290  }
291 
293  {
294  return *phashBlock;
295  }
296 
297  int64_t GetBlockTime() const
298  {
299  return (int64_t)nTime;
300  }
301 
302  int64_t GetBlockTimeMax() const
303  {
304  return (int64_t)nTimeMax;
305  }
306 
307  static constexpr int nMedianTimeSpan = 11;
308 
309  int64_t GetMedianTimePast() const
310  {
311  int64_t pmedian[nMedianTimeSpan];
312  int64_t* pbegin = &pmedian[nMedianTimeSpan];
313  int64_t* pend = &pmedian[nMedianTimeSpan];
314 
315  const CBlockIndex* pindex = this;
316  for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
317  *(--pbegin) = pindex->GetBlockTime();
318 
319  std::sort(pbegin, pend);
320  return pbegin[(pend - pbegin)/2];
321  }
322 
323  std::string ToString() const
324  {
325  return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
326  pprev, nHeight,
327  hashMerkleRoot.ToString(),
328  GetBlockHash().ToString());
329  }
330 
333  {
334  assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
335  if (nStatus & BLOCK_FAILED_MASK)
336  return false;
337  return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
338  }
339 
342  bool RaiseValidity(enum BlockStatus nUpTo)
343  {
344  assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
345  if (nStatus & BLOCK_FAILED_MASK)
346  return false;
347  if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
348  nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
349  return true;
350  }
351  return false;
352  }
353 
355  void BuildSkip();
356 
358  CBlockIndex* GetAncestor(int height);
359  const CBlockIndex* GetAncestor(int height) const;
360 };
361 
364 int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params&);
366 const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb);
367 
368 
371 {
372 public:
374 
376  hashPrev = uint256();
377  }
378 
379  explicit CDiskBlockIndex(const CBlockIndex* pindex) : CBlockIndex(*pindex) {
380  hashPrev = (pprev ? pprev->GetBlockHash() : uint256());
381  }
382 
384 
385  template <typename Stream, typename Operation>
386  inline void SerializationOp(Stream& s, Operation ser_action) {
387  int _nVersion = s.GetVersion();
388  if (!(s.GetType() & SER_GETHASH))
390 
392  READWRITE(VARINT(nStatus));
393  READWRITE(VARINT(nTx));
394  if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
396  if (nStatus & BLOCK_HAVE_DATA)
397  READWRITE(VARINT(nDataPos));
398  if (nStatus & BLOCK_HAVE_UNDO)
399  READWRITE(VARINT(nUndoPos));
400 
401  // block header
402  READWRITE(this->nVersion);
403  READWRITE(hashPrev);
404  READWRITE(hashMerkleRoot);
405  READWRITE(nTime);
406  READWRITE(nBits);
407  READWRITE(nNonce);
408  }
409 
411  {
412  CBlockHeader block;
413  block.nVersion = nVersion;
414  block.hashPrevBlock = hashPrev;
415  block.hashMerkleRoot = hashMerkleRoot;
416  block.nTime = nTime;
417  block.nBits = nBits;
418  block.nNonce = nNonce;
419  return block.GetHash();
420  }
421 
422 
423  std::string ToString() const
424  {
425  std::string str = "CDiskBlockIndex(";
426  str += CBlockIndex::ToString();
427  str += strprintf("\n hashBlock=%s, hashPrev=%s)",
428  GetBlockHash().ToString(),
429  hashPrev.ToString());
430  return str;
431  }
432 };
433 
435 class CChain {
436 private:
437  std::vector<CBlockIndex*> vChain;
438 
439 public:
441  CBlockIndex *Genesis() const {
442  return vChain.size() > 0 ? vChain[0] : nullptr;
443  }
444 
446  CBlockIndex *Tip() const {
447  return vChain.size() > 0 ? vChain[vChain.size() - 1] : nullptr;
448  }
449 
451  CBlockIndex *operator[](int nHeight) const {
452  if (nHeight < 0 || nHeight >= (int)vChain.size())
453  return nullptr;
454  return vChain[nHeight];
455  }
456 
458  friend bool operator==(const CChain &a, const CChain &b) {
459  return a.vChain.size() == b.vChain.size() &&
460  a.vChain[a.vChain.size() - 1] == b.vChain[b.vChain.size() - 1];
461  }
462 
464  bool Contains(const CBlockIndex *pindex) const {
465  return (*this)[pindex->nHeight] == pindex;
466  }
467 
469  CBlockIndex *Next(const CBlockIndex *pindex) const {
470  if (Contains(pindex))
471  return (*this)[pindex->nHeight + 1];
472  else
473  return nullptr;
474  }
475 
477  int Height() const {
478  return vChain.size() - 1;
479  }
480 
482  void SetTip(CBlockIndex *pindex);
483 
485  CBlockLocator GetLocator(const CBlockIndex *pindex = nullptr) const;
486 
488  const CBlockIndex *FindFork(const CBlockIndex *pindex) const;
489 
491  CBlockIndex* FindEarliestAtLeast(int64_t nTime) const;
492 };
493 
494 #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:195
ADD_SERIALIZE_METHODS
Definition: chain.h:383
CDiskBlockPos GetBlockPos() const
Definition: chain.h:261
int32_t nSequenceId
(memory only) Sequential id assigned to distinguish order in which blocks are received.
Definition: chain.h:217
ADD_SERIALIZE_METHODS
Definition: chain.h:42
CBlockIndex * pskip
pointer to the index of some further predecessor of this block
Definition: chain.h:180
std::vector< CBlockIndex * > vChain
Definition: chain.h:437
CDiskBlockPos(int nFileIn, unsigned int nPosIn)
Definition: chain.h:102
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:159
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:177
uint32_t nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:207
void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn)
update statistics (does not update nSize)
Definition: chain.h:72
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:435
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:451
CBlockIndex()
Definition: chain.h:245
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
Definition: chain.h:134
std::string ToString() const
Definition: chain.h:323
stage after last reached validness failed
Definition: chain.h:158
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid...
Definition: chain.h:141
unsigned int nSize
number of used bytes of block file
Definition: chain.h:35
friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b)
Definition: chain.h:107
uint32_t nTime
Definition: chain.h:212
undo data available in rev*.dat
Definition: chain.h:155
int nFile
Which # file this block is stored in (blk?????.dat)
Definition: chain.h:186
Unused.
Definition: chain.h:127
unsigned int nHeightLast
highest height of block in file
Definition: chain.h:38
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:204
unsigned int nUndoSize
number of used bytes in the undo file
Definition: chain.h:36
std::string ToString() const
Definition: uint256.cpp:62
friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b)
Definition: chain.h:111
int64_t GetBlockTimeMax() const
Definition: chain.h:302
void SetNull()
Definition: chain.h:55
arith_uint256 GetBlockProof(const CBlockIndex &block)
Definition: chain.cpp:121
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:446
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends...
Definition: chain.h:145
int Height() const
Return the maximal height in the chain.
Definition: chain.h:477
unsigned int nTimeMax
(memory only) Maximum nTime in the chain up to and including this block.
Definition: chain.h:220
uint64_t nTimeFirst
earliest time of block in file
Definition: chain.h:39
ADD_SERIALIZE_METHODS
Definition: chain.h:90
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:469
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
Definition: chain.h:148
CBlockHeader GetBlockHeader() const
Definition: chain.h:279
uint256 hashMerkleRoot
Definition: block.h:26
void SerializationOp(Stream &s, Operation ser_action)
Definition: chain.h:93
uint32_t nNonce
Definition: chain.h:214
unsigned int nDataPos
Byte offset within blk?????.dat where this block&#39;s data is stored.
Definition: chain.h:189
CBlockFileInfo()
Definition: chain.h:65
uint256 GetBlockHash() const
Definition: chain.h:410
Parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future...
Definition: chain.h:130
CBlockIndex(const CBlockHeader &block)
Definition: chain.h:250
uint256 hashPrevBlock
Definition: block.h:25
CDiskBlockIndex()
Definition: chain.h:375
CDiskBlockPos()
Definition: chain.h:98
uint256 hashMerkleRoot
Definition: chain.h:211
friend bool operator==(const CChain &a, const CChain &b)
Compare two chains efficiently.
Definition: chain.h:458
unsigned int nHeightFirst
lowest height of block in file
Definition: chain.h:37
std::string ToString() const
Definition: chain.h:118
Used to marshal pointers into hashes for db storage.
Definition: chain.h:370
bool IsNull() const
Definition: chain.h:116
Parameters that influence chain consensus.
Definition: params.h:49
std::string ToString() const
Definition: chain.h:423
256-bit unsigned big integer.
block data in blk*.data was received with a witness-enforcing client
Definition: chain.h:162
unsigned int nPos
Definition: chain.h:88
void SerializationOp(Stream &s, Operation ser_action)
Definition: chain.h:45
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:192
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
Definition: chain.h:441
int32_t nVersion
block header
Definition: chain.h:210
256-bit opaque blob.
Definition: uint256.h:122
uint256 hashPrev
Definition: chain.h:373
uint256 GetHash() const
Definition: block.cpp:13
void SerializationOp(Stream &s, Operation ser_action)
Definition: chain.h:386
CDiskBlockIndex(const CBlockIndex *pindex)
Definition: chain.h:379
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:170
void SetNull()
Definition: chain.h:115
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:464
unsigned int nBlocks
number of blocks stored in file
Definition: chain.h:34
std::string ToString() const
bool RaiseValidity(enum BlockStatus nUpTo)
Raise the validity level of this block index entry.
Definition: chain.h:342
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:332
BlockStatus
Definition: chain.h:125
All validity bits.
Definition: chain.h:151
uint64_t nTimeLast
latest time of block in file
Definition: chain.h:40
CDiskBlockPos GetUndoPos() const
Definition: chain.h:270
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:183
full block available in blk*.dat
Definition: chain.h:154
int64_t GetBlockTime() const
Definition: chain.h:297
#define READWRITE(...)
Definition: serialize.h:173
int nFile
Definition: chain.h:87
int64_t GetMedianTimePast() const
Definition: chain.h:309
int32_t nVersion
Definition: block.h:24
uint32_t nBits
Definition: chain.h:213
#define VARINT(obj,...)
Definition: serialize.h:407
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:199
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:20
uint256 GetBlockHash() const
Definition: chain.h:292
uint32_t nBits
Definition: block.h:28
void SetNull()
Definition: chain.h:222
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Definition: chain.h:174