Bitcoin Core 30.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-2022 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 <tinyformat.h>
8#include <util/check.h>
9#include <util/time.h>
10
11std::string CBlockFileInfo::ToString() const
12{
13 return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, FormatISO8601Date(nTimeFirst), FormatISO8601Date(nTimeLast));
14}
15
16std::string CBlockIndex::ToString() const
17{
18 return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
20}
21
23{
24 CBlockIndex* pindex = &block;
25 vChain.resize(pindex->nHeight + 1);
26 while (pindex && vChain[pindex->nHeight] != pindex) {
27 vChain[pindex->nHeight] = pindex;
28 pindex = pindex->pprev;
29 }
30}
31
32std::vector<uint256> LocatorEntries(const CBlockIndex* index)
33{
34 int step = 1;
35 std::vector<uint256> have;
36 if (index == nullptr) return have;
37
38 have.reserve(32);
39 while (index) {
40 have.emplace_back(index->GetBlockHash());
41 if (index->nHeight == 0) break;
42 // Exponentially larger steps back, plus the genesis block.
43 int height = std::max(index->nHeight - step, 0);
44 // Use skiplist.
45 index = index->GetAncestor(height);
46 if (have.size() > 10) step *= 2;
47 }
48 return have;
49}
50
52{
53 return CBlockLocator{LocatorEntries(index)};
54}
55
56const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const {
57 if (pindex == nullptr) {
58 return nullptr;
59 }
60 if (pindex->nHeight > Height())
61 pindex = pindex->GetAncestor(Height());
62 while (pindex && !Contains(pindex))
63 pindex = pindex->pprev;
64 return pindex;
65}
66
67CBlockIndex* CChain::FindEarliestAtLeast(int64_t nTime, int height) const
68{
69 std::pair<int64_t, int> blockparams = std::make_pair(nTime, height);
70 std::vector<CBlockIndex*>::const_iterator lower = std::lower_bound(vChain.begin(), vChain.end(), blockparams,
71 [](CBlockIndex* pBlock, const std::pair<int64_t, int>& blockparams) -> bool { return pBlock->GetBlockTimeMax() < blockparams.first || pBlock->nHeight < blockparams.second; });
72 return (lower == vChain.end() ? nullptr : *lower);
73}
74
76int static inline InvertLowestOne(int n) { return n & (n - 1); }
77
79int static inline GetSkipHeight(int height) {
80 if (height < 2)
81 return 0;
82
83 // Determine which height to jump back to. Any number strictly lower than height is acceptable,
84 // but the following expression seems to perform well in simulations (max 110 steps to go back
85 // up to 2**18 blocks).
86 return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height);
87}
88
89const CBlockIndex* CBlockIndex::GetAncestor(int height) const
90{
91 if (height > nHeight || height < 0) {
92 return nullptr;
93 }
94
95 const CBlockIndex* pindexWalk = this;
96 int heightWalk = nHeight;
97 while (heightWalk > height) {
98 int heightSkip = GetSkipHeight(heightWalk);
99 int heightSkipPrev = GetSkipHeight(heightWalk - 1);
100 if (pindexWalk->pskip != nullptr &&
101 (heightSkip == height ||
102 (heightSkip > height && !(heightSkipPrev < heightSkip - 2 &&
103 heightSkipPrev >= height)))) {
104 // Only follow pskip if pprev->pskip isn't better than pskip->pprev.
105 pindexWalk = pindexWalk->pskip;
106 heightWalk = heightSkip;
107 } else {
108 assert(pindexWalk->pprev);
109 pindexWalk = pindexWalk->pprev;
110 heightWalk--;
111 }
112 }
113 return pindexWalk;
114}
115
117{
118 return const_cast<CBlockIndex*>(static_cast<const CBlockIndex*>(this)->GetAncestor(height));
119}
120
122{
123 if (pprev)
125}
126
128{
129 arith_uint256 bnTarget;
130 bool fNegative;
131 bool fOverflow;
132 bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow);
133 if (fNegative || fOverflow || bnTarget == 0)
134 return 0;
135 // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
136 // as it's too large for an arith_uint256. However, as 2**256 is at least as large
137 // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
138 // or ~bnTarget / (bnTarget+1) + 1.
139 return (~bnTarget / (bnTarget + 1)) + 1;
140}
141
142int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params)
143{
145 int sign = 1;
146 if (to.nChainWork > from.nChainWork) {
147 r = to.nChainWork - from.nChainWork;
148 } else {
149 r = from.nChainWork - to.nChainWork;
150 sign = -1;
151 }
152 r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip);
153 if (r.bits() > 63) {
154 return sign * std::numeric_limits<int64_t>::max();
155 }
156 return sign * int64_t(r.GetLow64());
157}
158
162 // First rewind to the last common height (the forking point cannot be past one of the two).
163 if (pa->nHeight > pb->nHeight) {
164 pa = pa->GetAncestor(pb->nHeight);
165 } else if (pb->nHeight > pa->nHeight) {
166 pb = pb->GetAncestor(pa->nHeight);
167 }
168 while (pa != pb) {
169 // Jump back until pa and pb have a common "skip" ancestor.
170 while (pa->pskip != pb->pskip) {
171 // This logic relies on the property that equal-height blocks have equal-height skip
172 // pointers.
173 Assume(pa->nHeight == pb->nHeight);
174 Assume(pa->pskip->nHeight == pb->pskip->nHeight);
175 pa = pa->pskip;
176 pb = pb->pskip;
177 }
178 // At this point, pa and pb are different, but have equal pskip. The forking point lies in
179 // between pa/pb on the one end, and pa->pskip/pb->pskip on the other end.
180 pa = pa->pprev;
181 pb = pb->pprev;
182 }
183 return pa;
184}
arith_uint256 GetBlockProof(const CBlockIndex &block)
Definition: chain.cpp:127
std::vector< uint256 > LocatorEntries(const CBlockIndex *index)
Construct a list of hash entries to put in a locator.
Definition: chain.cpp:32
CBlockLocator GetLocator(const CBlockIndex *index)
Get a locator for a block index entry.
Definition: chain.cpp:51
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:142
static int GetSkipHeight(int height)
Compute what height to jump back to with the CBlockIndex::pskip pointer.
Definition: chain.cpp:79
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
Definition: chain.cpp:161
static int InvertLowestOne(int n)
Turn the lowest '1' bit in the binary representation of a number into a '0'.
Definition: chain.cpp:76
#define Assume(val)
Assume is the identity function.
Definition: check.h:118
uint64_t nTimeFirst
earliest time of block in file
Definition: chain.h:55
uint64_t nTimeLast
latest time of block in file
Definition: chain.h:56
std::string ToString() const
Definition: chain.cpp:11
unsigned int nHeightFirst
lowest height of block in file
Definition: chain.h:53
unsigned int nHeightLast
highest height of block in file
Definition: chain.h:54
unsigned int nBlocks
number of blocks stored in file
Definition: chain.h:50
unsigned int nSize
number of used bytes of block file
Definition: chain.h:51
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:141
uint256 hashMerkleRoot
Definition: chain.h:188
std::string ToString() const
Definition: chain.cpp:16
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:147
void BuildSkip()
Build the skiplist pointer for this entry.
Definition: chain.cpp:121
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:165
uint256 GetBlockHash() const
Definition: chain.h:243
uint32_t nBits
Definition: chain.h:190
CBlockIndex * pskip
pointer to the index of some further predecessor of this block
Definition: chain.h:150
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: chain.cpp:116
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:153
void SetTip(CBlockIndex &block)
Set/initialize a chain with a given tip.
Definition: chain.cpp:22
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:67
int Height() const
Return the maximal height in the chain.
Definition: chain.h:462
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
Definition: chain.cpp:56
std::vector< CBlockIndex * > vChain
Definition: chain.h:419
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:447
256-bit unsigned big integer.
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...
std::string ToString() const
Definition: uint256.cpp:21
uint64_t GetLow64() const
unsigned int bits() const
Returns the position of the highest bit set plus one, or zero if the value is zero.
static int sign(const secp256k1_context *ctx, struct signer_secrets *signer_secrets, struct signer *signer, const secp256k1_musig_keyagg_cache *cache, const unsigned char *msg32, unsigned char *sig64)
Definition: musig.c:106
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:124
Parameters that influence chain consensus.
Definition: params.h:84
int64_t nPowTargetSpacing
Definition: params.h:120
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
std::string FormatISO8601Date(int64_t nTime)
Definition: time.cpp:88
assert(!tx.IsCoinBase())