Coverage Report

Created: 2026-07-01 15:07

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/bitcoin/src/test/fuzz/util.cpp
Line
Count
Source
1
// Copyright (c) 2021-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 <consensus/amount.h>
6
#include <pubkey.h>
7
#include <test/fuzz/util.h>
8
#include <test/util/script.h>
9
#include <util/check.h>
10
#include <util/overflow.h>
11
#include <util/rbf.h>
12
#include <util/time.h>
13
14
#include <memory>
15
16
std::vector<uint8_t> ConstructPubKeyBytes(FuzzedDataProvider& fuzzed_data_provider, std::span<const uint8_t> byte_data, const bool compressed) noexcept
17
3.32k
{
18
3.32k
    uint8_t pk_type;
19
3.32k
    if (compressed) {
  Branch (19:9): [True: 1.74k, False: 1.57k]
20
1.74k
        pk_type = fuzzed_data_provider.PickValueInArray({0x02, 0x03});
21
1.74k
    } else {
22
1.57k
        pk_type = fuzzed_data_provider.PickValueInArray({0x04, 0x06, 0x07});
23
1.57k
    }
24
3.32k
    std::vector<uint8_t> pk_data{byte_data.begin(), byte_data.begin() + (compressed ? CPubKey::COMPRESSED_SIZE : CPubKey::SIZE)};
  Branch (24:74): [True: 1.74k, False: 1.57k]
25
3.32k
    pk_data[0] = pk_type;
26
3.32k
    return pk_data;
27
3.32k
}
28
29
CAmount ConsumeMoney(FuzzedDataProvider& fuzzed_data_provider, const std::optional<CAmount>& max) noexcept
30
0
{
31
0
    return fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(0, max.value_or(MAX_MONEY));
32
0
}
33
34
NodeSeconds ConsumeTime(FuzzedDataProvider& fuzzed_data_provider, const std::optional<int64_t>& min, const std::optional<int64_t>& max) noexcept
35
0
{
36
    // Avoid t=0 (1970-01-01T00:00:00Z) since SetMockTime(0) disables mocktime.
37
0
    static const int64_t time_min{ParseISO8601DateTime("2000-01-01T00:00:01Z").value()};
38
0
    static const int64_t time_max{ParseISO8601DateTime("2100-12-31T23:59:59Z").value()};
39
0
    return NodeSeconds{ConsumeDuration<std::chrono::seconds>(fuzzed_data_provider, min.value_or(time_min) * 1s, max.value_or(time_max) * 1s)};
40
0
}
41
42
CMutableTransaction ConsumeTransaction(FuzzedDataProvider& fuzzed_data_provider, const std::optional<std::vector<Txid>>& prevout_txids, const int max_num_in, const int max_num_out) noexcept
43
910
{
44
910
    CMutableTransaction tx_mut;
45
910
    const auto p2wsh_op_true = fuzzed_data_provider.ConsumeBool();
46
910
    tx_mut.version = fuzzed_data_provider.ConsumeBool() ?
  Branch (46:22): [True: 735, False: 175]
47
735
                          CTransaction::CURRENT_VERSION :
48
910
                          fuzzed_data_provider.ConsumeIntegral<uint32_t>();
49
910
    tx_mut.nLockTime = fuzzed_data_provider.ConsumeIntegral<uint32_t>();
50
910
    const auto num_in = fuzzed_data_provider.ConsumeIntegralInRange<int>(0, max_num_in);
51
910
    const auto num_out = fuzzed_data_provider.ConsumeIntegralInRange<int>(0, max_num_out);
52
2.95k
    for (int i = 0; i < num_in; ++i) {
  Branch (52:21): [True: 2.04k, False: 910]
53
2.04k
        const auto& txid_prev = prevout_txids ?
  Branch (53:33): [True: 0, False: 2.04k]
54
0
                                    PickValue(fuzzed_data_provider, *prevout_txids) :
55
2.04k
                                    Txid::FromUint256(ConsumeUInt256(fuzzed_data_provider));
56
2.04k
        const auto index_out = fuzzed_data_provider.ConsumeIntegralInRange<uint32_t>(0, max_num_out);
57
2.04k
        const auto sequence = ConsumeSequence(fuzzed_data_provider);
58
2.04k
        const auto script_sig = p2wsh_op_true ? CScript{} : ConsumeScript(fuzzed_data_provider);
  Branch (58:33): [True: 876, False: 1.17k]
59
2.04k
        CScriptWitness script_wit;
60
2.04k
        if (p2wsh_op_true) {
  Branch (60:13): [True: 876, False: 1.17k]
61
876
            script_wit.stack = std::vector<std::vector<uint8_t>>{WITNESS_STACK_ELEM_OP_TRUE};
62
1.17k
        } else {
63
1.17k
            script_wit = ConsumeScriptWitness(fuzzed_data_provider);
64
1.17k
        }
65
2.04k
        CTxIn in;
66
2.04k
        in.prevout = COutPoint{txid_prev, index_out};
67
2.04k
        in.nSequence = sequence;
68
2.04k
        in.scriptSig = script_sig;
69
2.04k
        in.scriptWitness = script_wit;
70
71
2.04k
        tx_mut.vin.push_back(in);
72
2.04k
    }
73
4.24k
    for (int i = 0; i < num_out; ++i) {
  Branch (73:21): [True: 3.33k, False: 910]
74
3.33k
        const auto amount = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-10, 50 * COIN + 10);
75
3.33k
        const auto script_pk = p2wsh_op_true ?
  Branch (75:32): [True: 1.39k, False: 1.94k]
76
1.39k
                                   P2WSH_OP_TRUE :
77
3.33k
                                   ConsumeScript(fuzzed_data_provider, /*maybe_p2wsh=*/true);
78
3.33k
        tx_mut.vout.emplace_back(amount, script_pk);
79
3.33k
    }
80
910
    return tx_mut;
81
910
}
82
83
CScriptWitness ConsumeScriptWitness(FuzzedDataProvider& fuzzed_data_provider, const size_t max_stack_elem_size) noexcept
84
1.17k
{
85
1.17k
    CScriptWitness ret;
86
1.17k
    const auto n_elements = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, max_stack_elem_size);
87
3.78k
    for (size_t i = 0; i < n_elements; ++i) {
  Branch (87:24): [True: 2.61k, False: 1.17k]
88
2.61k
        ret.stack.push_back(ConsumeRandomLengthByteVector(fuzzed_data_provider));
89
2.61k
    }
90
1.17k
    return ret;
91
1.17k
}
92
93
CScript ConsumeScript(FuzzedDataProvider& fuzzed_data_provider, const bool maybe_p2wsh) noexcept
94
6.05k
{
95
6.05k
    CScript r_script{};
96
6.05k
    {
97
        // Keep a buffer of bytes to allow the fuzz engine to produce smaller
98
        // inputs to generate CScripts with repeated data.
99
6.05k
        static constexpr unsigned MAX_BUFFER_SZ{128};
100
6.05k
        std::vector<uint8_t> buffer(MAX_BUFFER_SZ, uint8_t{'a'});
101
16.1k
        while (fuzzed_data_provider.ConsumeBool()) {
  Branch (101:16): [True: 10.1k, False: 6.05k]
102
10.1k
            CallOneOf(
103
10.1k
                fuzzed_data_provider,
104
10.1k
                [&] {
105
                    // Insert byte vector directly to allow malformed or unparsable scripts
106
3.74k
                    r_script.insert(r_script.end(), buffer.begin(), buffer.begin() + fuzzed_data_provider.ConsumeIntegralInRange(0U, MAX_BUFFER_SZ));
107
3.74k
                },
108
10.1k
                [&] {
109
                    // Push a byte vector from the buffer
110
3.29k
                    r_script << std::vector<uint8_t>{buffer.begin(), buffer.begin() + fuzzed_data_provider.ConsumeIntegralInRange(0U, MAX_BUFFER_SZ)};
111
3.29k
                },
112
10.1k
                [&] {
113
                    // Push multisig
114
                    // There is a special case for this to aid the fuzz engine
115
                    // navigate the highly structured multisig format.
116
720
                    r_script << fuzzed_data_provider.ConsumeIntegralInRange<int64_t>(0, 22);
117
720
                    int num_data{fuzzed_data_provider.ConsumeIntegralInRange(1, 22)};
118
4.04k
                    while (num_data--) {
  Branch (118:28): [True: 3.32k, False: 720]
119
3.32k
                        auto pubkey_bytes{ConstructPubKeyBytes(fuzzed_data_provider, buffer, fuzzed_data_provider.ConsumeBool())};
120
3.32k
                        if (fuzzed_data_provider.ConsumeBool()) {
  Branch (120:29): [True: 1.59k, False: 1.72k]
121
1.59k
                            pubkey_bytes.back() = num_data; // Make each pubkey different
122
1.59k
                        }
123
3.32k
                        r_script << pubkey_bytes;
124
3.32k
                    }
125
720
                    r_script << fuzzed_data_provider.ConsumeIntegralInRange<int64_t>(0, 22);
126
720
                },
127
10.1k
                [&] {
128
                    // Mutate the buffer
129
536
                    const auto vec{ConsumeRandomLengthByteVector(fuzzed_data_provider, /*max_length=*/MAX_BUFFER_SZ)};
130
536
                    std::copy(vec.begin(), vec.end(), buffer.begin());
131
536
                },
132
10.1k
                [&] {
133
                    // Push an integral
134
350
                    r_script << fuzzed_data_provider.ConsumeIntegral<int64_t>();
135
350
                },
136
10.1k
                [&] {
137
                    // Push an opcode
138
1.07k
                    r_script << ConsumeOpcodeType(fuzzed_data_provider);
139
1.07k
                },
140
10.1k
                [&] {
141
                    // Push a scriptnum
142
424
                    r_script << ConsumeScriptNum(fuzzed_data_provider);
143
424
                });
144
10.1k
        }
145
6.05k
    }
146
6.05k
    if (maybe_p2wsh && fuzzed_data_provider.ConsumeBool()) {
  Branch (146:9): [True: 1.94k, False: 4.11k]
  Branch (146:24): [True: 167, False: 1.77k]
147
167
        uint256 script_hash;
148
167
        CSHA256().Write(r_script.data(), r_script.size()).Finalize(script_hash.begin());
149
167
        r_script.clear();
150
167
        r_script << OP_0 << ToByteVector(script_hash);
151
167
    }
152
6.05k
    return r_script;
153
6.05k
}
154
155
uint32_t ConsumeSequence(FuzzedDataProvider& fuzzed_data_provider) noexcept
156
2.04k
{
157
2.04k
    return fuzzed_data_provider.ConsumeBool() ?
  Branch (157:12): [True: 471, False: 1.57k]
158
471
               fuzzed_data_provider.PickValueInArray({
159
471
                   CTxIn::SEQUENCE_FINAL,
160
471
                   CTxIn::MAX_SEQUENCE_NONFINAL,
161
471
                   MAX_BIP125_RBF_SEQUENCE,
162
471
               }) :
163
2.04k
               fuzzed_data_provider.ConsumeIntegral<uint32_t>();
164
2.04k
}
165
166
std::map<COutPoint, Coin> ConsumeCoins(FuzzedDataProvider& fuzzed_data_provider) noexcept
167
0
{
168
0
    std::map<COutPoint, Coin> coins;
169
0
    LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10000) {
170
0
        const std::optional<COutPoint> outpoint{ConsumeDeserializable<COutPoint>(fuzzed_data_provider)};
171
0
        if (!outpoint) {
  Branch (171:13): [True: 0, False: 0]
172
0
            break;
173
0
        }
174
0
        const std::optional<Coin> coin{ConsumeDeserializable<Coin>(fuzzed_data_provider)};
175
0
        if (!coin) {
  Branch (175:13): [True: 0, False: 0]
176
0
            break;
177
0
        }
178
0
        coins[*outpoint] = *coin;
179
0
    }
180
181
0
    return coins;
182
0
}
183
184
CTxDestination ConsumeTxDestination(FuzzedDataProvider& fuzzed_data_provider) noexcept
185
0
{
186
0
    CTxDestination tx_destination;
187
0
    const size_t call_size{CallOneOf(
188
0
        fuzzed_data_provider,
189
0
        [&] {
190
0
            tx_destination = CNoDestination{};
191
0
        },
192
0
        [&] {
193
0
            bool compressed = fuzzed_data_provider.ConsumeBool();
194
0
            CPubKey pk{ConstructPubKeyBytes(
195
0
                    fuzzed_data_provider,
196
0
                    ConsumeFixedLengthByteVector(fuzzed_data_provider, (compressed ? CPubKey::COMPRESSED_SIZE : CPubKey::SIZE)),
  Branch (196:73): [True: 0, False: 0]
197
0
                    compressed
198
0
            )};
199
0
            tx_destination = PubKeyDestination{pk};
200
0
        },
201
0
        [&] {
202
0
            tx_destination = PKHash{ConsumeUInt160(fuzzed_data_provider)};
203
0
        },
204
0
        [&] {
205
0
            tx_destination = ScriptHash{ConsumeUInt160(fuzzed_data_provider)};
206
0
        },
207
0
        [&] {
208
0
            tx_destination = WitnessV0ScriptHash{ConsumeUInt256(fuzzed_data_provider)};
209
0
        },
210
0
        [&] {
211
0
            tx_destination = WitnessV0KeyHash{ConsumeUInt160(fuzzed_data_provider)};
212
0
        },
213
0
        [&] {
214
0
            tx_destination = WitnessV1Taproot{XOnlyPubKey{ConsumeUInt256(fuzzed_data_provider)}};
215
0
        },
216
0
        [&] {
217
0
            tx_destination = PayToAnchor{};
218
0
        },
219
0
        [&] {
220
0
            std::vector<unsigned char> program{ConsumeRandomLengthByteVector(fuzzed_data_provider, /*max_length=*/40)};
221
0
            if (program.size() < 2) {
  Branch (221:17): [True: 0, False: 0]
222
0
                program = {0, 0};
223
0
            }
224
0
            tx_destination = WitnessUnknown{fuzzed_data_provider.ConsumeIntegralInRange<unsigned int>(2, 16), program};
225
0
        })};
226
0
    Assert(call_size == std::variant_size_v<CTxDestination>);
227
0
    return tx_destination;
228
0
}
229
230
CKey ConsumePrivateKey(FuzzedDataProvider& fuzzed_data_provider, std::optional<bool> compressed) noexcept
231
0
{
232
0
    auto key_data = fuzzed_data_provider.ConsumeBytes<uint8_t>(32);
233
0
    key_data.resize(32);
234
0
    CKey key;
235
0
    bool compressed_value = compressed ? *compressed : fuzzed_data_provider.ConsumeBool();
  Branch (235:29): [True: 0, False: 0]
236
0
    key.Set(key_data.begin(), key_data.end(), compressed_value);
237
0
    return key;
238
0
}
239
240
UniValue ConsumeUniValue(FuzzedDataProvider& fuzzed_data_provider) noexcept
241
2.16k
{
242
2.16k
    UniValue value{UniValue::VOBJ};
243
2.16k
    value.pushKV("bool", fuzzed_data_provider.ConsumeBool());
244
2.16k
    value.pushKV("number", fuzzed_data_provider.ConsumeIntegralInRange<int>(-1'000'000, 1'000'000));
245
2.16k
    value.pushKV("string", "ipc fuzz");
246
247
2.16k
    return value;
248
2.16k
}
249
250
bool ContainsSpentInput(const CTransaction& tx, const CCoinsViewCache& inputs) noexcept
251
0
{
252
0
    for (const CTxIn& tx_in : tx.vin) {
  Branch (252:29): [True: 0, False: 0]
253
0
        const Coin& coin = inputs.AccessCoin(tx_in.prevout);
254
0
        if (coin.IsSpent()) {
  Branch (254:13): [True: 0, False: 0]
255
0
            return true;
256
0
        }
257
0
    }
258
0
    return false;
259
0
}
260
261
FILE* FuzzedFileProvider::open()
262
0
{
263
0
    SetFuzzedErrNo(m_fuzzed_data_provider);
264
0
    if (m_fuzzed_data_provider.ConsumeBool()) {
  Branch (264:9): [True: 0, False: 0]
265
0
        return nullptr;
266
0
    }
267
0
    std::string mode;
268
0
    CallOneOf(
269
0
        m_fuzzed_data_provider,
270
0
        [&] {
271
0
            mode = "r";
272
0
        },
273
0
        [&] {
274
0
            mode = "r+";
275
0
        },
276
0
        [&] {
277
0
            mode = "w";
278
0
        },
279
0
        [&] {
280
0
            mode = "w+";
281
0
        },
282
0
        [&] {
283
0
            mode = "a";
284
0
        },
285
0
        [&] {
286
0
            mode = "a+";
287
0
        });
288
0
#if defined _GNU_SOURCE && (defined(__linux__) || defined(__FreeBSD__))
289
0
    const cookie_io_functions_t io_hooks = {
290
0
        FuzzedFileProvider::read,
291
0
        FuzzedFileProvider::write,
292
0
        FuzzedFileProvider::seek,
293
0
        FuzzedFileProvider::close,
294
0
    };
295
0
    return fopencookie(this, mode.c_str(), io_hooks);
296
#else
297
    (void)mode;
298
    return nullptr;
299
#endif
300
0
}
301
302
ssize_t FuzzedFileProvider::read(void* cookie, char* buf, size_t size)
303
0
{
304
0
    FuzzedFileProvider* fuzzed_file = (FuzzedFileProvider*)cookie;
305
0
    SetFuzzedErrNo(fuzzed_file->m_fuzzed_data_provider);
306
0
    if (buf == nullptr || size == 0 || fuzzed_file->m_fuzzed_data_provider.ConsumeBool()) {
  Branch (306:9): [True: 0, False: 0]
  Branch (306:27): [True: 0, False: 0]
  Branch (306:40): [True: 0, False: 0]
307
0
        return fuzzed_file->m_fuzzed_data_provider.ConsumeBool() ? 0 : -1;
  Branch (307:16): [True: 0, False: 0]
308
0
    }
309
0
    const std::vector<uint8_t> random_bytes = fuzzed_file->m_fuzzed_data_provider.ConsumeBytes<uint8_t>(size);
310
0
    if (random_bytes.empty()) {
  Branch (310:9): [True: 0, False: 0]
311
0
        return 0;
312
0
    }
313
0
    std::memcpy(buf, random_bytes.data(), random_bytes.size());
314
0
    if (AdditionOverflow(fuzzed_file->m_offset, (int64_t)random_bytes.size())) {
  Branch (314:9): [True: 0, False: 0]
315
0
        return fuzzed_file->m_fuzzed_data_provider.ConsumeBool() ? 0 : -1;
  Branch (315:16): [True: 0, False: 0]
316
0
    }
317
0
    fuzzed_file->m_offset += random_bytes.size();
318
0
    return random_bytes.size();
319
0
}
320
321
ssize_t FuzzedFileProvider::write(void* cookie, const char* buf, size_t size)
322
0
{
323
0
    FuzzedFileProvider* fuzzed_file = (FuzzedFileProvider*)cookie;
324
0
    SetFuzzedErrNo(fuzzed_file->m_fuzzed_data_provider);
325
0
    const ssize_t n = fuzzed_file->m_fuzzed_data_provider.ConsumeIntegralInRange<ssize_t>(0, size);
326
0
    if (AdditionOverflow(fuzzed_file->m_offset, (int64_t)n)) {
  Branch (326:9): [True: 0, False: 0]
327
0
        return 0;
328
0
    }
329
0
    fuzzed_file->m_offset += n;
330
0
    return n;
331
0
}
332
333
int FuzzedFileProvider::seek(void* cookie, int64_t* offset, int whence)
334
0
{
335
0
    assert(whence == SEEK_SET || whence == SEEK_CUR || whence == SEEK_END);
  Branch (335:5): [True: 0, False: 0]
  Branch (335:5): [True: 0, False: 0]
  Branch (335:5): [True: 0, False: 0]
  Branch (335:5): [True: 0, False: 0]
336
0
    FuzzedFileProvider* fuzzed_file = (FuzzedFileProvider*)cookie;
337
0
    SetFuzzedErrNo(fuzzed_file->m_fuzzed_data_provider);
338
0
    int64_t new_offset = 0;
339
0
    if (whence == SEEK_SET) {
  Branch (339:9): [True: 0, False: 0]
340
0
        new_offset = *offset;
341
0
    } else if (whence == SEEK_CUR) {
  Branch (341:16): [True: 0, False: 0]
342
0
        if (AdditionOverflow(fuzzed_file->m_offset, *offset)) {
  Branch (342:13): [True: 0, False: 0]
343
0
            return -1;
344
0
        }
345
0
        new_offset = fuzzed_file->m_offset + *offset;
346
0
    } else if (whence == SEEK_END) {
  Branch (346:16): [True: 0, False: 0]
347
0
        const int64_t n = fuzzed_file->m_fuzzed_data_provider.ConsumeIntegralInRange<int64_t>(0, 4096);
348
0
        if (AdditionOverflow(n, *offset)) {
  Branch (348:13): [True: 0, False: 0]
349
0
            return -1;
350
0
        }
351
0
        new_offset = n + *offset;
352
0
    }
353
0
    if (new_offset < 0) {
  Branch (353:9): [True: 0, False: 0]
354
0
        return -1;
355
0
    }
356
0
    fuzzed_file->m_offset = new_offset;
357
0
    *offset = new_offset;
358
0
    return fuzzed_file->m_fuzzed_data_provider.ConsumeIntegralInRange<int>(-1, 0);
359
0
}
360
361
int FuzzedFileProvider::close(void* cookie)
362
0
{
363
0
    FuzzedFileProvider* fuzzed_file = (FuzzedFileProvider*)cookie;
364
0
    SetFuzzedErrNo(fuzzed_file->m_fuzzed_data_provider);
365
0
    return fuzzed_file->m_fuzzed_data_provider.ConsumeIntegralInRange<int>(-1, 0);
366
0
}