Coverage Report

Created: 2026-04-29 19:21

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/chain.cpp
Line
Count
Source
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
#include <chain.h>
7
#include <tinyformat.h>
8
#include <util/check.h>
9
10
std::string CBlockIndex::ToString() const
11
0
{
12
0
    return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
13
0
                     pprev, nHeight, hashMerkleRoot.ToString(), GetBlockHash().ToString());
14
0
}
15
16
void CChain::SetTip(CBlockIndex& block)
17
818k
{
18
818k
    CBlockIndex* pindex = &block;
19
818k
    vChain.resize(pindex->nHeight + 1);
20
124M
    while (pindex && vChain[pindex->nHeight] != pindex) {
21
123M
        vChain[pindex->nHeight] = pindex;
22
123M
        pindex = pindex->pprev;
23
123M
    }
24
818k
}
25
26
std::vector<uint256> LocatorEntries(const CBlockIndex* index)
27
20.7k
{
28
20.7k
    int step = 1;
29
20.7k
    std::vector<uint256> have;
30
20.7k
    if (index == nullptr) return have;
31
32
20.7k
    have.reserve(32);
33
345k
    while (index) {
34
345k
        have.emplace_back(index->GetBlockHash());
35
345k
        if (index->nHeight == 0) break;
36
        // Exponentially larger steps back, plus the genesis block.
37
325k
        int height = std::max(index->nHeight - step, 0);
38
        // Use skiplist.
39
325k
        index = index->GetAncestor(height);
40
325k
        if (have.size() > 10) step *= 2;
41
325k
    }
42
20.7k
    return have;
43
20.7k
}
44
45
CBlockLocator GetLocator(const CBlockIndex* index)
46
20.7k
{
47
20.7k
    return CBlockLocator{LocatorEntries(index)};
48
20.7k
}
49
50
const CBlockIndex* CChain::FindFork(const CBlockIndex& index) const
51
193k
{
52
193k
    const auto* pindex{&index};
53
193k
    if (pindex->nHeight > Height())
54
97.0k
        pindex = pindex->GetAncestor(Height());
55
218k
    while (pindex && !Contains(*pindex))
56
24.7k
        pindex = pindex->pprev;
57
193k
    return pindex;
58
193k
}
59
60
CBlockIndex* CChain::FindEarliestAtLeast(int64_t nTime, int height) const
61
10.7k
{
62
10.7k
    std::pair<int64_t, int> blockparams = std::make_pair(nTime, height);
63
10.7k
    std::vector<CBlockIndex*>::const_iterator lower = std::lower_bound(vChain.begin(), vChain.end(), blockparams,
64
171k
        [](CBlockIndex* pBlock, const std::pair<int64_t, int>& blockparams) -> bool { return pBlock->GetBlockTimeMax() < blockparams.first || pBlock->nHeight < blockparams.second; });
65
10.7k
    return (lower == vChain.end() ? nullptr : *lower);
66
10.7k
}
67
68
/** Turn the lowest '1' bit in the binary representation of a number into a '0'. */
69
261M
int static inline InvertLowestOne(int n) { return n & (n - 1); }
70
71
/** Compute what height to jump back to with the CBlockIndex::pskip pointer. */
72
174M
int static inline GetSkipHeight(int height) {
73
174M
    if (height < 2)
74
103k
        return 0;
75
76
    // Determine which height to jump back to. Any number strictly lower than height is acceptable,
77
    // but the following expression seems to perform well in simulations (max 110 steps to go back
78
    // up to 2**18 blocks).
79
174M
    return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height);
80
174M
}
81
82
const CBlockIndex* CBlockIndex::GetAncestor(int height) const
83
26.2M
{
84
26.2M
    if (height > nHeight || height < 0) {
85
13.2M
        return nullptr;
86
13.2M
    }
87
88
13.0M
    const CBlockIndex* pindexWalk = this;
89
13.0M
    int heightWalk = nHeight;
90
97.0M
    while (heightWalk > height) {
91
83.9M
        int heightSkip = GetSkipHeight(heightWalk);
92
83.9M
        int heightSkipPrev = GetSkipHeight(heightWalk - 1);
93
83.9M
        if (pindexWalk->pskip != nullptr &&
94
83.9M
            (heightSkip == height ||
95
83.9M
             (heightSkip > height && !(heightSkipPrev < heightSkip - 2 &&
96
41.2M
                                       heightSkipPrev >= height)))) {
97
            // Only follow pskip if pprev->pskip isn't better than pskip->pprev.
98
41.2M
            pindexWalk = pindexWalk->pskip;
99
41.2M
            heightWalk = heightSkip;
100
42.7M
        } else {
101
42.7M
            assert(pindexWalk->pprev);
102
42.7M
            pindexWalk = pindexWalk->pprev;
103
42.7M
            heightWalk--;
104
42.7M
        }
105
83.9M
    }
106
13.0M
    return pindexWalk;
107
13.0M
}
108
109
CBlockIndex* CBlockIndex::GetAncestor(int height)
110
17.3M
{
111
17.3M
    return const_cast<CBlockIndex*>(static_cast<const CBlockIndex*>(this)->GetAncestor(height));
112
17.3M
}
113
114
void CBlockIndex::BuildSkip()
115
6.63M
{
116
6.63M
    if (pprev)
117
6.63M
        pskip = pprev->GetAncestor(GetSkipHeight(nHeight));
118
6.63M
}
119
120
arith_uint256 GetBitsProof(uint32_t bits)
121
1.01M
{
122
1.01M
    arith_uint256 bnTarget;
123
1.01M
    bool fNegative;
124
1.01M
    bool fOverflow;
125
1.01M
    bnTarget.SetCompact(bits, &fNegative, &fOverflow);
126
1.01M
    if (fNegative || fOverflow || bnTarget == 0)
127
24
        return 0;
128
    // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
129
    // as it's too large for an arith_uint256. However, as 2**256 is at least as large
130
    // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
131
    // or ~bnTarget / (bnTarget+1) + 1.
132
1.01M
    return (~bnTarget / (bnTarget + 1)) + 1;
133
1.01M
}
134
135
int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params)
136
1.37k
{
137
1.37k
    arith_uint256 r;
138
1.37k
    int sign = 1;
139
1.37k
    if (to.nChainWork > from.nChainWork) {
140
872
        r = to.nChainWork - from.nChainWork;
141
872
    } else {
142
501
        r = from.nChainWork - to.nChainWork;
143
501
        sign = -1;
144
501
    }
145
1.37k
    r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip);
146
1.37k
    if (r.bits() > 63) {
147
0
        return sign * std::numeric_limits<int64_t>::max();
148
0
    }
149
1.37k
    return sign * int64_t(r.GetLow64());
150
1.37k
}
151
152
/** Find the last common ancestor two blocks have.
153
 *  Both pa and pb must be non-nullptr. */
154
231k
const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb) {
155
    // First rewind to the last common height (the forking point cannot be past one of the two).
156
231k
    if (pa->nHeight > pb->nHeight) {
157
88.6k
        pa = pa->GetAncestor(pb->nHeight);
158
142k
    } else if (pb->nHeight > pa->nHeight) {
159
51.1k
        pb = pb->GetAncestor(pa->nHeight);
160
51.1k
    }
161
839k
    while (pa != pb) {
162
        // Jump back until pa and pb have a common "skip" ancestor.
163
1.12M
        while (pa->pskip != pb->pskip) {
164
            // This logic relies on the property that equal-height blocks have equal-height skip
165
            // pointers.
166
520k
            Assume(pa->nHeight == pb->nHeight);
167
520k
            Assume(pa->pskip->nHeight == pb->pskip->nHeight);
168
520k
            pa = pa->pskip;
169
520k
            pb = pb->pskip;
170
520k
        }
171
        // At this point, pa and pb are different, but have equal pskip. The forking point lies in
172
        // between pa/pb on the one end, and pa->pskip/pb->pskip on the other end.
173
607k
        pa = pa->pprev;
174
607k
        pb = pb->pprev;
175
607k
    }
176
231k
    return pa;
177
231k
}