Coverage Report

Created: 2026-11-13 17:38

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/merkleblock.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 <merkleblock.h>
7
8
#include <consensus/consensus.h>
9
#include <hash.h>
10
#include <util/overflow.h>
11
12
13
std::vector<unsigned char> BitsToBytes(const std::vector<bool>& bits)
14
187
{
15
187
    std::vector<unsigned char> ret(CeilDiv(bits.size(), 8u));
16
77.6k
    for (unsigned int p = 0; p < bits.size(); p++) {
17
77.4k
        ret[p / 8] |= bits[p] << (p % 8);
18
77.4k
    }
19
187
    return ret;
20
187
}
21
22
std::vector<bool> BytesToBits(const std::vector<unsigned char>& bytes)
23
198
{
24
198
    std::vector<bool> ret(bytes.size() * 8);
25
78.5k
    for (unsigned int p = 0; p < ret.size(); p++) {
26
78.3k
        ret[p] = (bytes[p / 8] & (1 << (p % 8))) != 0;
27
78.3k
    }
28
198
    return ret;
29
198
}
30
31
CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter* filter, const std::set<Txid>* txids)
32
31
{
33
31
    header = static_cast<const CBlockHeader&>(block);
34
35
31
    std::vector<bool> vMatch;
36
31
    std::vector<Txid> vHashes;
37
38
31
    vMatch.reserve(block.vtx.size());
39
31
    vHashes.reserve(block.vtx.size());
40
41
153
    for (unsigned int i = 0; i < block.vtx.size(); i++)
42
122
    {
43
122
        const Txid& hash{block.vtx[i]->GetHash()};
44
122
        if (txids && txids->contains(hash)) {
45
21
            vMatch.push_back(true);
46
101
        } else if (filter && filter->IsRelevantAndUpdate(*block.vtx[i])) {
47
22
            vMatch.push_back(true);
48
22
            vMatchedTxn.emplace_back(i, hash);
49
79
        } else {
50
79
            vMatch.push_back(false);
51
79
        }
52
122
        vHashes.push_back(hash);
53
122
    }
54
55
31
    txn = CPartialMerkleTree(vHashes, vMatch);
56
31
}
57
58
// NOLINTNEXTLINE(misc-no-recursion)
59
143k
uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<Txid> &vTxid) {
60
    //we can never have zero txs in a merkle block, we always need the coinbase tx
61
    //if we do not have this assert, we can hit a memory access violation when indexing into vTxid
62
143k
    assert(vTxid.size() != 0);
63
143k
    if (height == 0) {
64
        // hash at height 0 is the txids themselves
65
90.9k
        return vTxid[pos].ToUint256();
66
90.9k
    } else {
67
        // calculate left hash
68
52.3k
        uint256 left = CalcHash(height-1, pos*2, vTxid), right;
69
        // calculate right hash if not beyond the end of the array - copy left hash otherwise
70
52.3k
        if (pos*2+1 < CalcTreeWidth(height-1))
71
52.1k
            right = CalcHash(height-1, pos*2+1, vTxid);
72
248
        else
73
248
            right = left;
74
        // combine subhashes
75
52.3k
        return Hash(left, right);
76
52.3k
    }
77
143k
}
78
79
// NOLINTNEXTLINE(misc-no-recursion)
80
77.5k
void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<Txid> &vTxid, const std::vector<bool> &vMatch) {
81
    // determine whether this node is the parent of at least one matched txid
82
77.5k
    bool fParentOfMatch = false;
83
943k
    for (unsigned int p = pos << height; p < (pos+1) << height && p < nTransactions; p++)
84
866k
        fParentOfMatch |= vMatch[p];
85
    // store as flag bit
86
77.5k
    vBits.push_back(fParentOfMatch);
87
77.5k
    if (height==0 || !fParentOfMatch) {
88
        // if at height 0, or nothing interesting below, store hash and stop
89
38.8k
        vHash.push_back(CalcHash(height, pos, vTxid));
90
38.8k
    } else {
91
        // otherwise, don't store any hash, but descend into the subtrees
92
38.7k
        TraverseAndBuild(height-1, pos*2, vTxid, vMatch);
93
38.7k
        if (pos*2+1 < CalcTreeWidth(height-1))
94
38.6k
            TraverseAndBuild(height-1, pos*2+1, vTxid, vMatch);
95
38.7k
    }
96
77.5k
}
97
98
// NOLINTNEXTLINE(misc-no-recursion)
99
387k
uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<Txid> &vMatch, std::vector<unsigned int> &vnIndex) {
100
387k
    if (nBitsUsed >= vBits.size()) {
101
        // overflowed the bits array - failure
102
3
        fBad = true;
103
3
        return uint256();
104
3
    }
105
387k
    bool fParentOfMatch = vBits[nBitsUsed++];
106
387k
    if (height==0 || !fParentOfMatch) {
107
        // if at height 0, or nothing interesting below, use stored hash and do not descend
108
193k
        if (nHashUsed >= vHash.size()) {
109
            // overflowed the hash array - failure
110
1
            fBad = true;
111
1
            return uint256();
112
1
        }
113
193k
        const uint256 &hash = vHash[nHashUsed++];
114
193k
        if (height==0 && fParentOfMatch) { // in case of height 0, we have a matched txid
115
97.4k
            vMatch.push_back(Txid::FromUint256(hash));
116
97.4k
            vnIndex.push_back(pos);
117
97.4k
        }
118
193k
        return hash;
119
193k
    } else {
120
        // otherwise, descend into the subtrees to extract matched txids and hashes
121
193k
        uint256 left = TraverseAndExtract(height-1, pos*2, nBitsUsed, nHashUsed, vMatch, vnIndex), right;
122
193k
        if (pos*2+1 < CalcTreeWidth(height-1)) {
123
192k
            right = TraverseAndExtract(height-1, pos*2+1, nBitsUsed, nHashUsed, vMatch, vnIndex);
124
192k
            if (right == left) {
125
                // The left and right branches should never be identical, as the transaction
126
                // hashes covered by them must each be unique.
127
1
                fBad = true;
128
1
            }
129
192k
        } else {
130
566
            right = left;
131
566
        }
132
        // and combine them before returning
133
193k
        return Hash(left, right);
134
193k
    }
135
387k
}
136
137
200
CPartialMerkleTree::CPartialMerkleTree(const std::vector<Txid> &vTxid, const std::vector<bool> &vMatch) : nTransactions(vTxid.size()), fBad(false) {
138
    // reset state
139
200
    vBits.clear();
140
200
    vHash.clear();
141
142
    // calculate height of tree
143
200
    int nHeight = 0;
144
1.36k
    while (CalcTreeWidth(nHeight) > 1)
145
1.16k
        nHeight++;
146
147
    // traverse the partial tree
148
200
    TraverseAndBuild(nHeight, 0, vTxid, vMatch);
149
200
}
150
151
236
CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {}
152
153
882
uint256 CPartialMerkleTree::ExtractMatches(std::vector<Txid> &vMatch, std::vector<unsigned int> &vnIndex) {
154
882
    vMatch.clear();
155
    // An empty set will not work
156
882
    if (nTransactions == 0)
157
1
        return uint256();
158
    // check for excessively high numbers of transactions
159
881
    if (nTransactions > MAX_BLOCK_WEIGHT / MIN_TRANSACTION_WEIGHT)
160
1
        return uint256();
161
    // there can never be more hashes provided than one for every txid
162
880
    if (vHash.size() > nTransactions)
163
1
        return uint256();
164
    // there must be at least one bit per node in the partial tree, and at least one node per hash
165
879
    if (vBits.size() < vHash.size())
166
1
        return uint256();
167
    // calculate height of tree
168
878
    int nHeight = 0;
169
6.49k
    while (CalcTreeWidth(nHeight) > 1)
170
5.61k
        nHeight++;
171
    // traverse the partial tree
172
878
    unsigned int nBitsUsed = 0, nHashUsed = 0;
173
878
    uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch, vnIndex);
174
    // verify that no problems occurred during the tree traversal
175
878
    if (fBad)
176
3
        return uint256();
177
    // verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence)
178
875
    if (CeilDiv(nBitsUsed, 8u) != CeilDiv(vBits.size(), 8u))
179
1
        return uint256();
180
    // verify that all hashes were consumed
181
874
    if (nHashUsed != vHash.size())
182
1
        return uint256();
183
873
    return hashMerkleRoot;
184
874
}