Coverage Report

Created: 2026-11-13 17:38

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/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/categories.h>
13
#include <random.h>
14
#include <streams.h>
15
#include <txmempool.h>
16
#include <util/log.h>
17
#include <validation.h>
18
19
#include <unordered_map>
20
21
CBlockHeaderAndShortTxIDs::CBlockHeaderAndShortTxIDs(const CBlock& block, uint64_t nonce)
22
75.9k
    : nonce(nonce),
23
75.9k
      shorttxids(block.vtx.size() - 1),
24
75.9k
      prefilledtxn(1),
25
75.9k
      header(block)
26
75.9k
{
27
75.9k
    FillShortTxIDSelector();
28
    // TODO: Use our mempool prior to block acceptance to predictively fill more than just the coinbase
29
75.9k
    prefilledtxn[0] = {0, block.vtx[0]};
30
126k
    for (size_t i = 1; i < block.vtx.size(); i++) {
31
50.5k
        const CTransaction& tx = *block.vtx[i];
32
50.5k
        shorttxids[i - 1] = GetShortID(tx.GetWitnessHash());
33
50.5k
    }
34
75.9k
}
35
36
void CBlockHeaderAndShortTxIDs::FillShortTxIDSelector() const
37
93.4k
{
38
93.4k
    DataStream stream{};
39
93.4k
    stream << header << nonce;
40
93.4k
    CSHA256 hasher;
41
93.4k
    hasher.Write((unsigned char*)&(*stream.begin()), stream.end() - stream.begin());
42
93.4k
    uint256 shorttxidhash;
43
93.4k
    hasher.Finalize(shorttxidhash.begin());
44
93.4k
    m_hasher.emplace(shorttxidhash.GetUint64(0), shorttxidhash.GetUint64(1));
45
93.4k
}
46
47
uint64_t CBlockHeaderAndShortTxIDs::GetShortID(const Wtxid& wtxid) const
48
115k
{
49
115k
    static_assert(SHORTTXIDS_LENGTH == 6, "shorttxids calculation assumes 6-byte shorttxids");
50
115k
    return (*Assert(m_hasher))(wtxid.ToUint256()) & 0xffffffffffffL;
51
115k
}
52
53
/* Reconstructing a compact block is in the hot-path for block relay,
54
 * so we want to do it as quickly as possible. Because this often
55
 * involves iterating over the entire mempool, we put all the data we
56
 * need (ie the wtxid and a reference to the actual transaction data)
57
 * in a vector and iterate over the vector directly. This allows optimal
58
 * CPU caching behaviour, at a cost of only 40 bytes per transaction.
59
 */
60
ReadStatus PartiallyDownloadedBlock::InitData(const CBlockHeaderAndShortTxIDs& cmpctblock, const std::vector<std::pair<Wtxid, CTransactionRef>>& extra_txn)
61
13.2k
{
62
13.2k
    LogDebug(BCLog::CMPCTBLOCK, "Initializing PartiallyDownloadedBlock for block %s using a cmpctblock of %u bytes\n", cmpctblock.header.GetHash().ToString(), GetSerializeSize(cmpctblock));
63
13.2k
    if (cmpctblock.header.IsNull() || (cmpctblock.shorttxids.empty() && cmpctblock.prefilledtxn.empty()))
64
0
        return READ_STATUS_INVALID;
65
13.2k
    if (cmpctblock.shorttxids.size() + cmpctblock.prefilledtxn.size() > MAX_BLOCK_WEIGHT / MIN_SERIALIZABLE_TRANSACTION_WEIGHT)
66
0
        return READ_STATUS_INVALID;
67
68
13.2k
    if (!header.IsNull() || !txn_available.empty()) return READ_STATUS_INVALID;
69
70
13.2k
    header = cmpctblock.header;
71
13.2k
    txn_available.resize(cmpctblock.BlockTxCount());
72
73
13.2k
    const bool debug_log{util::log::ShouldDebugLog(BCLog::CMPCTBLOCK)};
74
    // Track the prefills which were not already present in the mempool or extrapool.
75
13.2k
    std::map<Wtxid, size_t> leftover_prefills;
76
77
13.2k
    int32_t lastprefilledindex = -1;
78
13.2k
    prefilled_count = cmpctblock.prefilledtxn.size();
79
26.5k
    for (size_t i = 0; i < prefilled_count; i++) {
80
13.2k
        if (cmpctblock.prefilledtxn[i].tx->IsNull())
81
0
            return READ_STATUS_INVALID;
82
83
13.2k
        lastprefilledindex += cmpctblock.prefilledtxn[i].index + 1; //index is a uint16_t, so can't overflow here
84
13.2k
        if (lastprefilledindex > std::numeric_limits<uint16_t>::max())
85
0
            return READ_STATUS_INVALID;
86
13.2k
        if ((uint32_t)lastprefilledindex > cmpctblock.shorttxids.size() + i) {
87
            // If we are inserting a tx at an index greater than our full list of shorttxids
88
            // plus the number of prefilled txn we've inserted, then we have txn for which we
89
            // have neither a prefilled txn or a shorttxid!
90
3
            return READ_STATUS_INVALID;
91
3
        }
92
93
13.2k
        if (debug_log) {
94
13.2k
            const CTransactionRef& tx{cmpctblock.prefilledtxn[i].tx};
95
13.2k
            const size_t tx_size{tx->ComputeTotalSize()};
96
13.2k
            prefilled_size += tx_size;
97
98
13.2k
            leftover_prefills.emplace(tx->GetWitnessHash(), tx_size);
99
13.2k
        }
100
13.2k
        txn_available[lastprefilledindex] = cmpctblock.prefilledtxn[i].tx;
101
13.2k
    }
102
103
104
    // Calculate map of txids -> positions and check mempool to see what we have (or don't)
105
    // Because well-formed cmpctblock messages will have a (relatively) uniform distribution
106
    // of short IDs, any highly-uneven distribution of elements can be safely treated as a
107
    // READ_STATUS_FAILED.
108
13.2k
    std::unordered_map<uint64_t, uint16_t> shorttxids(cmpctblock.shorttxids.size());
109
13.2k
    uint16_t index_offset = 0;
110
26.7k
    for (size_t i = 0; i < cmpctblock.shorttxids.size(); i++) {
111
14.4k
        while (txn_available[i + index_offset])
112
1.01k
            index_offset++;
113
13.4k
        shorttxids[cmpctblock.shorttxids[i]] = i + index_offset;
114
        // To determine the chance that the number of entries in a bucket exceeds N,
115
        // we use the fact that the number of elements in a single bucket is
116
        // binomially distributed (with n = the number of shorttxids S, and p =
117
        // 1 / the number of buckets), that in the worst case the number of buckets is
118
        // equal to S (due to std::unordered_map having a default load factor of 1.0),
119
        // and that the chance for any bucket to exceed N elements is at most
120
        // buckets * (the chance that any given bucket is above N elements).
121
        // Thus: P(max_elements_per_bucket > N) <= S * (1 - cdf(binomial(n=S,p=1/S), N)).
122
        // If we assume blocks of up to 16000, allowing 12 elements per bucket should
123
        // only fail once per ~1 million block transfers (per peer and connection).
124
13.4k
        if (shorttxids.bucket_size(shorttxids.bucket(cmpctblock.shorttxids[i])) > 12)
125
0
            return READ_STATUS_FAILED;
126
13.4k
    }
127
13.2k
    if (shorttxids.size() != cmpctblock.shorttxids.size())
128
0
        return READ_STATUS_FAILED; // Short ID collision
129
130
13.2k
    enum class TxSource : uint8_t { NONE, MEMPOOL, EXTRA, COLLIDED };
131
13.2k
    std::vector<TxSource> tx_source(txn_available.size(), TxSource::NONE);
132
13.2k
    size_t available_count = 0;
133
13.2k
    {
134
13.2k
    LOCK(pool->cs);
135
13.2k
    if (debug_log) {
136
26.5k
        for (auto it{leftover_prefills.begin()}; it != leftover_prefills.end();) {
137
13.2k
            if (pool->GetIter(it->first)) {
138
0
                ++redundant_prefilled_mempool_count;
139
0
                redundant_prefilled_mempool_size += it->second;
140
0
                it = leftover_prefills.erase(it);
141
13.2k
            } else {
142
13.2k
                ++it;
143
13.2k
            }
144
13.2k
        }
145
13.2k
    }
146
147
61.6k
    for (const auto& [wtxid, txit] : pool->txns_randomized) {
148
61.6k
        uint64_t shortid = cmpctblock.GetShortID(wtxid);
149
61.6k
        std::unordered_map<uint64_t, uint16_t>::iterator idit = shorttxids.find(shortid);
150
61.6k
        if (idit != shorttxids.end()) {
151
11.4k
            if (tx_source[idit->second] == TxSource::NONE) {
152
11.4k
                txn_available[idit->second] = txit->GetSharedTx();
153
11.4k
                tx_source[idit->second] = TxSource::MEMPOOL;
154
11.4k
                ++available_count;
155
11.4k
            } else if (tx_source[idit->second] != TxSource::COLLIDED) {
156
                // If we find two mempool txn that match the short id, just request it.
157
                // This should be rare enough that the extra bandwidth doesn't matter,
158
                // but eating a round-trip due to FillBlock failure would be annoying
159
0
                txn_available[idit->second].reset();
160
0
                --available_count;
161
0
                tx_source[idit->second] = TxSource::COLLIDED;
162
0
            }
163
11.4k
        }
164
        // Though ideally we'd continue scanning for the two-txn-match-shortid case,
165
        // the performance win of an early exit here is too good to pass up and worth
166
        // the extra risk.
167
61.6k
        if (available_count == shorttxids.size())
168
387
            break;
169
61.6k
    }
170
13.2k
    }
171
172
15.9k
    for (size_t i = 0; i < extra_txn.size(); i++) {
173
3.36k
        uint64_t shortid = cmpctblock.GetShortID(extra_txn[i].first);
174
3.36k
        std::unordered_map<uint64_t, uint16_t>::iterator idit = shorttxids.find(shortid);
175
3.36k
        if (idit != shorttxids.end()) {
176
308
            if (tx_source[idit->second] == TxSource::NONE) {
177
293
                txn_available[idit->second] = extra_txn[i].second;
178
293
                tx_source[idit->second] = TxSource::EXTRA;
179
293
                ++available_count;
180
293
            } else if (tx_source[idit->second] != TxSource::COLLIDED &&
181
15
                       txn_available[idit->second]->GetWitnessHash() != extra_txn[i].second->GetWitnessHash()) {
182
                // If we find two mempool/extra txn that match the short id, just
183
                // request it.
184
                // This should be rare enough that the extra bandwidth doesn't matter,
185
                // but eating a round-trip due to FillBlock failure would be annoying
186
                // Note that we don't want duplication between extra_txn and mempool to
187
                // trigger this case, so we compare witness hashes first
188
5
                txn_available[idit->second].reset();
189
5
                --available_count;
190
5
                tx_source[idit->second] = TxSource::COLLIDED;
191
5
            }
192
308
        }
193
        // Though ideally we'd continue scanning for the two-txn-match-shortid case,
194
        // the performance win of an early exit here is too good to pass up and worth
195
        // the extra risk.
196
3.36k
        if (available_count == shorttxids.size())
197
647
            break;
198
3.36k
    }
199
200
201
13.2k
    if (debug_log) {
202
14.2k
        for (const auto& [id, tx] : extra_txn) {
203
14.2k
            if (!tx) continue;
204
14.1k
            const auto it{leftover_prefills.find(id)};
205
14.1k
            if (it == leftover_prefills.end()) continue;
206
0
            ++redundant_prefilled_extrapool_count;
207
0
            redundant_prefilled_extrapool_size += it->second;
208
0
            leftover_prefills.erase(it);
209
0
        }
210
211
13.2k
        Assume(txn_available.size() == tx_source.size());
212
40.0k
        for (size_t i = 0; i < txn_available.size(); i++) {
213
26.7k
            switch (tx_source[i]) {
214
11.4k
                case TxSource::MEMPOOL:
215
11.4k
                    ++mempool_count;
216
11.4k
                    Assume(txn_available[i]);
217
11.4k
                    mempool_size += txn_available[i]->ComputeTotalSize();
218
11.4k
                    break;
219
291
                case TxSource::EXTRA:
220
291
                    ++extra_count;
221
291
                    Assume(txn_available[i]);
222
291
                    extra_size += txn_available[i]->ComputeTotalSize();
223
291
                    break;
224
15.0k
                default:
225
15.0k
                    break;
226
26.7k
            }
227
26.7k
        }
228
13.2k
    }
229
230
13.2k
    LogDebug(BCLog::CMPCTBLOCK, "Initialized PartiallyDownloadedBlock for block %s using a cmpctblock of %u bytes\n", cmpctblock.header.GetHash().ToString(), GetSerializeSize(cmpctblock));
231
232
13.2k
    return READ_STATUS_OK;
233
13.2k
}
234
235
bool PartiallyDownloadedBlock::IsTxAvailable(size_t index) const
236
26.7k
{
237
26.7k
    if (header.IsNull()) return false;
238
239
26.7k
    assert(index < txn_available.size());
240
26.7k
    return txn_available[index] != nullptr;
241
26.7k
}
242
243
ReadStatus PartiallyDownloadedBlock::FillBlock(CBlock& block, const std::vector<CTransactionRef>& vtx_missing, bool segwit_active)
244
13.2k
{
245
13.2k
    if (header.IsNull()) return READ_STATUS_INVALID;
246
247
13.2k
    block = header;
248
13.2k
    block.vtx.resize(txn_available.size());
249
250
13.2k
    size_t tx_missing_offset = 0;
251
39.8k
    for (size_t i = 0; i < txn_available.size(); i++) {
252
26.5k
        if (!txn_available[i]) {
253
1.59k
            if (tx_missing_offset >= vtx_missing.size()) {
254
2
                return READ_STATUS_INVALID;
255
2
            }
256
1.59k
            block.vtx[i] = vtx_missing[tx_missing_offset++];
257
25.0k
        } else {
258
25.0k
            block.vtx[i] = std::move(txn_available[i]);
259
25.0k
        }
260
26.5k
    }
261
262
    // Make sure we can't call FillBlock again.
263
13.2k
    header.SetNull();
264
13.2k
    txn_available.clear();
265
266
13.2k
    if (vtx_missing.size() != tx_missing_offset) {
267
0
        return READ_STATUS_INVALID;
268
0
    }
269
270
    // Check for possible mutations early now that we have a seemingly good block
271
13.2k
    IsBlockMutatedFn check_mutated{m_check_block_mutated_mock ? m_check_block_mutated_mock : IsBlockMutated};
272
13.2k
    if (check_mutated(/*block=*/block, /*check_witness_root=*/segwit_active)) {
273
5
        return READ_STATUS_FAILED; // Possible Short ID collision
274
5
    }
275
276
13.2k
    if (util::log::ShouldDebugLog(BCLog::CMPCTBLOCK)) {
277
13.2k
        const uint256 hash{block.GetHash()};
278
13.2k
        uint32_t tx_missing_size{0};
279
13.2k
        for (const auto& tx : vtx_missing) { tx_missing_size += tx->ComputeTotalSize(); }
280
13.2k
        LogDebug(BCLog::CMPCTBLOCK,
281
13.2k
            "Successfully reconstructed block %s with %u txn prefilled (%u bytes), "
282
13.2k
            "%u txn from mempool (%u bytes), "
283
13.2k
            "%u txn from extrapool (%u bytes), "
284
13.2k
            "and %u txn requested (%u bytes)",
285
13.2k
            hash.ToString(),
286
13.2k
            prefilled_count, prefilled_size,
287
13.2k
            mempool_count, mempool_size,
288
13.2k
            extra_count, extra_size,
289
13.2k
            vtx_missing.size(), tx_missing_size);
290
13.2k
        LogDebug(BCLog::CMPCTBLOCK,
291
13.2k
            "Block %s prefill redundancy statistics: "
292
13.2k
            "%u txn (%u bytes) of the prefill were redundant, "
293
13.2k
            "%u txn (%u bytes) were present in the mempool, "
294
13.2k
            "%u txn (%u bytes) were present in the extrapool.",
295
13.2k
            hash.ToString(),
296
13.2k
            redundant_prefilled_mempool_count + redundant_prefilled_extrapool_count,
297
13.2k
            redundant_prefilled_mempool_size + redundant_prefilled_extrapool_size,
298
13.2k
            redundant_prefilled_mempool_count, redundant_prefilled_mempool_size,
299
13.2k
            redundant_prefilled_extrapool_count, redundant_prefilled_extrapool_size);
300
301
13.2k
        if (util::log::ShouldTraceLog(BCLog::CMPCTBLOCK)) {
302
13.2k
            const std::string missing_txids{util::Join(vtx_missing, ", ", [](const auto& tx) { return tx->GetHash().ToString(); })};
303
13.2k
            LogTrace(BCLog::CMPCTBLOCK, "Reconstructed block %s required requesting the following transactions: %s\n", hash.ToString(), missing_txids);
304
13.2k
        }
305
13.2k
    }
306
307
13.2k
    return READ_STATUS_OK;
308
13.2k
}