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