Bitcoin Core  22.99.0
P2P Digital Currency
chain.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2019 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 #include <chain.h>
7 #include <util/time.h>
8 
9 std::string CBlockFileInfo::ToString() const
10 {
11  return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, FormatISO8601Date(nTimeFirst), FormatISO8601Date(nTimeLast));
12 }
13 
14 void CChain::SetTip(CBlockIndex *pindex) {
15  if (pindex == nullptr) {
16  vChain.clear();
17  return;
18  }
19  vChain.resize(pindex->nHeight + 1);
20  while (pindex && vChain[pindex->nHeight] != pindex) {
21  vChain[pindex->nHeight] = pindex;
22  pindex = pindex->pprev;
23  }
24 }
25 
27  int nStep = 1;
28  std::vector<uint256> vHave;
29  vHave.reserve(32);
30 
31  if (!pindex)
32  pindex = Tip();
33  while (pindex) {
34  vHave.push_back(pindex->GetBlockHash());
35  // Stop when we have added the genesis block.
36  if (pindex->nHeight == 0)
37  break;
38  // Exponentially larger steps back, plus the genesis block.
39  int nHeight = std::max(pindex->nHeight - nStep, 0);
40  if (Contains(pindex)) {
41  // Use O(1) CChain index if possible.
42  pindex = (*this)[nHeight];
43  } else {
44  // Otherwise, use O(log n) skiplist.
45  pindex = pindex->GetAncestor(nHeight);
46  }
47  if (vHave.size() > 10)
48  nStep *= 2;
49  }
50 
51  return CBlockLocator(vHave);
52 }
53 
54 const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const {
55  if (pindex == nullptr) {
56  return nullptr;
57  }
58  if (pindex->nHeight > Height())
59  pindex = pindex->GetAncestor(Height());
60  while (pindex && !Contains(pindex))
61  pindex = pindex->pprev;
62  return pindex;
63 }
64 
65 CBlockIndex* CChain::FindEarliestAtLeast(int64_t nTime, int height) const
66 {
67  std::pair<int64_t, int> blockparams = std::make_pair(nTime, height);
68  std::vector<CBlockIndex*>::const_iterator lower = std::lower_bound(vChain.begin(), vChain.end(), blockparams,
69  [](CBlockIndex* pBlock, const std::pair<int64_t, int>& blockparams) -> bool { return pBlock->GetBlockTimeMax() < blockparams.first || pBlock->nHeight < blockparams.second; });
70  return (lower == vChain.end() ? nullptr : *lower);
71 }
72 
74 int static inline InvertLowestOne(int n) { return n & (n - 1); }
75 
77 int static inline GetSkipHeight(int height) {
78  if (height < 2)
79  return 0;
80 
81  // Determine which height to jump back to. Any number strictly lower than height is acceptable,
82  // but the following expression seems to perform well in simulations (max 110 steps to go back
83  // up to 2**18 blocks).
84  return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height);
85 }
86 
87 const CBlockIndex* CBlockIndex::GetAncestor(int height) const
88 {
89  if (height > nHeight || height < 0) {
90  return nullptr;
91  }
92 
93  const CBlockIndex* pindexWalk = this;
94  int heightWalk = nHeight;
95  while (heightWalk > height) {
96  int heightSkip = GetSkipHeight(heightWalk);
97  int heightSkipPrev = GetSkipHeight(heightWalk - 1);
98  if (pindexWalk->pskip != nullptr &&
99  (heightSkip == height ||
100  (heightSkip > height && !(heightSkipPrev < heightSkip - 2 &&
101  heightSkipPrev >= height)))) {
102  // Only follow pskip if pprev->pskip isn't better than pskip->pprev.
103  pindexWalk = pindexWalk->pskip;
104  heightWalk = heightSkip;
105  } else {
106  assert(pindexWalk->pprev);
107  pindexWalk = pindexWalk->pprev;
108  heightWalk--;
109  }
110  }
111  return pindexWalk;
112 }
113 
115 {
116  return const_cast<CBlockIndex*>(static_cast<const CBlockIndex*>(this)->GetAncestor(height));
117 }
118 
120 {
121  if (pprev)
123 }
124 
126 {
127  arith_uint256 bnTarget;
128  bool fNegative;
129  bool fOverflow;
130  bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow);
131  if (fNegative || fOverflow || bnTarget == 0)
132  return 0;
133  // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
134  // as it's too large for an arith_uint256. However, as 2**256 is at least as large
135  // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
136  // or ~bnTarget / (bnTarget+1) + 1.
137  return (~bnTarget / (bnTarget + 1)) + 1;
138 }
139 
140 int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params)
141 {
142  arith_uint256 r;
143  int sign = 1;
144  if (to.nChainWork > from.nChainWork) {
145  r = to.nChainWork - from.nChainWork;
146  } else {
147  r = from.nChainWork - to.nChainWork;
148  sign = -1;
149  }
150  r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip);
151  if (r.bits() > 63) {
152  return sign * std::numeric_limits<int64_t>::max();
153  }
154  return sign * r.GetLow64();
155 }
156 
160  if (pa->nHeight > pb->nHeight) {
161  pa = pa->GetAncestor(pb->nHeight);
162  } else if (pb->nHeight > pa->nHeight) {
163  pb = pb->GetAncestor(pa->nHeight);
164  }
165 
166  while (pa != pb && pa && pb) {
167  pa = pa->pprev;
168  pb = pb->pprev;
169  }
170 
171  // Eventually all chain branches meet at the genesis block.
172  assert(pa == pb);
173  return pa;
174 }
FormatISO8601Date
std::string FormatISO8601Date(int64_t nTime)
Definition: time.cpp:145
CBlockFileInfo::nTimeFirst
uint64_t nTimeFirst
earliest time of block in file
Definition: chain.h:48
CBlockIndex::GetAncestor
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: chain.cpp:114
assert
assert(!tx.IsCoinBase())
CBlockIndex::nTime
uint32_t nTime
Definition: chain.h:203
nHeight
unsigned int nHeight
Definition: mempool_eviction.cpp:14
CBlockIndex::nBits
uint32_t nBits
Definition: chain.h:204
arith_uint256
256-bit unsigned big integer.
Definition: arith_uint256.h:250
CBlockIndex::pprev
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:155
CBlockIndex::nHeight
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:161
base_uint::bits
unsigned int bits() const
Returns the position of the highest bit set plus one, or zero if the value is zero.
Definition: arith_uint256.cpp:171
CBlockIndex::nChainWork
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:173
LastCommonAncestor
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
Definition: chain.cpp:159
CBlockIndex::pskip
CBlockIndex * pskip
pointer to the index of some further predecessor of this block
Definition: chain.h:158
CChain::Tip
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:434
CChain::FindFork
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
Definition: chain.cpp:54
Consensus::Params::nPowTargetSpacing
int64_t nPowTargetSpacing
Definition: params.h:103
CChain::FindEarliestAtLeast
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:65
Consensus::Params
Parameters that influence chain consensus.
Definition: params.h:70
CBlockFileInfo::nTimeLast
uint64_t nTimeLast
latest time of block in file
Definition: chain.h:49
CBlockFileInfo::nBlocks
unsigned int nBlocks
number of blocks stored in file
Definition: chain.h:43
CBlockFileInfo::nHeightFirst
unsigned int nHeightFirst
lowest height of block in file
Definition: chain.h:46
base_uint::GetLow64
uint64_t GetLow64() const
Definition: arith_uint256.h:242
CChain::GetLocator
CBlockLocator GetLocator(const CBlockIndex *pindex=nullptr) const
Return a CBlockLocator that refers to a block in this chain (by default the tip).
Definition: chain.cpp:26
time.h
CBlockFileInfo::nHeightLast
unsigned int nHeightLast
highest height of block in file
Definition: chain.h:47
chain.h
CChain::SetTip
void SetTip(CBlockIndex *pindex)
Set/initialize a chain with a given tip.
Definition: chain.cpp:14
CBlockIndex::GetBlockHash
uint256 GetBlockHash() const
Definition: chain.h:259
CChain::Height
int Height() const
Return the maximal height in the chain.
Definition: chain.h:463
InvertLowestOne
static int InvertLowestOne(int n)
Turn the lowest '1' bit in the binary representation of a number into a '0'.
Definition: chain.cpp:74
strprintf
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
arith_uint256::SetCompact
arith_uint256 & SetCompact(uint32_t nCompact, bool *pfNegative=nullptr, bool *pfOverflow=nullptr)
The "compact" format is a representation of a whole number N using an unsigned 32bit number similar t...
Definition: arith_uint256.cpp:203
CBlockIndex::BuildSkip
void BuildSkip()
Build the skiplist pointer for this entry.
Definition: chain.cpp:119
CChain::vChain
std::vector< CBlockIndex * > vChain
Definition: chain.h:420
CChain::Contains
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:448
GetBlockProof
arith_uint256 GetBlockProof(const CBlockIndex &block)
Definition: chain.cpp:125
CBlockFileInfo::ToString
std::string ToString() const
Definition: chain.cpp:9
CBlockLocator
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:114
GetSkipHeight
static int GetSkipHeight(int height)
Compute what height to jump back to with the CBlockIndex::pskip pointer.
Definition: chain.cpp:77
CBlockIndex
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:148
CBlockFileInfo::nSize
unsigned int nSize
number of used bytes of block file
Definition: chain.h:44
GetBlockProofEquivalentTime
int64_t GetBlockProofEquivalentTime(const CBlockIndex &to, const CBlockIndex &from, const CBlockIndex &tip, const Consensus::Params &params)
Return the time it would take to redo the work difference between from and to, assuming the current h...
Definition: chain.cpp:140