Dogecoin Core  1.14.2
P2P Digital Currency
chain.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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 "primitives/block.h"
11 #include "primitives/pureheader.h"
12 #include "pow.h"
13 #include "tinyformat.h"
14 #include "uint256.h"
15 
16 #include <vector>
17 
19 {
20 public:
21  unsigned int nBlocks;
22  unsigned int nSize;
23  unsigned int nUndoSize;
24  unsigned int nHeightFirst;
25  unsigned int nHeightLast;
26  uint64_t nTimeFirst;
27  uint64_t nTimeLast;
28 
30 
31  template <typename Stream, typename Operation>
32  inline void SerializationOp(Stream& s, Operation ser_action) {
40  }
41 
42  void SetNull() {
43  nBlocks = 0;
44  nSize = 0;
45  nUndoSize = 0;
46  nHeightFirst = 0;
47  nHeightLast = 0;
48  nTimeFirst = 0;
49  nTimeLast = 0;
50  }
51 
53  SetNull();
54  }
55 
56  std::string ToString() const;
57 
59  void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn) {
60  if (nBlocks==0 || nHeightFirst > nHeightIn)
61  nHeightFirst = nHeightIn;
62  if (nBlocks==0 || nTimeFirst > nTimeIn)
63  nTimeFirst = nTimeIn;
64  nBlocks++;
65  if (nHeightIn > nHeightLast)
66  nHeightLast = nHeightIn;
67  if (nTimeIn > nTimeLast)
68  nTimeLast = nTimeIn;
69  }
70 };
71 
73 {
74  int nFile;
75  unsigned int nPos;
76 
78 
79  template <typename Stream, typename Operation>
80  inline void SerializationOp(Stream& s, Operation ser_action) {
83  }
84 
86  SetNull();
87  }
88 
89  CDiskBlockPos(int nFileIn, unsigned int nPosIn) {
90  nFile = nFileIn;
91  nPos = nPosIn;
92  }
93 
94  friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
95  return (a.nFile == b.nFile && a.nPos == b.nPos);
96  }
97 
98  friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
99  return !(a == b);
100  }
101 
102  void SetNull() { nFile = -1; nPos = 0; }
103  bool IsNull() const { return (nFile == -1); }
104 
105  std::string ToString() const
106  {
107  return strprintf("CBlockDiskPos(nFile=%i, nPos=%i)", nFile, nPos);
108  }
109 
110 };
111 
112 enum BlockStatus: uint32_t {
115 
118 
122 
129 
133 
136 
140 
144 
148 
150 };
151 
158 {
159 public:
162 
165 
168 
170  int nHeight;
171 
173  int nFile;
174 
176  unsigned int nDataPos;
177 
179  unsigned int nUndoPos;
180 
183 
186  unsigned int nTx;
187 
191  unsigned int nChainTx;
192 
194  unsigned int nStatus;
195 
197  int nVersion;
199  unsigned int nTime;
200  unsigned int nBits;
201  unsigned int nNonce;
202 
204  int32_t nSequenceId;
205 
207  unsigned int nTimeMax;
208 
209  void SetNull()
210  {
211  phashBlock = NULL;
212  pprev = NULL;
213  pskip = NULL;
214  nHeight = 0;
215  nFile = 0;
216  nDataPos = 0;
217  nUndoPos = 0;
219  nTx = 0;
220  nChainTx = 0;
221  nStatus = 0;
222  nSequenceId = 0;
223  nTimeMax = 0;
224 
225  nVersion = 0;
227  nTime = 0;
228  nBits = 0;
229  nNonce = 0;
230  }
231 
233  {
234  SetNull();
235  }
236 
237  CBlockIndex(const CBlockHeader& block)
238  {
239  SetNull();
240 
241  nVersion = block.nVersion;
243  nTime = block.nTime;
244  nBits = block.nBits;
245  nNonce = block.nNonce;
246  }
247 
249  CDiskBlockPos ret;
250  if (nStatus & BLOCK_HAVE_DATA) {
251  ret.nFile = nFile;
252  ret.nPos = nDataPos;
253  }
254  return ret;
255  }
256 
258  CDiskBlockPos ret;
259  if (nStatus & BLOCK_HAVE_UNDO) {
260  ret.nFile = nFile;
261  ret.nPos = nUndoPos;
262  }
263  return ret;
264  }
265 
266  CBlockHeader GetBlockHeader(const Consensus::Params& consensusParams, bool fCheckPOW = true) const;
267 
269  {
270  return *phashBlock;
271  }
272 
273  int64_t GetBlockTime() const
274  {
275  return (int64_t)nTime;
276  }
277 
278  int64_t GetBlockTimeMax() const
279  {
280  return (int64_t)nTimeMax;
281  }
282 
283  enum { nMedianTimeSpan=11 };
284 
285  int64_t GetMedianTimePast() const
286  {
287  int64_t pmedian[nMedianTimeSpan];
288  int64_t* pbegin = &pmedian[nMedianTimeSpan];
289  int64_t* pend = &pmedian[nMedianTimeSpan];
290 
291  const CBlockIndex* pindex = this;
292  for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
293  *(--pbegin) = pindex->GetBlockTime();
294 
295  std::sort(pbegin, pend);
296  return pbegin[(pend - pbegin)/2];
297  }
298 
299  std::string ToString() const
300  {
301  return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
302  pprev, nHeight,
304  GetBlockHash().ToString());
305  }
306 
309  {
310  assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
312  return false;
313  return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
314  }
315 
318  bool RaiseValidity(enum BlockStatus nUpTo)
319  {
320  assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
322  return false;
323  if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
324  nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
325  return true;
326  }
327  return false;
328  }
329 
331  void BuildSkip();
332 
334  CBlockIndex* GetAncestor(int height);
335  const CBlockIndex* GetAncestor(int height) const;
336 
341  inline int32_t GetChainId() const
342  {
343  return nVersion >> 16;
344  }
345 
350  inline bool IsAuxpow() const
351  {
353  }
354 
355  /* Analyse the block version. */
356  inline int GetBaseVersion() const
357  {
359  }
360 };
361 
364 int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params&);
365 
368 {
369 public:
371 
373  hashPrev = uint256();
374  }
375 
376  explicit CDiskBlockIndex(const CBlockIndex* pindex) : CBlockIndex(*pindex) {
377  hashPrev = (pprev ? pprev->GetBlockHash() : uint256());
378  }
379 
381 
382  template <typename Stream, typename Operation>
383  inline void SerializationOp(Stream& s, Operation ser_action) {
384  int nVersion = s.GetVersion();
385  if (!(s.GetType() & SER_GETHASH))
387 
390  READWRITE(VARINT(nTx));
393  if (nStatus & BLOCK_HAVE_DATA)
395  if (nStatus & BLOCK_HAVE_UNDO)
397 
398  // block header
399  READWRITE(this->nVersion);
402  READWRITE(nTime);
403  READWRITE(nBits);
404  READWRITE(nNonce);
405  }
406 
408  {
409  CBlockHeader block;
410  block.nVersion = nVersion;
411  block.hashPrevBlock = hashPrev;
413  block.nTime = nTime;
414  block.nBits = nBits;
415  block.nNonce = nNonce;
416  return block.GetHash();
417  }
418 
419 
420  std::string ToString() const
421  {
422  std::string str = "CDiskBlockIndex(";
423  str += CBlockIndex::ToString();
424  str += strprintf("\n hashBlock=%s, hashPrev=%s)",
426  hashPrev.ToString());
427  return str;
428  }
429 };
430 
432 class CChain {
433 private:
434  std::vector<CBlockIndex*> vChain;
435 
436 public:
438  CBlockIndex *Genesis() const {
439  return vChain.size() > 0 ? vChain[0] : NULL;
440  }
441 
443  CBlockIndex *Tip() const {
444  return vChain.size() > 0 ? vChain[vChain.size() - 1] : NULL;
445  }
446 
448  CBlockIndex *operator[](int nHeight) const {
449  if (nHeight < 0 || nHeight >= (int)vChain.size())
450  return NULL;
451  return vChain[nHeight];
452  }
453 
455  friend bool operator==(const CChain &a, const CChain &b) {
456  return a.vChain.size() == b.vChain.size() &&
457  a.vChain[a.vChain.size() - 1] == b.vChain[b.vChain.size() - 1];
458  }
459 
461  bool Contains(const CBlockIndex *pindex) const {
462  return (*this)[pindex->nHeight] == pindex;
463  }
464 
466  CBlockIndex *Next(const CBlockIndex *pindex) const {
467  if (Contains(pindex))
468  return (*this)[pindex->nHeight + 1];
469  else
470  return NULL;
471  }
472 
474  int Height() const {
475  return vChain.size() - 1;
476  }
477 
479  void SetTip(CBlockIndex *pindex);
480 
482  CBlockLocator GetLocator(const CBlockIndex *pindex = NULL) const;
483 
485  const CBlockIndex *FindFork(const CBlockIndex *pindex) const;
486 
488  CBlockIndex* FindEarliestAtLeast(int64_t nTime) const;
489 };
490 
491 #endif // BITCOIN_CHAIN_H
BlockStatus
Definition: chain.h:112
@ BLOCK_VALID_CHAIN
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends,...
Definition: chain.h:132
@ BLOCK_VALID_MASK
All validity bits.
Definition: chain.h:138
@ BLOCK_VALID_TRANSACTIONS
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid,...
Definition: chain.h:128
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
Definition: chain.h:135
@ BLOCK_VALID_TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
Definition: chain.h:121
@ BLOCK_HAVE_UNDO
undo data available in rev*.dat
Definition: chain.h:142
@ BLOCK_HAVE_DATA
full block available in blk*.dat
Definition: chain.h:141
@ BLOCK_FAILED_CHILD
descends from failed block
Definition: chain.h:146
@ BLOCK_FAILED_MASK
Definition: chain.h:147
@ BLOCK_VALID_HEADER
Parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future.
Definition: chain.h:117
@ BLOCK_FAILED_VALID
stage after last reached validness failed
Definition: chain.h:145
@ BLOCK_OPT_WITNESS
block data in blk*.data was received with a witness-enforcing client
Definition: chain.h:149
@ BLOCK_HAVE_MASK
Definition: chain.h:143
@ BLOCK_VALID_UNKNOWN
Unused.
Definition: chain.h:114
arith_uint256 GetBlockProof(const CBlockIndex &block)
Definition: chain.cpp:149
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:164
uint64_t nTimeFirst
earliest time of block in file
Definition: chain.h:26
uint64_t nTimeLast
latest time of block in file
Definition: chain.h:27
void SetNull()
Definition: chain.h:42
std::string ToString() const
CBlockFileInfo()
Definition: chain.h:52
void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn)
update statistics (does not update nSize)
Definition: chain.h:59
unsigned int nHeightFirst
lowest height of block in file
Definition: chain.h:24
void SerializationOp(Stream &s, Operation ser_action)
Definition: chain.h:32
unsigned int nHeightLast
highest height of block in file
Definition: chain.h:25
ADD_SERIALIZE_METHODS
Definition: chain.h:29
unsigned int nUndoSize
number of used bytes in the undo file
Definition: chain.h:23
unsigned int nBlocks
number of blocks stored in file
Definition: chain.h:21
unsigned int nSize
number of used bytes of block file
Definition: chain.h:22
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:25
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:158
uint256 hashMerkleRoot
Definition: chain.h:198
bool RaiseValidity(enum BlockStatus nUpTo)
Raise the validity level of this block index entry.
Definition: chain.h:318
CBlockIndex()
Definition: chain.h:232
std::string ToString() const
Definition: chain.h:299
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:164
void BuildSkip()
Build the skiplist pointer for this entry.
Definition: chain.cpp:143
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:182
int32_t GetChainId() const
Extract the chain ID.
Definition: chain.h:341
unsigned int nBits
Definition: chain.h:200
int nFile
Which # file this block is stored in (blk?????.dat)
Definition: chain.h:173
int nVersion
block header
Definition: chain.h:197
unsigned int nTime
Definition: chain.h:199
unsigned int nNonce
Definition: chain.h:201
void SetNull()
Definition: chain.h:209
CBlockHeader GetBlockHeader(const Consensus::Params &consensusParams, bool fCheckPOW=true) const
Definition: chain.cpp:13
int GetBaseVersion() const
Definition: chain.h:356
unsigned int nTimeMax
(memory only) Maximum nTime in the chain upto and including this block.
Definition: chain.h:207
int32_t nSequenceId
(memory only) Sequential id assigned to distinguish order in which blocks are received.
Definition: chain.h:204
unsigned int nUndoPos
Byte offset within rev?????.dat where this block's undo data is stored.
Definition: chain.h:179
uint256 GetBlockHash() const
Definition: chain.h:268
int64_t GetBlockTime() const
Definition: chain.h:273
CDiskBlockPos GetUndoPos() const
Definition: chain.h:257
bool IsAuxpow() const
Check if the auxpow flag is set in the version.
Definition: chain.h:350
int64_t GetMedianTimePast() const
Definition: chain.h:285
CBlockIndex * pskip
pointer to the index of some further predecessor of this block
Definition: chain.h:167
int64_t GetBlockTimeMax() const
Definition: chain.h:278
unsigned int nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:194
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:186
CBlockIndex(const CBlockHeader &block)
Definition: chain.h:237
@ nMedianTimeSpan
Definition: chain.h:283
CDiskBlockPos GetBlockPos() const
Definition: chain.h:248
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:308
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: chain.cpp:112
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:170
unsigned int nDataPos
Byte offset within blk?????.dat where this block's data is stored.
Definition: chain.h:176
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block.
Definition: chain.h:191
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Definition: chain.h:161
An in-memory indexed chain of blocks.
Definition: chain.h:432
CBlockLocator GetLocator(const CBlockIndex *pindex=NULL) const
Return a CBlockLocator that refers to a block in this chain (by default the tip).
Definition: chain.cpp:52
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or NULL if none.
Definition: chain.h:438
friend bool operator==(const CChain &a, const CChain &b)
Compare two chains efficiently.
Definition: chain.h:455
CBlockIndex * operator[](int nHeight) const
Returns the index entry at a particular height in this chain, or NULL if no such height exists.
Definition: chain.h:448
CBlockIndex * Next(const CBlockIndex *pindex) const
Find the successor of a block in this chain, or NULL if the given index is not found or is the tip.
Definition: chain.h:466
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or NULL if none.
Definition: chain.h:443
int Height() const
Return the maximal height in the chain.
Definition: chain.h:474
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
Definition: chain.cpp:80
std::vector< CBlockIndex * > vChain
Definition: chain.h:434
void SetTip(CBlockIndex *pindex)
Set/initialize a chain with a given tip.
Definition: chain.cpp:40
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:461
CBlockIndex * FindEarliestAtLeast(int64_t nTime) const
Find the earliest block with timestamp equal or greater than the given.
Definition: chain.cpp:91
Used to marshal pointers into hashes for db storage.
Definition: chain.h:368
void SerializationOp(Stream &s, Operation ser_action)
Definition: chain.h:383
std::string ToString() const
Definition: chain.h:420
uint256 hashPrev
Definition: chain.h:370
CDiskBlockIndex()
Definition: chain.h:372
CDiskBlockIndex(const CBlockIndex *pindex)
Definition: chain.h:376
uint256 GetBlockHash() const
Definition: chain.h:407
ADD_SERIALIZE_METHODS
Definition: chain.h:380
int32_t nVersion
Definition: pureheader.h:29
uint32_t nNonce
Definition: pureheader.h:34
int32_t GetBaseVersion() const
Extract the base version (without modifiers and chain ID).
Definition: pureheader.h:88
uint256 hashPrevBlock
Definition: pureheader.h:30
uint32_t nTime
Definition: pureheader.h:32
uint256 GetHash() const
Definition: pureheader.cpp:20
uint256 hashMerkleRoot
Definition: pureheader.h:31
uint32_t nBits
Definition: pureheader.h:33
static const int32_t VERSION_AUXPOW
Definition: pureheader.h:23
256-bit unsigned big integer.
std::string ToString() const
Definition: uint256.cpp:65
256-bit opaque blob.
Definition: uint256.h:123
#define VARINT(obj)
Definition: serialize.h:348
#define READWRITE(obj)
Definition: serialize.h:151
@ SER_GETHASH
Definition: serialize.h:148
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:130
friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b)
Definition: chain.h:94
int nFile
Definition: chain.h:74
void SetNull()
Definition: chain.h:102
CDiskBlockPos(int nFileIn, unsigned int nPosIn)
Definition: chain.h:89
void SerializationOp(Stream &s, Operation ser_action)
Definition: chain.h:80
bool IsNull() const
Definition: chain.h:103
ADD_SERIALIZE_METHODS
Definition: chain.h:77
unsigned int nPos
Definition: chain.h:75
CDiskBlockPos()
Definition: chain.h:85
std::string ToString() const
Definition: chain.h:105
friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b)
Definition: chain.h:98
Parameters that influence chain consensus.
Definition: params.h:39
#define strprintf
Definition: tinyformat.h:1047