Bitcoin Core  31.0.0
P2P Digital Currency
chain.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-present 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;
39 static constexpr int32_t SEQ_ID_BEST_CHAIN_FROM_DISK = 0;
40 static constexpr int32_t SEQ_ID_INIT_FROM_DISK = 1;
41 
42 enum BlockStatus : uint32_t {
45 
48 
52 
62 
66 
70 
74 
78 
81 
83 
85 };
87 
94 {
95 public:
97  const uint256* phashBlock{nullptr};
98 
100  CBlockIndex* pprev{nullptr};
101 
103  CBlockIndex* pskip{nullptr};
104 
106  int nHeight{0};
107 
109  int nFile GUARDED_BY(::cs_main){0};
110 
112  unsigned int nDataPos GUARDED_BY(::cs_main){0};
113 
115  unsigned int nUndoPos GUARDED_BY(::cs_main){0};
116 
119 
123  unsigned int nTx{0};
124 
129  uint64_t m_chain_tx_count{0};
130 
137  uint32_t nStatus GUARDED_BY(::cs_main){0};
138 
140  int32_t nVersion{0};
142  uint32_t nTime{0};
143  uint32_t nBits{0};
144  uint32_t nNonce{0};
145 
150 
152  unsigned int nTimeMax{0};
153 
154  explicit CBlockIndex(const CBlockHeader& block)
155  : nVersion{block.nVersion},
156  hashMerkleRoot{block.hashMerkleRoot},
157  nTime{block.nTime},
158  nBits{block.nBits},
159  nNonce{block.nNonce}
160  {
161  }
162 
164  {
167  if (nStatus & BLOCK_HAVE_DATA) {
168  ret.nFile = nFile;
169  ret.nPos = nDataPos;
170  }
171  return ret;
172  }
173 
175  {
178  if (nStatus & BLOCK_HAVE_UNDO) {
179  ret.nFile = nFile;
180  ret.nPos = nUndoPos;
181  }
182  return ret;
183  }
184 
186  {
187  CBlockHeader block;
188  block.nVersion = nVersion;
189  if (pprev)
190  block.hashPrevBlock = pprev->GetBlockHash();
192  block.nTime = nTime;
193  block.nBits = nBits;
194  block.nNonce = nNonce;
195  return block;
196  }
197 
199  {
200  assert(phashBlock != nullptr);
201  return *phashBlock;
202  }
203 
214  bool HaveNumChainTxs() const { return m_chain_tx_count != 0; }
215 
217  {
218  return NodeSeconds{std::chrono::seconds{nTime}};
219  }
220 
221  int64_t GetBlockTime() const
222  {
223  return (int64_t)nTime;
224  }
225 
226  int64_t GetBlockTimeMax() const
227  {
228  return (int64_t)nTimeMax;
229  }
230 
231  static constexpr int nMedianTimeSpan = 11;
232 
233  int64_t GetMedianTimePast() const
234  {
235  int64_t pmedian[nMedianTimeSpan];
236  int64_t* pbegin = &pmedian[nMedianTimeSpan];
237  int64_t* pend = &pmedian[nMedianTimeSpan];
238 
239  const CBlockIndex* pindex = this;
240  for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
241  *(--pbegin) = pindex->GetBlockTime();
242 
243  std::sort(pbegin, pend);
244  return pbegin[(pend - pbegin) / 2];
245  }
246 
247  std::string ToString() const;
248 
250  bool IsValid(enum BlockStatus nUpTo) const
252  {
254  assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
255  if (nStatus & BLOCK_FAILED_VALID)
256  return false;
257  return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
258  }
259 
263  {
265  assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
266  if (nStatus & BLOCK_FAILED_VALID) return false;
267 
268  if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
269  nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
270  return true;
271  }
272  return false;
273  }
274 
276  void BuildSkip();
277 
279  CBlockIndex* GetAncestor(int height);
280  const CBlockIndex* GetAncestor(int height) const;
281 
282  CBlockIndex() = default;
283  ~CBlockIndex() = default;
284 
285 protected:
295  CBlockIndex(const CBlockIndex&) = default;
296  CBlockIndex& operator=(const CBlockIndex&) = delete;
297  CBlockIndex(CBlockIndex&&) = delete;
298  CBlockIndex& operator=(CBlockIndex&&) = delete;
299 };
300 
302 arith_uint256 GetBitsProof(uint32_t bits);
303 
305 inline arith_uint256 GetBlockProof(const CBlockIndex& block) { return GetBitsProof(block.nBits); }
306 
308 inline arith_uint256 GetBlockProof(const CBlockHeader& header) { return GetBitsProof(header.nBits); }
309 
311 int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params&);
313 const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb);
314 
315 
318 {
325  static constexpr int DUMMY_VERSION = 259900;
326 
327 public:
329 
331  {
332  hashPrev = uint256();
333  }
334 
335  explicit CDiskBlockIndex(const CBlockIndex* pindex) : CBlockIndex(*pindex)
336  {
337  hashPrev = (pprev ? pprev->GetBlockHash() : uint256());
338  }
339 
341  {
342  LOCK(::cs_main);
343  int _nVersion = DUMMY_VERSION;
345 
347  READWRITE(VARINT(obj.nStatus));
348  READWRITE(VARINT(obj.nTx));
350  if (obj.nStatus & BLOCK_HAVE_DATA) READWRITE(VARINT(obj.nDataPos));
351  if (obj.nStatus & BLOCK_HAVE_UNDO) READWRITE(VARINT(obj.nUndoPos));
352 
353  // block header
354  READWRITE(obj.nVersion);
355  READWRITE(obj.hashPrev);
356  READWRITE(obj.hashMerkleRoot);
357  READWRITE(obj.nTime);
358  READWRITE(obj.nBits);
359  READWRITE(obj.nNonce);
360  }
361 
363  {
364  CBlockHeader block;
365  block.nVersion = nVersion;
366  block.hashPrevBlock = hashPrev;
368  block.nTime = nTime;
369  block.nBits = nBits;
370  block.nNonce = nNonce;
371  return block.GetHash();
372  }
373 
374  uint256 GetBlockHash() = delete;
375  std::string ToString() = delete;
376 };
377 
379 class CChain
380 {
381 private:
382  std::vector<CBlockIndex*> vChain;
383 
384 public:
385  CChain() = default;
386  CChain(const CChain&) = delete;
387  CChain& operator=(const CChain&) = delete;
388 
391  {
392  return vChain.size() > 0 ? vChain[0] : nullptr;
393  }
394 
396  CBlockIndex* Tip() const
397  {
398  return vChain.size() > 0 ? vChain[vChain.size() - 1] : nullptr;
399  }
400 
403  {
404  if (nHeight < 0 || nHeight >= (int)vChain.size())
405  return nullptr;
406  return vChain[nHeight];
407  }
408 
410  bool Contains(const CBlockIndex* pindex) const
411  {
412  return (*this)[pindex->nHeight] == pindex;
413  }
414 
416  CBlockIndex* Next(const CBlockIndex* pindex) const
417  {
418  if (Contains(pindex))
419  return (*this)[pindex->nHeight + 1];
420  else
421  return nullptr;
422  }
423 
425  int Height() const
426  {
427  return int(vChain.size()) - 1;
428  }
429 
431  bool IsTipRecent(const arith_uint256& min_chain_work, std::chrono::seconds max_tip_age) const EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
432  {
433  const auto tip{Tip()};
434  return tip &&
435  tip->nChainWork >= min_chain_work &&
436  tip->Time() >= Now<NodeSeconds>() - max_tip_age;
437  }
438 
440  void SetTip(CBlockIndex& block);
441 
443  const CBlockIndex* FindFork(const CBlockIndex* pindex) const;
444 
446  CBlockIndex* FindEarliestAtLeast(int64_t nTime, int height) const;
447 };
448 
450 CBlockLocator GetLocator(const CBlockIndex* index);
451 
453 std::vector<uint256> LocatorEntries(const CBlockIndex* index);
454 
455 #endif // BITCOIN_CHAIN_H
uint32_t nNonce
Definition: block.h:35
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:118
#define VARINT(obj)
Definition: serialize.h:491
int ret
std::string ToString() const
Definition: chain.cpp:10
int32_t nSequenceId
(memory only) Sequential id assigned to distinguish order in which blocks are received.
Definition: chain.h:149
bool HaveNumChainTxs() const
Check whether this block and all previous blocks back to the genesis block or an assumeutxo snapshot ...
Definition: chain.h:214
CBlockIndex * pskip
pointer to the index of some further predecessor of this block
Definition: chain.h:103
std::vector< CBlockIndex * > vChain
Definition: chain.h:382
AssertLockHeld(pool.cs)
int64_t GetBlockTime() const
Definition: chain.h:221
assert(!tx.IsCoinBase())
NodeSeconds Time() const
Definition: chain.h:216
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:116
Unused flag that was previously set when descending from failed block.
Definition: chain.h:80
Reserved (was BLOCK_VALID_HEADER).
Definition: chain.h:47
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:100
CBlockLocator GetLocator(const CBlockIndex *index)
Get a locator for a block index entry.
Definition: chain.cpp:45
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the forking point between two chain tips.
Definition: chain.cpp:155
An in-memory indexed chain of blocks.
Definition: chain.h:379
int nFile GUARDED_BY(::cs_main)
Which # file this block is stored in (blk?????.dat)
Definition: chain.h:109
All parent headers found, difficulty matches, timestamp >= median previous.
Definition: chain.h:51
CBlockHeader GetBlockHeader() const
Definition: chain.h:185
int Height() const
Return the maximal height in the chain.
Definition: chain.h:425
Unused flag that was previously set on assumeutxo snapshot blocks and their ancestors before they wer...
Definition: chain.h:84
stage after last reached validness failed
Definition: chain.h:79
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid...
Definition: chain.h:61
static constexpr int32_t SEQ_ID_BEST_CHAIN_FROM_DISK
Init values for CBlockIndex nSequenceId when loaded from disk.
Definition: chain.h:39
~CBlockIndex()=default
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
Definition: chain.h:390
CChain()=default
uint32_t nTime
Definition: chain.h:142
undo data available in rev*.dat
Definition: chain.h:76
Unused.
Definition: chain.h:44
SERIALIZE_METHODS(CDiskBlockIndex, obj)
Definition: chain.h:340
void SetTip(CBlockIndex &block)
Set/initialize a chain with a given tip.
Definition: chain.cpp:16
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
uint32_t nTime
Definition: block.h:33
CBlockIndex()=default
static constexpr int nMedianTimeSpan
Definition: chain.h:231
uint256 GetBlockHash() const
Definition: chain.h:198
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:61
#define VARINT_MODE(obj, mode)
Definition: serialize.h:490
arith_uint256 GetBlockProof(const CBlockIndex &block)
Compute how much work a block index entry corresponds to.
Definition: chain.h:305
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends...
Definition: chain.h:65
unsigned int nTimeMax
(memory only) Maximum nTime in the chain up to and including this block.
Definition: chain.h:152
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:402
Scripts & signatures ok.
Definition: chain.h:69
uint256 hashMerkleRoot
Definition: block.h:32
std::string ToString()=delete
uint32_t nNonce
Definition: chain.h:144
arith_uint256 GetBitsProof(uint32_t bits)
Compute how much work an nBits value corresponds to.
Definition: chain.cpp:121
uint64_t m_chain_tx_count
(memory only) Number of transactions in the chain up to and including this block. ...
Definition: chain.h:129
#define LOCK(cs)
Definition: sync.h:258
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:410
CBlockIndex(const CBlockHeader &block)
Definition: chain.h:154
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:416
uint256 hashPrevBlock
Definition: block.h:31
std::vector< uint256 > LocatorEntries(const CBlockIndex *index)
Construct a list of hash entries to put in a locator.
Definition: chain.cpp:26
int64_t GetBlockTimeMax() const
Definition: chain.h:226
static constexpr int DUMMY_VERSION
Historically CBlockLocator&#39;s version field has been written to disk streams as the client version...
Definition: chain.h:325
CDiskBlockIndex()
Definition: chain.h:330
uint256 hashMerkleRoot
Definition: chain.h:141
CChain & operator=(const CChain &)=delete
void BuildSkip()
Build the skiplist pointer for this entry.
Definition: chain.cpp:115
Used to marshal pointers into hashes for db storage.
Definition: chain.h:317
Parameters that influence chain consensus.
Definition: params.h:84
unsigned int nHeight
256-bit unsigned big integer.
int64_t GetMedianTimePast() const
Definition: chain.h:233
block data in blk*.dat was received with a witness-enforcing client
Definition: chain.h:82
FlatFilePos GetUndoPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: chain.h:174
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 nDataPos GUARDED_BY(::cs_main)
Byte offset within blk?????.dat where this block&#39;s data is stored.
Definition: chain.h:112
uint32_t nStatus GUARDED_BY(::cs_main)
Verification status of this block.
Definition: chain.h:137
uint256 GetHash() const
Definition: block.cpp:15
int32_t nVersion
block header
Definition: chain.h:140
256-bit opaque blob.
Definition: uint256.h:195
bool IsTipRecent(const arith_uint256 &min_chain_work, std::chrono::seconds max_tip_age) const EXCLUSIVE_LOCKS_REQUIRED(
Check whether this chain&#39;s tip exists, has enough work, and is recent.
Definition: chain.h:431
uint256 ConstructBlockHash() const
Definition: chain.h:362
uint256 hashPrev
Definition: chain.h:328
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:51
unsigned int nUndoPos GUARDED_BY(::cs_main)
Byte offset within rev?????.dat where this block&#39;s undo data is stored.
Definition: chain.h:115
CDiskBlockIndex(const CBlockIndex *pindex)
Definition: chain.h:335
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:93
static constexpr int32_t SEQ_ID_INIT_FROM_DISK
Definition: chain.h:40
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:396
bool RaiseValidity(enum BlockStatus nUpTo) EXCLUSIVE_LOCKS_REQUIRED(
Raise the validity level of this block index entry.
Definition: chain.h:262
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
Definition: time.h:25
BlockStatus
Definition: chain.h:42
bool IsValid(enum BlockStatus nUpTo) const EXCLUSIVE_LOCKS_REQUIRED(
Check whether this block index entry is valid up to the passed validity level.
Definition: chain.h:250
All validity bits.
Definition: chain.h:72
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
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:106
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: chain.h:163
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: chain.cpp:110
full block available in blk*.dat
Definition: chain.h:75
#define READWRITE(...)
Definition: serialize.h:145
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: cs_main.cpp:8
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
Definition: chain.cpp:50
int32_t nVersion
Definition: block.h:30
uint32_t nBits
Definition: chain.h:143
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:123
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:26
uint32_t nBits
Definition: block.h:34
uint256 GetBlockHash()=delete
CBlockIndex & operator=(const CBlockIndex &)=delete
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Definition: chain.h:97