Coverage Report

Created: 2026-07-14 18:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/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 <random.h>
13
#include <streams.h>
14
#include <txmempool.h>
15
#include <util/log.h>
16
#include <validation.h>
17
18
#include <unordered_map>
19
20
CBlockHeaderAndShortTxIDs::CBlockHeaderAndShortTxIDs(const CBlock& block, uint64_t nonce)
21
22.1k
    : nonce(nonce),
22
22.1k
      shorttxids(block.vtx.size() - 1),
23
22.1k
      prefilledtxn(1),
24
22.1k
      header(block)
25
22.1k
{
26
22.1k
    FillShortTxIDSelector();
27
    // TODO: Use our mempool prior to block acceptance to predictively fill more than just the coinbase
28
22.1k
    prefilledtxn[0] = {0, block.vtx[0]};
29
138k
    for (size_t i = 1; i < block.vtx.size(); i++) {
  Branch (29:24): [True: 116k, False: 22.1k]
30
116k
        const CTransaction& tx = *block.vtx[i];
31
116k
        shorttxids[i - 1] = GetShortID(tx.GetWitnessHash());
32
116k
    }
33
22.1k
}
34
35
void CBlockHeaderAndShortTxIDs::FillShortTxIDSelector() const
36
163k
{
37
163k
    DataStream stream{};
38
163k
    stream << header << nonce;
39
163k
    CSHA256 hasher;
40
163k
    hasher.Write((unsigned char*)&(*stream.begin()), stream.end() - stream.begin());
41
163k
    uint256 shorttxidhash;
42
163k
    hasher.Finalize(shorttxidhash.begin());
43
163k
    m_hasher.emplace(shorttxidhash.GetUint64(0), shorttxidhash.GetUint64(1));
44
163k
}
45
46
uint64_t CBlockHeaderAndShortTxIDs::GetShortID(const Wtxid& wtxid) const
47
598k
{
48
598k
    static_assert(SHORTTXIDS_LENGTH == 6, "shorttxids calculation assumes 6-byte shorttxids");
49
598k
    return (*Assert(m_hasher))(wtxid.ToUint256()) & 0xffffffffffffL;
50
598k
}
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
16.2k
{
61
16.2k
    LogDebug(BCLog::CMPCTBLOCK, "Initializing PartiallyDownloadedBlock for block %s using a cmpctblock of %u bytes\n", cmpctblock.header.GetHash().ToString(), GetSerializeSize(cmpctblock));
62
16.2k
    if (cmpctblock.header.IsNull() || (cmpctblock.shorttxids.empty() && cmpctblock.prefilledtxn.empty()))
  Branch (62:9): [True: 18.4E, False: 16.2k]
  Branch (62:40): [True: 5.98k, False: 10.2k]
  Branch (62:73): [True: 0, False: 5.98k]
63
0
        return READ_STATUS_INVALID;
64
16.2k
    if (cmpctblock.shorttxids.size() + cmpctblock.prefilledtxn.size() > MAX_BLOCK_WEIGHT / MIN_SERIALIZABLE_TRANSACTION_WEIGHT)
  Branch (64:9): [True: 0, False: 16.2k]
65
0
        return READ_STATUS_INVALID;
66
67
16.2k
    if (!header.IsNull() || !txn_available.empty()) return READ_STATUS_INVALID;
  Branch (67:9): [True: 18.4E, False: 16.2k]
  Branch (67:29): [True: 0, False: 16.2k]
68
69
16.2k
    header = cmpctblock.header;
70
16.2k
    txn_available.resize(cmpctblock.BlockTxCount());
71
72
16.2k
    int32_t lastprefilledindex = -1;
73
103k
    for (size_t i = 0; i < cmpctblock.prefilledtxn.size(); i++) {
  Branch (73:24): [True: 87.0k, False: 16.2k]
74
87.0k
        if (cmpctblock.prefilledtxn[i].tx->IsNull())
  Branch (74:13): [True: 0, False: 87.0k]
75
0
            return READ_STATUS_INVALID;
76
77
87.0k
        lastprefilledindex += cmpctblock.prefilledtxn[i].index + 1; //index is a uint16_t, so can't overflow here
78
87.0k
        if (lastprefilledindex > std::numeric_limits<uint16_t>::max())
  Branch (78:13): [True: 0, False: 87.0k]
79
0
            return READ_STATUS_INVALID;
80
87.0k
        if ((uint32_t)lastprefilledindex > cmpctblock.shorttxids.size() + i) {
  Branch (80:13): [True: 0, False: 87.0k]
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
87.0k
        txn_available[lastprefilledindex] = cmpctblock.prefilledtxn[i].tx;
87
87.0k
    }
88
16.2k
    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
16.2k
    std::unordered_map<uint64_t, uint16_t> shorttxids(cmpctblock.shorttxids.size());
95
16.2k
    uint16_t index_offset = 0;
96
282k
    for (size_t i = 0; i < cmpctblock.shorttxids.size(); i++) {
  Branch (96:24): [True: 266k, False: 16.2k]
97
341k
        while (txn_available[i + index_offset])
  Branch (97:16): [True: 75.5k, False: 266k]
98
75.5k
            index_offset++;
99
266k
        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
266k
        if (shorttxids.bucket_size(shorttxids.bucket(cmpctblock.shorttxids[i])) > 12)
  Branch (110:13): [True: 0, False: 266k]
111
0
            return READ_STATUS_FAILED;
112
266k
    }
113
16.2k
    if (shorttxids.size() != cmpctblock.shorttxids.size())
  Branch (113:9): [True: 3.37k, False: 12.8k]
114
3.37k
        return READ_STATUS_FAILED; // Short ID collision
115
116
12.8k
    std::vector<bool> have_txn(txn_available.size());
117
12.8k
    {
118
12.8k
    LOCK(pool->cs);
119
39.5k
    for (const auto& [wtxid, txit] : pool->txns_randomized) {
  Branch (119:36): [True: 39.5k, False: 10.2k]
120
39.5k
        uint64_t shortid = cmpctblock.GetShortID(wtxid);
121
39.5k
        std::unordered_map<uint64_t, uint16_t>::iterator idit = shorttxids.find(shortid);
122
39.5k
        if (idit != shorttxids.end()) {
  Branch (122:13): [True: 4.80k, False: 34.7k]
123
4.80k
            if (!have_txn[idit->second]) {
  Branch (123:17): [True: 4.80k, False: 0]
124
4.80k
                txn_available[idit->second] = txit->GetSharedTx();
125
4.80k
                have_txn[idit->second]  = true;
126
4.80k
                mempool_count++;
127
4.80k
            } else {
128
                // If we find two mempool txn that match the short id, just request it.
129
                // This should be rare enough that the extra bandwidth doesn't matter,
130
                // but eating a round-trip due to FillBlock failure would be annoying
131
0
                if (txn_available[idit->second]) {
  Branch (131:21): [True: 0, False: 0]
132
0
                    txn_available[idit->second].reset();
133
0
                    mempool_count--;
134
0
                }
135
0
            }
136
4.80k
        }
137
        // Though ideally we'd continue scanning for the two-txn-match-shortid case,
138
        // the performance win of an early exit here is too good to pass up and worth
139
        // the extra risk.
140
39.5k
        if (mempool_count == shorttxids.size())
  Branch (140:13): [True: 2.59k, False: 36.9k]
141
2.59k
            break;
142
39.5k
    }
143
12.8k
    }
144
145
450k
    for (size_t i = 0; i < extra_txn.size(); i++) {
  Branch (145:24): [True: 442k, False: 7.74k]
146
442k
        uint64_t shortid = cmpctblock.GetShortID(extra_txn[i].first);
147
442k
        std::unordered_map<uint64_t, uint16_t>::iterator idit = shorttxids.find(shortid);
148
442k
        if (idit != shorttxids.end()) {
  Branch (148:13): [True: 18.1k, False: 424k]
149
18.1k
            if (!have_txn[idit->second]) {
  Branch (149:17): [True: 17.2k, False: 918]
150
17.2k
                txn_available[idit->second] = extra_txn[i].second;
151
17.2k
                have_txn[idit->second]  = true;
152
17.2k
                mempool_count++;
153
17.2k
                extra_count++;
154
17.2k
            } else {
155
                // If we find two mempool/extra txn that match the short id, just
156
                // 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
                // Note that we don't want duplication between extra_txn and mempool to
160
                // trigger this case, so we compare witness hashes first
161
918
                if (txn_available[idit->second] &&
  Branch (161:21): [True: 918, False: 0]
162
918
                        txn_available[idit->second]->GetWitnessHash() != extra_txn[i].second->GetWitnessHash()) {
  Branch (162:25): [True: 0, False: 918]
163
0
                    txn_available[idit->second].reset();
164
0
                    mempool_count--;
165
0
                    extra_count--;
166
0
                }
167
918
            }
168
18.1k
        }
169
        // Though ideally we'd continue scanning for the two-txn-match-shortid case,
170
        // the performance win of an early exit here is too good to pass up and worth
171
        // the extra risk.
172
442k
        if (mempool_count == shorttxids.size())
  Branch (172:13): [True: 5.10k, False: 437k]
173
5.10k
            break;
174
442k
    }
175
176
12.8k
    LogDebug(BCLog::CMPCTBLOCK, "Initialized PartiallyDownloadedBlock for block %s using a cmpctblock of %u bytes\n", cmpctblock.header.GetHash().ToString(), GetSerializeSize(cmpctblock));
177
178
12.8k
    return READ_STATUS_OK;
179
16.2k
}
180
181
bool PartiallyDownloadedBlock::IsTxAvailable(size_t index) const
182
79.8k
{
183
79.8k
    if (header.IsNull()) return false;
  Branch (183:9): [True: 0, False: 79.8k]
184
185
79.8k
    assert(index < txn_available.size());
  Branch (185:5): [True: 79.8k, False: 0]
186
79.8k
    return txn_available[index] != nullptr;
187
79.8k
}
188
189
ReadStatus PartiallyDownloadedBlock::FillBlock(CBlock& block, const std::vector<CTransactionRef>& vtx_missing, bool segwit_active)
190
9.02k
{
191
9.02k
    if (header.IsNull()) return READ_STATUS_INVALID;
  Branch (191:9): [True: 0, False: 9.02k]
192
193
9.02k
    block = header;
194
9.02k
    block.vtx.resize(txn_available.size());
195
196
9.02k
    size_t tx_missing_offset = 0;
197
34.5k
    for (size_t i = 0; i < txn_available.size(); i++) {
  Branch (197:24): [True: 25.8k, False: 8.71k]
198
25.8k
        if (!txn_available[i]) {
  Branch (198:13): [True: 2.18k, False: 23.6k]
199
2.18k
            if (tx_missing_offset >= vtx_missing.size()) {
  Branch (199:17): [True: 308, False: 1.88k]
200
308
                return READ_STATUS_INVALID;
201
308
            }
202
1.88k
            block.vtx[i] = vtx_missing[tx_missing_offset++];
203
23.6k
        } else {
204
23.6k
            block.vtx[i] = std::move(txn_available[i]);
205
23.6k
        }
206
25.8k
    }
207
208
    // Make sure we can't call FillBlock again.
209
8.71k
    header.SetNull();
210
8.71k
    txn_available.clear();
211
212
8.71k
    if (vtx_missing.size() != tx_missing_offset) {
  Branch (212:9): [True: 11, False: 8.70k]
213
11
        return READ_STATUS_INVALID;
214
11
    }
215
216
    // Check for possible mutations early now that we have a seemingly good block
217
8.70k
    IsBlockMutatedFn check_mutated{m_check_block_mutated_mock ? m_check_block_mutated_mock : IsBlockMutated};
  Branch (217:36): [True: 0, False: 8.70k]
218
8.70k
    if (check_mutated(/*block=*/block, /*check_witness_root=*/segwit_active)) {
  Branch (218:9): [True: 311, False: 8.39k]
219
311
        return READ_STATUS_FAILED; // Possible Short ID collision
220
311
    }
221
222
8.39k
    if (util::log::ShouldDebugLog(BCLog::CMPCTBLOCK)) {
  Branch (222:9): [True: 8.39k, False: 0]
223
8.39k
        const uint256 hash{block.GetHash()};
224
8.39k
        uint32_t tx_missing_size{0};
225
8.39k
        for (const auto& tx : vtx_missing) tx_missing_size += tx->ComputeTotalSize();
  Branch (225:29): [True: 914, False: 8.39k]
226
8.39k
        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);
227
8.39k
        if (vtx_missing.size() < 5) {
  Branch (227:13): [True: 8.34k, False: 43]
228
8.34k
            for (const auto& tx : vtx_missing) {
  Branch (228:33): [True: 231, False: 8.34k]
229
231
                LogDebug(BCLog::CMPCTBLOCK, "Reconstructed block %s required tx %s\n", hash.ToString(), tx->GetHash().ToString());
230
231
            }
231
8.34k
        }
232
8.39k
    }
233
234
8.39k
    return READ_STATUS_OK;
235
8.70k
}