Coverage Report

Created: 2026-09-15 16:03

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/bitcoin/src/wallet/test/fuzz/scriptpubkeyman.cpp
Line
Count
Source
1
// Copyright (c) 2023-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 <addresstype.h>
6
#include <chainparams.h>
7
#include <coins.h>
8
#include <key.h>
9
#include <primitives/transaction.h>
10
#include <psbt.h>
11
#include <script/descriptor.h>
12
#include <script/interpreter.h>
13
#include <script/script.h>
14
#include <script/signingprovider.h>
15
#include <sync.h>
16
#include <test/fuzz/FuzzedDataProvider.h>
17
#include <test/fuzz/fuzz.h>
18
#include <test/fuzz/util.h>
19
#include <test/fuzz/util/descriptor.h>
20
#include <test/util/setup_common.h>
21
#include <test/util/time.h>
22
#include <util/check.h>
23
#include <util/time.h>
24
#include <util/translation.h>
25
#include <util/string.h>
26
#include <validation.h>
27
#include <wallet/context.h>
28
#include <wallet/scriptpubkeyman.h>
29
#include <wallet/test/util.h>
30
#include <wallet/types.h>
31
#include <wallet/wallet.h>
32
#include <wallet/walletutil.h>
33
34
#include <map>
35
#include <memory>
36
#include <optional>
37
#include <string>
38
#include <utility>
39
#include <variant>
40
41
namespace wallet {
42
namespace {
43
const TestingSetup* g_setup;
44
45
//! The converter of mocked descriptors, needs to be initialized when the target is.
46
MockedDescriptorConverter MOCKED_DESC_CONVERTER;
47
48
void initialize_spkm()
49
0
{
50
0
    static const auto testing_setup{MakeNoLogFileContext<const TestingSetup>()};
51
0
    g_setup = testing_setup.get();
52
0
    MOCKED_DESC_CONVERTER.Init();
53
0
}
54
55
void initialize_spkm_migration()
56
0
{
57
0
    static const auto testing_setup{MakeNoLogFileContext<const TestingSetup>()};
58
0
    g_setup = testing_setup.get();
59
0
}
60
61
static std::optional<std::pair<WalletDescriptor, FlatSigningProvider>> CreateWalletDescriptor(FuzzedDataProvider& fuzzed_data_provider)
62
0
{
63
0
    const std::string mocked_descriptor{fuzzed_data_provider.ConsumeRandomLengthString()};
64
0
    const auto desc_str{MOCKED_DESC_CONVERTER.GetDescriptor(mocked_descriptor)};
65
0
    if (!desc_str.has_value()) return std::nullopt;
  Branch (65:9): [True: 0, False: 0]
66
0
    if (IsTooExpensive(MakeUCharSpan(*desc_str))) return {};
  Branch (66:9): [True: 0, False: 0]
67
68
0
    FlatSigningProvider keys;
69
0
    std::string error;
70
0
    std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str.value(), keys, error, false);
71
0
    if (parsed_descs.empty()) return std::nullopt;
  Branch (71:9): [True: 0, False: 0]
72
73
    // Verify expand succeeds before making WalletDescriptor
74
    // Expansion results are not needed
75
0
    FlatSigningProvider out_keys;
76
0
    std::vector<CScript> scripts_temp;
77
0
    DescriptorCache temp_cache;
78
0
    if (!parsed_descs.at(0)->Expand(0, keys, scripts_temp, out_keys, &temp_cache)) return std::nullopt;
  Branch (78:9): [True: 0, False: 0]
79
80
0
    WalletDescriptor w_desc{std::move(parsed_descs.at(0)), /*creation_time=*/0, /*range_start=*/0, /*range_end=*/1, /*next_index=*/1};
81
0
    return std::make_pair(w_desc, keys);
82
0
}
83
84
static DescriptorScriptPubKeyMan* CreateDescriptor(WalletDescriptor& wallet_desc, FlatSigningProvider& keys, CWallet& keystore)
85
0
{
86
0
    LOCK(keystore.cs_wallet);
87
0
    auto spk_manager_res = keystore.AddWalletDescriptor(wallet_desc, keys, /*label=*/"", /*internal=*/false);
88
0
    if (!spk_manager_res) return nullptr;
  Branch (88:9): [True: 0, False: 0]
89
0
    return &spk_manager_res.value().get();
90
0
};
91
92
FUZZ_TARGET(scriptpubkeyman, .init = initialize_spkm)
93
0
{
94
0
    SeedRandomStateForTest(SeedRand::ZEROS);
95
0
    FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
96
0
    FakeNodeClock clock{ConsumeTime(fuzzed_data_provider)};
97
0
    const auto& node{g_setup->m_node};
98
0
    Chainstate& chainstate{node.chainman->ActiveChainstate()};
99
0
    std::unique_ptr<CWallet> wallet_ptr{std::make_unique<CWallet>(node.chain.get(), "", CreateMockableWalletDatabase())};
100
0
    CWallet& wallet{*wallet_ptr};
101
0
    {
102
0
        LOCK(wallet.cs_wallet);
103
0
        wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
104
0
        wallet.SetLastBlockProcessed(chainstate.m_chain.Height(), chainstate.m_chain.Tip()->GetBlockHash());
105
0
        wallet.m_keypool_size = 1;
106
0
    }
107
108
0
    auto wallet_desc{CreateWalletDescriptor(fuzzed_data_provider)};
109
0
    if (!wallet_desc.has_value()) return;
  Branch (109:9): [True: 0, False: 0]
110
0
    auto spk_manager{CreateDescriptor(wallet_desc->first, wallet_desc->second, wallet)};
111
0
    if (spk_manager == nullptr) return;
  Branch (111:9): [True: 0, False: 0]
112
113
0
    if (fuzzed_data_provider.ConsumeBool()) {
  Branch (113:9): [True: 0, False: 0]
114
0
        auto wallet_desc{CreateWalletDescriptor(fuzzed_data_provider)};
115
0
        if (!wallet_desc.has_value()) {
  Branch (115:13): [True: 0, False: 0]
116
0
            return;
117
0
        }
118
0
        std::string error;
119
0
        if (spk_manager->CanUpdateToWalletDescriptor(wallet_desc->first, error)) {
  Branch (119:13): [True: 0, False: 0]
120
0
            auto new_spk_manager{CreateDescriptor(wallet_desc->first, wallet_desc->second, wallet)};
121
0
            if (new_spk_manager != nullptr) spk_manager = new_spk_manager;
  Branch (121:17): [True: 0, False: 0]
122
0
        }
123
0
    }
124
125
0
    bool good_data{true};
126
0
    LIMITED_WHILE (good_data && fuzzed_data_provider.ConsumeBool(), 20) {
127
0
        CallOneOf(
128
0
            fuzzed_data_provider,
129
0
            [&] {
130
0
                const CScript script{ConsumeScript(fuzzed_data_provider)};
131
0
                if (spk_manager->IsMine(script)) {
  Branch (131:21): [True: 0, False: 0]
132
0
                    assert(spk_manager->GetScriptPubKeys().contains(script));
  Branch (132:21): [True: 0, False: 0]
133
0
                }
134
0
            },
135
0
            [&] {
136
0
                auto spks{spk_manager->GetScriptPubKeys()};
137
0
                for (const CScript& spk : spks) {
  Branch (137:41): [True: 0, False: 0]
138
0
                    assert(spk_manager->IsMine(spk));
  Branch (138:21): [True: 0, False: 0]
139
0
                    CTxDestination dest;
140
0
                    bool extract_dest{ExtractDestination(spk, dest)};
141
0
                    if (extract_dest) {
  Branch (141:25): [True: 0, False: 0]
142
0
                        const std::string msg{fuzzed_data_provider.ConsumeRandomLengthString()};
143
0
                        PKHash pk_hash{std::get_if<PKHash>(&dest) && fuzzed_data_provider.ConsumeBool() ?
  Branch (143:40): [True: 0, False: 0]
  Branch (143:70): [True: 0, False: 0]
144
0
                                           *std::get_if<PKHash>(&dest) :
145
0
                                           PKHash{ConsumeUInt160(fuzzed_data_provider)}};
146
0
                        std::string str_sig;
147
0
                        (void)spk_manager->SignMessage(msg, pk_hash, str_sig);
148
0
                        (void)spk_manager->GetMetadata(dest);
149
0
                    }
150
0
                }
151
0
            },
152
0
            [&] {
153
0
                auto spks{spk_manager->GetScriptPubKeys()};
154
0
                if (!spks.empty()) {
  Branch (154:21): [True: 0, False: 0]
155
0
                    auto& spk{PickValue(fuzzed_data_provider, spks)};
156
0
                    (void)spk_manager->MarkUnusedAddresses(spk);
157
0
                }
158
0
            },
159
0
            [&] {
160
0
                LOCK(spk_manager->cs_desc_man);
161
0
                auto wallet_desc{spk_manager->GetWalletDescriptor()};
162
0
                if (wallet_desc.descriptor->IsSingleType()) {
  Branch (162:21): [True: 0, False: 0]
163
0
                    auto output_type{wallet_desc.descriptor->GetOutputType()};
164
0
                    if (output_type.has_value()) {
  Branch (164:25): [True: 0, False: 0]
165
0
                        auto dest{spk_manager->GetNewDestination(*output_type)};
166
0
                        if (dest) {
  Branch (166:29): [True: 0, False: 0]
167
0
                            assert(IsValidDestination(*dest));
  Branch (167:29): [True: 0, False: 0]
168
0
                            assert(spk_manager->IsHDEnabled());
  Branch (168:29): [True: 0, False: 0]
169
0
                        }
170
0
                    }
171
0
                }
172
0
            },
173
0
            [&] {
174
0
                CMutableTransaction tx_to;
175
0
                const std::optional<CMutableTransaction> opt_tx_to{ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS)};
176
0
                if (!opt_tx_to) {
  Branch (176:21): [True: 0, False: 0]
177
0
                    good_data = false;
178
0
                    return;
179
0
                }
180
0
                tx_to = *opt_tx_to;
181
182
0
                std::map<COutPoint, Coin> coins{ConsumeCoins(fuzzed_data_provider)};
183
0
                const int sighash{fuzzed_data_provider.ConsumeIntegral<int>()};
184
0
                std::map<int, bilingual_str> input_errors;
185
0
                (void)spk_manager->SignTransaction(tx_to, coins, sighash, input_errors);
186
0
            },
187
0
            [&] {
188
0
                std::optional<PartiallySignedTransaction> opt_psbt{ConsumeDeserializableConstructor<PartiallySignedTransaction>(fuzzed_data_provider)};
189
0
                if (!opt_psbt) {
  Branch (189:21): [True: 0, False: 0]
190
0
                    good_data = false;
191
0
                    return;
192
0
                }
193
0
                auto psbt{*opt_psbt};
194
0
                std::optional<PrecomputedTransactionData> txdata_res = PrecomputePSBTData(psbt);
195
0
                if (!txdata_res) {
  Branch (195:21): [True: 0, False: 0]
196
0
                    return;
197
0
                }
198
0
                const PrecomputedTransactionData& txdata = *txdata_res;
199
0
                common::PSBTFillOptions options{
200
0
                    .sign = fuzzed_data_provider.ConsumeBool(),
201
0
                    .sighash_type = fuzzed_data_provider.ConsumeIntegralInRange<int>(0, 151),
202
0
                    .finalize = fuzzed_data_provider.ConsumeBool(),
203
0
                    .bip32_derivs = fuzzed_data_provider.ConsumeBool()
204
0
                };
205
0
                if (options.sighash_type == 151) options.sighash_type = std::nullopt;
  Branch (205:21): [True: 0, False: 0]
206
0
                (void)spk_manager->FillPSBT(psbt, txdata, options);
207
0
            }
208
0
        );
209
0
    }
210
211
0
    std::string descriptor;
212
0
    (void)spk_manager->GetDescriptorString(descriptor, /*priv=*/fuzzed_data_provider.ConsumeBool());
213
0
    (void)spk_manager->GetEndRange();
214
0
    (void)spk_manager->GetKeyPoolSize();
215
0
}
216
217
FUZZ_TARGET(spkm_migration, .init = initialize_spkm_migration)
218
0
{
219
0
    SeedRandomStateForTest(SeedRand::ZEROS);
220
0
    FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
221
0
    FakeNodeClock clock{ConsumeTime(fuzzed_data_provider)};
222
0
    const auto& node{g_setup->m_node};
223
0
    Chainstate& chainstate{node.chainman->ActiveChainstate()};
224
225
0
    std::unique_ptr<CWallet> wallet_ptr{std::make_unique<CWallet>(node.chain.get(), "", CreateMockableWalletDatabase())};
226
0
    CWallet& wallet{*wallet_ptr};
227
0
    wallet.m_keypool_size = 1;
228
0
    {
229
0
        LOCK(wallet.cs_wallet);
230
0
        wallet.UnsetWalletFlag(WALLET_FLAG_DESCRIPTORS);
231
0
        wallet.SetLastBlockProcessed(chainstate.m_chain.Height(), chainstate.m_chain.Tip()->GetBlockHash());
232
0
    }
233
234
0
    auto& legacy_data{*wallet.GetOrCreateLegacyDataSPKM()};
235
236
0
    std::vector<CKey> keys;
237
0
    LIMITED_WHILE (fuzzed_data_provider.ConsumeBool(), 30) {
238
0
        const auto key{ConsumePrivateKey(fuzzed_data_provider)};
239
0
        if (!key.IsValid()) return;
  Branch (239:13): [True: 0, False: 0]
240
0
        auto pub_key{key.GetPubKey()};
241
0
        if (!pub_key.IsFullyValid()) return;
  Branch (241:13): [True: 0, False: 0]
242
0
        if (legacy_data.LoadKey(key, pub_key) && std::find(keys.begin(), keys.end(), key) == keys.end()) keys.push_back(key);
  Branch (242:13): [True: 0, False: 0]
  Branch (242:13): [True: 0, False: 0]
  Branch (242:50): [True: 0, False: 0]
243
0
    }
244
245
0
    size_t added_chains = 0;
246
0
    bool add_hd_chain{fuzzed_data_provider.ConsumeBool() && !keys.empty()};
  Branch (246:23): [True: 0, False: 0]
  Branch (246:61): [True: 0, False: 0]
247
0
    CHDChain hd_chain;
248
0
    auto version{fuzzed_data_provider.ConsumeBool() ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE};
  Branch (248:18): [True: 0, False: 0]
249
0
    CKey hd_key;
250
0
    if (add_hd_chain) {
  Branch (250:9): [True: 0, False: 0]
251
0
        hd_key = PickValue(fuzzed_data_provider, keys);
252
0
        hd_chain.nVersion = version;
253
0
        hd_chain.seed_id = hd_key.GetPubKey().GetID();
254
0
        legacy_data.LoadHDChain(hd_chain);
255
0
        added_chains++;
256
0
    }
257
258
0
    bool add_inactive_hd_chain{fuzzed_data_provider.ConsumeBool() && !keys.empty()};
  Branch (258:32): [True: 0, False: 0]
  Branch (258:70): [True: 0, False: 0]
259
0
    if (add_inactive_hd_chain) {
  Branch (259:9): [True: 0, False: 0]
260
0
        CKey inactive_hd_key = PickValue(fuzzed_data_provider, keys);
261
0
        hd_chain.nVersion = fuzzed_data_provider.ConsumeBool() ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
  Branch (261:29): [True: 0, False: 0]
262
0
        bool dup_chain = hd_key.IsValid() && std::equal(hd_key.begin(), hd_key.end(), inactive_hd_key.begin());
  Branch (262:26): [True: 0, False: 0]
  Branch (262:46): [True: 0, False: 0]
263
0
        hd_chain.seed_id = inactive_hd_key.GetPubKey().GetID();
264
0
        legacy_data.AddInactiveHDChain(hd_chain);
265
0
        if (!dup_chain) added_chains++;
  Branch (265:13): [True: 0, False: 0]
266
0
    }
267
268
0
    bool watch_only = false;
269
0
    const auto pub_key = ConsumeDeserializable<CPubKey>(fuzzed_data_provider);
270
0
    if (!pub_key || !pub_key->IsFullyValid()) return;
  Branch (270:9): [True: 0, False: 0]
  Branch (270:21): [True: 0, False: 0]
271
0
    auto script_dest{GetScriptForDestination(WitnessV0KeyHash{*pub_key})};
272
0
    if (fuzzed_data_provider.ConsumeBool()) {
  Branch (272:9): [True: 0, False: 0]
273
0
        script_dest = GetScriptForDestination(CTxDestination{PKHash(*pub_key)});
274
0
    }
275
0
    if (legacy_data.LoadWatchOnly(script_dest)) watch_only = true;
  Branch (275:9): [True: 0, False: 0]
276
277
0
    size_t added_script{0};
278
0
    bool good_data{true};
279
0
    LIMITED_WHILE (good_data && fuzzed_data_provider.ConsumeBool(), 30) {
280
0
        CallOneOf(
281
0
            fuzzed_data_provider,
282
0
            [&] {
283
0
                CKey key;
284
0
                if (!keys.empty()) {
  Branch (284:21): [True: 0, False: 0]
285
0
                    key = PickValue(fuzzed_data_provider, keys);
286
0
                } else {
287
0
                    key = ConsumePrivateKey(fuzzed_data_provider, /*compressed=*/fuzzed_data_provider.ConsumeBool());
288
0
                }
289
0
                if (!key.IsValid()) return;
  Branch (289:21): [True: 0, False: 0]
290
0
                auto pub_key{key.GetPubKey()};
291
0
                CScript script;
292
0
                CallOneOf(
293
0
                    fuzzed_data_provider,
294
0
                    [&] {
295
0
                        script = GetScriptForDestination(CTxDestination{PKHash(pub_key)});
296
0
                    },
297
0
                    [&] {
298
0
                        script = GetScriptForDestination(WitnessV0KeyHash(pub_key));
299
0
                    },
300
0
                    [&] {
301
0
                        std::optional<CScript> script_opt{ConsumeDeserializable<CScript>(fuzzed_data_provider)};
302
0
                        if (!script_opt) {
  Branch (302:29): [True: 0, False: 0]
303
0
                            good_data = false;
304
0
                            return;
305
0
                        }
306
0
                        script = script_opt.value();
307
0
                    }
308
0
                );
309
0
                if (fuzzed_data_provider.ConsumeBool()) script = GetScriptForDestination(ScriptHash(script));
  Branch (309:21): [True: 0, False: 0]
310
0
                if (!legacy_data.HaveCScript(CScriptID(script)) && legacy_data.AddCScript(script)) added_script++;
  Branch (310:21): [True: 0, False: 0]
  Branch (310:21): [True: 0, False: 0]
  Branch (310:68): [True: 0, False: 0]
311
0
            },
312
0
            [&] {
313
0
                CKey key;
314
0
                if (!keys.empty()) {
  Branch (314:21): [True: 0, False: 0]
315
0
                    key = PickValue(fuzzed_data_provider, keys);
316
0
                } else {
317
0
                    key = ConsumePrivateKey(fuzzed_data_provider, /*compressed=*/fuzzed_data_provider.ConsumeBool());
318
0
                }
319
0
                if (!key.IsValid()) return;
  Branch (319:21): [True: 0, False: 0]
320
0
                const auto num_keys{fuzzed_data_provider.ConsumeIntegralInRange<size_t>(1, MAX_PUBKEYS_PER_MULTISIG)};
321
0
                std::vector<CPubKey> pubkeys;
322
0
                pubkeys.emplace_back(key.GetPubKey());
323
0
                for (size_t i = 1; i < num_keys; i++) {
  Branch (323:36): [True: 0, False: 0]
324
0
                    if (fuzzed_data_provider.ConsumeBool()) {
  Branch (324:25): [True: 0, False: 0]
325
0
                        pubkeys.emplace_back(key.GetPubKey());
326
0
                    } else {
327
0
                        CKey private_key{ConsumePrivateKey(fuzzed_data_provider, /*compressed=*/fuzzed_data_provider.ConsumeBool())};
328
0
                        if (!private_key.IsValid()) return;
  Branch (328:29): [True: 0, False: 0]
329
0
                        pubkeys.emplace_back(private_key.GetPubKey());
330
0
                    }
331
0
                }
332
0
                if (pubkeys.size() < num_keys) return;
  Branch (332:21): [True: 0, False: 0]
333
0
                CScript multisig_script{GetScriptForMultisig(num_keys, pubkeys)};
334
0
                if (!legacy_data.HaveCScript(CScriptID(multisig_script)) && legacy_data.AddCScript(multisig_script)) {
  Branch (334:21): [True: 0, False: 0]
  Branch (334:21): [True: 0, False: 0]
  Branch (334:77): [True: 0, False: 0]
335
0
                    added_script++;
336
0
                }
337
0
            }
338
0
        );
339
0
    }
340
341
0
    auto result{legacy_data.MigrateToDescriptor()};
342
0
    assert(result);
  Branch (342:5): [True: 0, False: 0]
343
0
    if ((add_hd_chain && version >= CHDChain::VERSION_HD_CHAIN_SPLIT) || (!add_hd_chain && add_inactive_hd_chain)) {
  Branch (343:10): [True: 0, False: 0]
  Branch (343:26): [True: 0, False: 0]
  Branch (343:75): [True: 0, False: 0]
  Branch (343:92): [True: 0, False: 0]
344
0
        added_chains *= 2;
345
0
    }
346
0
    size_t added_size{keys.size() + added_chains};
347
0
    if (added_script > 0) {
  Branch (347:9): [True: 0, False: 0]
348
0
        assert(result->desc_spkms.size() >= added_size);
  Branch (348:9): [True: 0, False: 0]
349
0
    } else {
350
0
        assert(result->desc_spkms.size() == added_size);
  Branch (350:9): [True: 0, False: 0]
351
0
    }
352
0
    if (watch_only) assert(!result->watch_descs.empty());
  Branch (352:9): [True: 0, False: 0]
  Branch (352:21): [True: 0, False: 0]
353
0
    if (!result->solvable_descs.empty()) assert(added_script > 0);
  Branch (353:9): [True: 0, False: 0]
  Branch (353:42): [True: 0, False: 0]
354
0
}
355
356
} // namespace
357
} // namespace wallet