fuzz coverage

Coverage Report

Created: 2026-04-24 13:48

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/bitcoin/src/blockencodings.cpp
Line
Count
Source
1
// Copyright (c) 2016-present The Bitcoin Core developers
2
// Distributed under the MIT software license, see the accompanying
3
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5
#include <blockencodings.h>
6
#include <chainparams.h>
7
#include <common/system.h>
8
#include <consensus/consensus.h>
9
#include <consensus/validation.h>
10
#include <crypto/sha256.h>
11
#include <crypto/siphash.h>
12
#include <logging.h>
13
#include <random.h>
14
#include <streams.h>
15
#include <txmempool.h>
16
#include <validation.h>
17
18
#include <unordered_map>
19
20
CBlockHeaderAndShortTxIDs::CBlockHeaderAndShortTxIDs(const CBlock& block, uint64_t nonce)
21
4.28M
    : nonce(nonce),
22
4.28M
      shorttxids(block.vtx.size() - 1),
23
4.28M
      prefilledtxn(1),
24
4.28M
      header(block)
25
4.28M
{
26
4.28M
    FillShortTxIDSelector();
27
    // TODO: Use our mempool prior to block acceptance to predictively fill more than just the coinbase
28
4.28M
    prefilledtxn[0] = {0, block.vtx[0]};
29
32.3M
    for (size_t i = 1; i < block.vtx.size(); 
i++28.1M
) {
30
28.1M
        const CTransaction& tx = *block.vtx[i];
31
28.1M
        shorttxids[i - 1] = GetShortID(tx.GetWitnessHash());
32
28.1M
    }
33
4.28M
}
34
35
void CBlockHeaderAndShortTxIDs::FillShortTxIDSelector() const
36
7.79M
{
37
7.79M
    DataStream stream{};
38
7.79M
    stream << header << nonce;
39
7.79M
    CSHA256 hasher;
40
7.79M
    hasher.Write((unsigned char*)&(*stream.begin()), stream.end() - stream.begin());
41
7.79M
    uint256 shorttxidhash;
42
7.79M
    hasher.Finalize(shorttxidhash.begin());
43
7.79M
    m_hasher.emplace(shorttxidhash.GetUint64(0), shorttxidhash.GetUint64(1));
44
7.79M
}
45
46
uint64_t CBlockHeaderAndShortTxIDs::GetShortID(const Wtxid& wtxid) const
47
34.5M
{
48
34.5M
    static_assert(SHORTTXIDS_LENGTH == 6, "shorttxids calculation assumes 6-byte shorttxids");
49
34.5M
    return (*Assert(m_hasher))(wtxid.ToUint256()) & 0xffffffffffffL;
Line
Count
Source
113
34.5M
#define Assert(val) inline_assertion_check<true>(val, std::source_location::current(), #val)
50
34.5M
}
51
52
/* Reconstructing a compact block is in the hot-path for block relay,
53
 * so we want to do it as quickly as possible. Because this often
54
 * involves iterating over the entire mempool, we put all the data we
55
 * need (ie the wtxid and a reference to the actual transaction data)
56
 * in a vector and iterate over the vector directly. This allows optimal
57
 * CPU caching behaviour, at a cost of only 40 bytes per transaction.
58
 */
59
ReadStatus PartiallyDownloadedBlock::InitData(const CBlockHeaderAndShortTxIDs& cmpctblock, const std::vector<std::pair<Wtxid, CTransactionRef>>& extra_txn)
60
1.11M
{
61
1.11M
    LogDebug(BCLog::CMPCTBLOCK, "Initializing PartiallyDownloadedBlock for block %s using a cmpctblock of %u bytes\n", cmpctblock.header.GetHash().ToString(), GetSerializeSize(cmpctblock));
Line
Count
Source
117
1.11M
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, BCLog::Level::Debug, __VA_ARGS__)
Line
Count
Source
108
1.11M
    do {                                                               \
109
1.11M
        if (util::log::ShouldLog((category), (level))) {               \
110
0
            bool rate_limit{level >= BCLog::Level::Info};              \
111
0
            Assume(!rate_limit); /*Only called with the levels below*/ \
Line
Count
Source
125
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
112
0
            LogPrintLevel_(category, level, rate_limit, __VA_ARGS__);  \
Line
Count
Source
91
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
113
0
        }                                                              \
114
1.11M
    } while (0)
62
1.11M
    if (cmpctblock.header.IsNull() || (cmpctblock.shorttxids.empty() && 
cmpctblock.prefilledtxn.empty()416k
))
63
0
        return READ_STATUS_INVALID;
64
1.11M
    if (cmpctblock.shorttxids.size() + cmpctblock.prefilledtxn.size() > MAX_BLOCK_WEIGHT / MIN_SERIALIZABLE_TRANSACTION_WEIGHT)
65
0
        return READ_STATUS_INVALID;
66
67
1.11M
    if (!header.IsNull() || !txn_available.empty()) 
return READ_STATUS_INVALID0
;
68
69
1.11M
    header = cmpctblock.header;
70
1.11M
    txn_available.resize(cmpctblock.BlockTxCount());
71
72
1.11M
    int32_t lastprefilledindex = -1;
73
2.23M
    for (size_t i = 0; i < cmpctblock.prefilledtxn.size(); 
i++1.12M
) {
74
1.12M
        if (cmpctblock.prefilledtxn[i].tx->IsNull())
75
0
            return READ_STATUS_INVALID;
76
77
1.12M
        lastprefilledindex += cmpctblock.prefilledtxn[i].index + 1; //index is a uint16_t, so can't overflow here
78
1.12M
        if (lastprefilledindex > std::numeric_limits<uint16_t>::max())
79
0
            return READ_STATUS_INVALID;
80
1.12M
        if ((uint32_t)lastprefilledindex > cmpctblock.shorttxids.size() + i) {
81
            // If we are inserting a tx at an index greater than our full list of shorttxids
82
            // plus the number of prefilled txn we've inserted, then we have txn for which we
83
            // have neither a prefilled txn or a shorttxid!
84
0
            return READ_STATUS_INVALID;
85
0
        }
86
1.12M
        txn_available[lastprefilledindex] = cmpctblock.prefilledtxn[i].tx;
87
1.12M
    }
88
1.11M
    prefilled_count = cmpctblock.prefilledtxn.size();
89
90
    // Calculate map of txids -> positions and check mempool to see what we have (or don't)
91
    // Because well-formed cmpctblock messages will have a (relatively) uniform distribution
92
    // of short IDs, any highly-uneven distribution of elements can be safely treated as a
93
    // READ_STATUS_FAILED.
94
1.11M
    std::unordered_map<uint64_t, uint16_t> shorttxids(cmpctblock.shorttxids.size());
95
1.11M
    uint16_t index_offset = 0;
96
6.78M
    for (size_t i = 0; i < cmpctblock.shorttxids.size(); 
i++5.67M
) {
97
6.36M
        while (txn_available[i + index_offset])
98
686k
            index_offset++;
99
5.67M
        shorttxids[cmpctblock.shorttxids[i]] = i + index_offset;
100
        // To determine the chance that the number of entries in a bucket exceeds N,
101
        // we use the fact that the number of elements in a single bucket is
102
        // binomially distributed (with n = the number of shorttxids S, and p =
103
        // 1 / the number of buckets), that in the worst case the number of buckets is
104
        // equal to S (due to std::unordered_map having a default load factor of 1.0),
105
        // and that the chance for any bucket to exceed N elements is at most
106
        // buckets * (the chance that any given bucket is above N elements).
107
        // Thus: P(max_elements_per_bucket > N) <= S * (1 - cdf(binomial(n=S,p=1/S), N)).
108
        // If we assume blocks of up to 16000, allowing 12 elements per bucket should
109
        // only fail once per ~1 million block transfers (per peer and connection).
110
5.67M
        if (shorttxids.bucket_size(shorttxids.bucket(cmpctblock.shorttxids[i])) > 12)
111
0
            return READ_STATUS_FAILED;
112
5.67M
    }
113
    // TODO: in the shortid-collision case, we should instead request both transactions
114
    // which collided. Falling back to full-block-request here is overkill.
115
1.11M
    if (shorttxids.size() != cmpctblock.shorttxids.size())
116
526k
        return READ_STATUS_FAILED; // Short ID collision
117
118
584k
    std::vector<bool> have_txn(txn_available.size());
119
584k
    {
120
584k
    LOCK(pool->cs);
Line
Count
Source
268
584k
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
584k
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
584k
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
584k
#define PASTE(x, y) x ## y
121
673k
    for (const auto& [wtxid, txit] : pool->txns_randomized) {
122
673k
        uint64_t shortid = cmpctblock.GetShortID(wtxid);
123
673k
        std::unordered_map<uint64_t, uint16_t>::iterator idit = shorttxids.find(shortid);
124
673k
        if (idit != shorttxids.end()) {
125
272k
            if (!have_txn[idit->second]) {
126
272k
                txn_available[idit->second] = txit->GetSharedTx();
127
272k
                have_txn[idit->second]  = true;
128
272k
                mempool_count++;
129
272k
            } else {
130
                // If we find two mempool txn that match the short id, just request it.
131
                // This should be rare enough that the extra bandwidth doesn't matter,
132
                // but eating a round-trip due to FillBlock failure would be annoying
133
0
                if (txn_available[idit->second]) {
134
0
                    txn_available[idit->second].reset();
135
0
                    mempool_count--;
136
0
                }
137
0
            }
138
272k
        }
139
        // Though ideally we'd continue scanning for the two-txn-match-shortid case,
140
        // the performance win of an early exit here is too good to pass up and worth
141
        // the extra risk.
142
673k
        if (mempool_count == shorttxids.size())
143
266k
            break;
144
673k
    }
145
584k
    }
146
147
6.05M
    for (size_t i = 0; i < extra_txn.size(); 
i++5.47M
) {
148
5.73M
        uint64_t shortid = cmpctblock.GetShortID(extra_txn[i].first);
149
5.73M
        std::unordered_map<uint64_t, uint16_t>::iterator idit = shorttxids.find(shortid);
150
5.73M
        if (idit != shorttxids.end()) {
151
51.2k
            if (!have_txn[idit->second]) {
152
39.3k
                txn_available[idit->second] = extra_txn[i].second;
153
39.3k
                have_txn[idit->second]  = true;
154
39.3k
                mempool_count++;
155
39.3k
                extra_count++;
156
39.3k
            } else {
157
                // If we find two mempool/extra txn that match the short id, just
158
                // request it.
159
                // This should be rare enough that the extra bandwidth doesn't matter,
160
                // but eating a round-trip due to FillBlock failure would be annoying
161
                // Note that we don't want duplication between extra_txn and mempool to
162
                // trigger this case, so we compare witness hashes first
163
11.9k
                if (txn_available[idit->second] &&
164
11.9k
                        txn_available[idit->second]->GetWitnessHash() != extra_txn[i].second->GetWitnessHash()) {
165
0
                    txn_available[idit->second].reset();
166
0
                    mempool_count--;
167
0
                    extra_count--;
168
0
                }
169
11.9k
            }
170
51.2k
        }
171
        // Though ideally we'd continue scanning for the two-txn-match-shortid case,
172
        // the performance win of an early exit here is too good to pass up and worth
173
        // the extra risk.
174
5.73M
        if (mempool_count == shorttxids.size())
175
264k
            break;
176
5.73M
    }
177
178
584k
    LogDebug(BCLog::CMPCTBLOCK, "Initialized PartiallyDownloadedBlock for block %s using a cmpctblock of %u bytes\n", cmpctblock.header.GetHash().ToString(), GetSerializeSize(cmpctblock));
Line
Count
Source
117
584k
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, BCLog::Level::Debug, __VA_ARGS__)
Line
Count
Source
108
584k
    do {                                                               \
109
584k
        if (util::log::ShouldLog((category), (level))) {               \
110
0
            bool rate_limit{level >= BCLog::Level::Info};              \
111
0
            Assume(!rate_limit); /*Only called with the levels below*/ \
Line
Count
Source
125
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
112
0
            LogPrintLevel_(category, level, rate_limit, __VA_ARGS__);  \
Line
Count
Source
91
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
113
0
        }                                                              \
114
584k
    } while (0)
179
180
584k
    return READ_STATUS_OK;
181
1.11M
}
182
183
bool PartiallyDownloadedBlock::IsTxAvailable(size_t index) const
184
1.19M
{
185
1.19M
    if (header.IsNull()) 
return false0
;
186
187
1.19M
    assert(index < txn_available.size());
188
1.19M
    return txn_available[index] != nullptr;
189
1.19M
}
190
191
ReadStatus PartiallyDownloadedBlock::FillBlock(CBlock& block, const std::vector<CTransactionRef>& vtx_missing, bool segwit_active)
192
480k
{
193
480k
    if (header.IsNull()) 
return READ_STATUS_INVALID0
;
194
195
480k
    block = header;
196
480k
    block.vtx.resize(txn_available.size());
197
198
480k
    size_t tx_missing_offset = 0;
199
1.23M
    for (size_t i = 0; i < txn_available.size(); 
i++751k
) {
200
778k
        if (!txn_available[i]) {
201
48.4k
            if (tx_missing_offset >= vtx_missing.size()) {
202
27.1k
                return READ_STATUS_INVALID;
203
27.1k
            }
204
21.3k
            block.vtx[i] = vtx_missing[tx_missing_offset++];
205
730k
        } else {
206
730k
            block.vtx[i] = std::move(txn_available[i]);
207
730k
        }
208
778k
    }
209
210
    // Make sure we can't call FillBlock again.
211
453k
    header.SetNull();
212
453k
    txn_available.clear();
213
214
453k
    if (vtx_missing.size() != tx_missing_offset) {
215
141
        return READ_STATUS_INVALID;
216
141
    }
217
218
    // Check for possible mutations early now that we have a seemingly good block
219
453k
    IsBlockMutatedFn check_mutated{m_check_block_mutated_mock ? 
m_check_block_mutated_mock0
: IsBlockMutated};
220
453k
    if (check_mutated(/*block=*/block, /*check_witness_root=*/segwit_active)) {
221
829
        return READ_STATUS_FAILED; // Possible Short ID collision
222
829
    }
223
224
452k
    if (LogAcceptCategory(BCLog::CMPCTBLOCK, BCLog::Level::Debug)) {
225
0
        const uint256 hash{block.GetHash()};
226
0
        uint32_t tx_missing_size{0};
227
0
        for (const auto& tx : vtx_missing) tx_missing_size += tx->ComputeTotalSize();
228
0
        LogDebug(BCLog::CMPCTBLOCK, "Successfully reconstructed block %s with %u txn prefilled, %u txn from mempool (incl at least %u from extra pool) and %u txn (%u bytes) requested\n", hash.ToString(), prefilled_count, mempool_count, extra_count, vtx_missing.size(), tx_missing_size);
Line
Count
Source
117
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, BCLog::Level::Debug, __VA_ARGS__)
Line
Count
Source
108
0
    do {                                                               \
109
0
        if (util::log::ShouldLog((category), (level))) {               \
110
0
            bool rate_limit{level >= BCLog::Level::Info};              \
111
0
            Assume(!rate_limit); /*Only called with the levels below*/ \
Line
Count
Source
125
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
112
0
            LogPrintLevel_(category, level, rate_limit, __VA_ARGS__);  \
Line
Count
Source
91
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
113
0
        }                                                              \
114
0
    } while (0)
229
0
        if (vtx_missing.size() < 5) {
230
0
            for (const auto& tx : vtx_missing) {
231
0
                LogDebug(BCLog::CMPCTBLOCK, "Reconstructed block %s required tx %s\n", hash.ToString(), tx->GetHash().ToString());
Line
Count
Source
117
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, BCLog::Level::Debug, __VA_ARGS__)
Line
Count
Source
108
0
    do {                                                               \
109
0
        if (util::log::ShouldLog((category), (level))) {               \
110
0
            bool rate_limit{level >= BCLog::Level::Info};              \
111
0
            Assume(!rate_limit); /*Only called with the levels below*/ \
Line
Count
Source
125
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
112
0
            LogPrintLevel_(category, level, rate_limit, __VA_ARGS__);  \
Line
Count
Source
91
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
113
0
        }                                                              \
114
0
    } while (0)
232
0
            }
233
0
        }
234
0
    }
235
236
452k
    return READ_STATUS_OK;
237
453k
}