Branch data Line data Source code
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 : 1 : void initialize_spkm()
49 : : {
50 [ + - + - : 2 : static const auto testing_setup{MakeNoLogFileContext<const TestingSetup>()};
+ - ]
51 : 1 : g_setup = testing_setup.get();
52 : 1 : MOCKED_DESC_CONVERTER.Init();
53 : 1 : }
54 : :
55 : 1 : void initialize_spkm_migration()
56 : : {
57 [ + - + - : 2 : static const auto testing_setup{MakeNoLogFileContext<const TestingSetup>()};
+ - ]
58 : 1 : g_setup = testing_setup.get();
59 : 1 : }
60 : :
61 : 14989 : static std::optional<std::pair<WalletDescriptor, FlatSigningProvider>> CreateWalletDescriptor(FuzzedDataProvider& fuzzed_data_provider)
62 : : {
63 : 14989 : const std::string mocked_descriptor{fuzzed_data_provider.ConsumeRandomLengthString()};
64 [ - + + - ]: 14989 : const auto desc_str{MOCKED_DESC_CONVERTER.GetDescriptor(mocked_descriptor)};
65 [ + + ]: 14989 : if (!desc_str.has_value()) return std::nullopt;
66 [ + - + + ]: 14850 : if (IsTooExpensive(MakeUCharSpan(*desc_str))) return {};
67 : :
68 : 14836 : FlatSigningProvider keys;
69 [ + - ]: 14836 : std::string error;
70 [ + - - + : 14836 : std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str.value(), keys, error, false);
+ - ]
71 [ + + ]: 14836 : if (parsed_descs.empty()) return std::nullopt;
72 : :
73 : : // Verify expand succeeds before making WalletDescriptor
74 : : // Expansion results are not needed
75 : 12663 : FlatSigningProvider out_keys;
76 : 12663 : std::vector<CScript> scripts_temp;
77 : 12663 : DescriptorCache temp_cache;
78 [ + - + - : 12663 : if (!parsed_descs.at(0)->Expand(0, keys, scripts_temp, out_keys, &temp_cache)) return std::nullopt;
+ + ]
79 : :
80 [ + - + - : 12560 : WalletDescriptor w_desc{std::move(parsed_descs.at(0)), /*creation_time=*/0, /*range_start=*/0, /*range_end=*/1, /*next_index=*/1};
+ - ]
81 [ + - ]: 12560 : return std::make_pair(w_desc, keys);
82 : 29825 : }
83 : :
84 : 10515 : static DescriptorScriptPubKeyMan* CreateDescriptor(WalletDescriptor& wallet_desc, FlatSigningProvider& keys, CWallet& keystore)
85 : : {
86 : 10515 : LOCK(keystore.cs_wallet);
87 [ + - + - ]: 10515 : auto spk_manager_res = keystore.AddWalletDescriptor(wallet_desc, keys, /*label=*/"", /*internal=*/false);
88 [ + - ]: 10515 : if (!spk_manager_res) return nullptr;
89 : 10515 : return &spk_manager_res.value().get();
90 [ + - ]: 21030 : };
91 : :
92 [ + - ]: 13051 : FUZZ_TARGET(scriptpubkeyman, .init = initialize_spkm)
93 : : {
94 : 12577 : SeedRandomStateForTest(SeedRand::ZEROS);
95 : 12577 : FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
96 : 12577 : FakeNodeClock clock{ConsumeTime(fuzzed_data_provider)};
97 : 12577 : const auto& node{g_setup->m_node};
98 [ + - ]: 12577 : Chainstate& chainstate{node.chainman->ActiveChainstate()};
99 [ + - + - ]: 12577 : std::unique_ptr<CWallet> wallet_ptr{std::make_unique<CWallet>(node.chain.get(), "", CreateMockableWalletDatabase())};
100 [ + - ]: 12577 : CWallet& wallet{*wallet_ptr};
101 : 12577 : {
102 [ + - ]: 12577 : LOCK(wallet.cs_wallet);
103 [ + - ]: 12577 : wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
104 [ - + + - ]: 25154 : wallet.SetLastBlockProcessed(chainstate.m_chain.Height(), chainstate.m_chain.Tip()->GetBlockHash());
105 [ + - ]: 12577 : wallet.m_keypool_size = 1;
106 : 0 : }
107 : :
108 [ + - ]: 12577 : auto wallet_desc{CreateWalletDescriptor(fuzzed_data_provider)};
109 [ + + ]: 12577 : if (!wallet_desc.has_value()) return;
110 [ + - ]: 10398 : auto spk_manager{CreateDescriptor(wallet_desc->first, wallet_desc->second, wallet)};
111 [ + - ]: 10398 : if (spk_manager == nullptr) return;
112 : :
113 [ + + ]: 10398 : if (fuzzed_data_provider.ConsumeBool()) {
114 [ + - ]: 2412 : auto wallet_desc{CreateWalletDescriptor(fuzzed_data_provider)};
115 [ + + ]: 2412 : if (!wallet_desc.has_value()) {
116 : 250 : return;
117 : : }
118 [ + - ]: 2162 : std::string error;
119 [ + - + + ]: 2162 : if (spk_manager->CanUpdateToWalletDescriptor(wallet_desc->first, error)) {
120 [ + - ]: 117 : auto new_spk_manager{CreateDescriptor(wallet_desc->first, wallet_desc->second, wallet)};
121 [ + - ]: 117 : if (new_spk_manager != nullptr) spk_manager = new_spk_manager;
122 : : }
123 [ + - ]: 4574 : }
124 : :
125 : 10148 : bool good_data{true};
126 [ + + + + : 116512 : LIMITED_WHILE (good_data && fuzzed_data_provider.ConsumeBool(), 20) {
+ + ]
127 [ + - ]: 49254 : CallOneOf(
128 : : fuzzed_data_provider,
129 : 1723 : [&] {
130 : 1723 : const CScript script{ConsumeScript(fuzzed_data_provider)};
131 [ + - + + ]: 1723 : if (spk_manager->IsMine(script)) {
132 [ + - + - : 124 : assert(spk_manager->GetScriptPubKeys().contains(script));
- + ]
133 : : }
134 : 1723 : },
135 : 9751 : [&] {
136 : 9751 : auto spks{spk_manager->GetScriptPubKeys()};
137 [ + + + - ]: 40729 : for (const CScript& spk : spks) {
138 [ - + + - ]: 30978 : assert(spk_manager->IsMine(spk));
139 : 30978 : CTxDestination dest;
140 [ + - ]: 30978 : bool extract_dest{ExtractDestination(spk, dest)};
141 [ + + ]: 30978 : if (extract_dest) {
142 [ + - ]: 24116 : const std::string msg{fuzzed_data_provider.ConsumeRandomLengthString()};
143 [ + + + + ]: 24116 : PKHash pk_hash{std::get_if<PKHash>(&dest) && fuzzed_data_provider.ConsumeBool() ?
144 : 5646 : *std::get_if<PKHash>(&dest) :
145 : 24116 : PKHash{ConsumeUInt160(fuzzed_data_provider)}};
146 [ + - ]: 24116 : std::string str_sig;
147 [ + - ]: 24116 : (void)spk_manager->SignMessage(msg, pk_hash, str_sig);
148 [ + - ]: 24116 : (void)spk_manager->GetMetadata(dest);
149 : 24116 : }
150 : 30978 : }
151 : 9751 : },
152 : 3743 : [&] {
153 : 3743 : auto spks{spk_manager->GetScriptPubKeys()};
154 [ + + ]: 3743 : if (!spks.empty()) {
155 : 3699 : auto& spk{PickValue(fuzzed_data_provider, spks)};
156 [ + - ]: 3699 : (void)spk_manager->MarkUnusedAddresses(spk);
157 : : }
158 : 3743 : },
159 : 18127 : [&] {
160 : 18127 : LOCK(spk_manager->cs_desc_man);
161 [ + - ]: 18127 : auto wallet_desc{spk_manager->GetWalletDescriptor()};
162 [ + - + + ]: 18127 : if (wallet_desc.descriptor->IsSingleType()) {
163 [ + - ]: 17905 : auto output_type{wallet_desc.descriptor->GetOutputType()};
164 [ + + ]: 17905 : if (output_type.has_value()) {
165 [ + - ]: 14507 : auto dest{spk_manager->GetNewDestination(*output_type)};
166 [ + + ]: 14507 : if (dest) {
167 [ + - - + ]: 13398 : assert(IsValidDestination(*dest));
168 [ + - - + ]: 13398 : assert(spk_manager->IsHDEnabled());
169 : : }
170 : 14507 : }
171 : : }
172 [ + - ]: 36254 : },
173 : 5557 : [&] {
174 : 5557 : CMutableTransaction tx_to;
175 : 5557 : const std::optional<CMutableTransaction> opt_tx_to{ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS)};
176 [ + + ]: 5557 : if (!opt_tx_to) {
177 : 231 : good_data = false;
178 [ - + ]: 231 : return;
179 : : }
180 [ + - ]: 5326 : tx_to = *opt_tx_to;
181 : :
182 : 5326 : std::map<COutPoint, Coin> coins{ConsumeCoins(fuzzed_data_provider)};
183 : 5326 : const int sighash{fuzzed_data_provider.ConsumeIntegral<int>()};
184 [ + - ]: 5326 : std::map<int, bilingual_str> input_errors;
185 [ + - ]: 5326 : (void)spk_manager->SignTransaction(tx_to, coins, sighash, input_errors);
186 [ + - ]: 16440 : },
187 : 10353 : [&] {
188 : 10353 : std::optional<PartiallySignedTransaction> opt_psbt{ConsumeDeserializableConstructor<PartiallySignedTransaction>(fuzzed_data_provider)};
189 [ + + ]: 10353 : if (!opt_psbt) {
190 : 2061 : good_data = false;
191 : 2061 : return;
192 : : }
193 [ + - ]: 8292 : auto psbt{*opt_psbt};
194 [ + - ]: 8292 : std::optional<PrecomputedTransactionData> txdata_res = PrecomputePSBTData(psbt);
195 [ - + ]: 8292 : if (!txdata_res) {
196 : 0 : return;
197 : : }
198 : 8292 : const PrecomputedTransactionData& txdata = *txdata_res;
199 : 8292 : common::PSBTFillOptions options{
200 : 8292 : .sign = fuzzed_data_provider.ConsumeBool(),
201 : 8292 : .sighash_type = fuzzed_data_provider.ConsumeIntegralInRange<int>(0, 151),
202 : 16584 : .finalize = fuzzed_data_provider.ConsumeBool(),
203 : 16584 : .bip32_derivs = fuzzed_data_provider.ConsumeBool()
204 : 8292 : };
205 [ + - ]: 8297 : if (options.sighash_type == 151) options.sighash_type = std::nullopt;
206 [ + - ]: 8292 : (void)spk_manager->FillPSBT(psbt, txdata, options);
207 : 10353 : }
208 : : );
209 : : }
210 : :
211 : 10148 : std::string descriptor;
212 [ + - ]: 10148 : (void)spk_manager->GetDescriptorString(descriptor, /*priv=*/fuzzed_data_provider.ConsumeBool());
213 [ + - ]: 10148 : (void)spk_manager->GetEndRange();
214 [ + - ]: 10148 : (void)spk_manager->GetKeyPoolSize();
215 [ + - + - : 35302 : }
+ - ]
216 : :
217 [ + - ]: 2007 : FUZZ_TARGET(spkm_migration, .init = initialize_spkm_migration)
218 : : {
219 : 1533 : SeedRandomStateForTest(SeedRand::ZEROS);
220 : 1533 : FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
221 : 1533 : FakeNodeClock clock{ConsumeTime(fuzzed_data_provider)};
222 : 1533 : const auto& node{g_setup->m_node};
223 [ + - ]: 1533 : Chainstate& chainstate{node.chainman->ActiveChainstate()};
224 : :
225 [ + - + - ]: 1533 : std::unique_ptr<CWallet> wallet_ptr{std::make_unique<CWallet>(node.chain.get(), "", CreateMockableWalletDatabase())};
226 [ + - ]: 1533 : CWallet& wallet{*wallet_ptr};
227 : 1533 : wallet.m_keypool_size = 1;
228 : 1533 : {
229 [ + - ]: 1533 : LOCK(wallet.cs_wallet);
230 [ + - ]: 1533 : wallet.UnsetWalletFlag(WALLET_FLAG_DESCRIPTORS);
231 [ - + + - ]: 3066 : wallet.SetLastBlockProcessed(chainstate.m_chain.Height(), chainstate.m_chain.Tip()->GetBlockHash());
232 : 0 : }
233 : :
234 [ + - ]: 1533 : auto& legacy_data{*wallet.GetOrCreateLegacyDataSPKM()};
235 : :
236 : 1533 : std::vector<CKey> keys;
237 [ + + + + ]: 8084 : LIMITED_WHILE (fuzzed_data_provider.ConsumeBool(), 30) {
238 : 6556 : const auto key{ConsumePrivateKey(fuzzed_data_provider)};
239 [ + + ]: 6556 : if (!key.IsValid()) return;
240 [ + - ]: 6551 : auto pub_key{key.GetPubKey()};
241 [ + - + - ]: 6551 : if (!pub_key.IsFullyValid()) return;
242 [ + - + - : 6551 : if (legacy_data.LoadKey(key, pub_key) && std::find(keys.begin(), keys.end(), key) == keys.end()) keys.push_back(key);
+ + + - ]
243 : 6556 : }
244 : :
245 : 1528 : size_t added_chains = 0;
246 [ + + + + ]: 1528 : bool add_hd_chain{fuzzed_data_provider.ConsumeBool() && !keys.empty()};
247 : 1528 : CHDChain hd_chain;
248 [ + + ]: 1528 : auto version{fuzzed_data_provider.ConsumeBool() ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE};
249 : 1528 : CKey hd_key;
250 [ + + ]: 1528 : if (add_hd_chain) {
251 [ + - ]: 477 : hd_key = PickValue(fuzzed_data_provider, keys);
252 : 477 : hd_chain.nVersion = version;
253 [ + - + - ]: 477 : hd_chain.seed_id = hd_key.GetPubKey().GetID();
254 [ + - ]: 477 : legacy_data.LoadHDChain(hd_chain);
255 : : added_chains++;
256 : : }
257 : :
258 [ + + + + ]: 1528 : bool add_inactive_hd_chain{fuzzed_data_provider.ConsumeBool() && !keys.empty()};
259 : 464 : if (add_inactive_hd_chain) {
260 [ + - ]: 464 : CKey inactive_hd_key = PickValue(fuzzed_data_provider, keys);
261 [ + + ]: 464 : hd_chain.nVersion = fuzzed_data_provider.ConsumeBool() ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
262 [ + + + + ]: 860 : bool dup_chain = hd_key.IsValid() && std::equal(hd_key.begin(), hd_key.end(), inactive_hd_key.begin());
263 [ + - + - ]: 464 : hd_chain.seed_id = inactive_hd_key.GetPubKey().GetID();
264 [ + - ]: 464 : legacy_data.AddInactiveHDChain(hd_chain);
265 [ + + ]: 464 : if (!dup_chain) added_chains++;
266 : 464 : }
267 : :
268 : 1528 : bool watch_only = false;
269 : 1528 : const auto pub_key = ConsumeDeserializable<CPubKey>(fuzzed_data_provider);
270 [ + + + - : 1528 : if (!pub_key || !pub_key->IsFullyValid()) return;
+ + ]
271 [ + - + - ]: 1418 : auto script_dest{GetScriptForDestination(WitnessV0KeyHash{*pub_key})};
272 [ + + ]: 1418 : if (fuzzed_data_provider.ConsumeBool()) {
273 [ + - + - ]: 1470 : script_dest = GetScriptForDestination(CTxDestination{PKHash(*pub_key)});
274 : : }
275 [ + - + - ]: 1418 : if (legacy_data.LoadWatchOnly(script_dest)) watch_only = true;
276 : :
277 : 1418 : size_t added_script{0};
278 : 1418 : bool good_data{true};
279 [ + + + + : 27537 : LIMITED_WHILE (good_data && fuzzed_data_provider.ConsumeBool(), 30) {
+ + ]
280 [ + - ]: 12374 : CallOneOf(
281 : : fuzzed_data_provider,
282 : 3180 : [&] {
283 : 3180 : CKey key;
284 [ + + ]: 3180 : if (!keys.empty()) {
285 [ + - ]: 931 : key = PickValue(fuzzed_data_provider, keys);
286 : : } else {
287 : 2249 : key = ConsumePrivateKey(fuzzed_data_provider, /*compressed=*/fuzzed_data_provider.ConsumeBool());
288 : : }
289 [ + + ]: 3180 : if (!key.IsValid()) return;
290 [ + - ]: 3153 : auto pub_key{key.GetPubKey()};
291 : 3153 : CScript script;
292 [ + - ]: 3153 : CallOneOf(
293 : : fuzzed_data_provider,
294 : 770 : [&] {
295 [ + - ]: 770 : script = GetScriptForDestination(CTxDestination{PKHash(pub_key)});
296 : 770 : },
297 : 431 : [&] {
298 [ + - ]: 431 : script = GetScriptForDestination(WitnessV0KeyHash(pub_key));
299 : 431 : },
300 : 1952 : [&] {
301 : 1952 : std::optional<CScript> script_opt{ConsumeDeserializable<CScript>(fuzzed_data_provider)};
302 [ + + ]: 1952 : if (!script_opt) {
303 : 47 : good_data = false;
304 : 47 : return;
305 : : }
306 : 1905 : script = script_opt.value();
307 : 1952 : }
308 : : );
309 [ + + + - : 4039 : if (fuzzed_data_provider.ConsumeBool()) script = GetScriptForDestination(ScriptHash(script));
+ - ]
310 [ + - + - : 3153 : if (!legacy_data.HaveCScript(CScriptID(script)) && legacy_data.AddCScript(script)) added_script++;
+ + + - +
- ]
311 : 3180 : },
312 : 9194 : [&] {
313 : 9194 : CKey key;
314 [ + + ]: 9194 : if (!keys.empty()) {
315 [ + - ]: 8151 : key = PickValue(fuzzed_data_provider, keys);
316 : : } else {
317 : 1043 : key = ConsumePrivateKey(fuzzed_data_provider, /*compressed=*/fuzzed_data_provider.ConsumeBool());
318 : : }
319 [ + + ]: 9194 : if (!key.IsValid()) return;
320 : 9113 : const auto num_keys{fuzzed_data_provider.ConsumeIntegralInRange<size_t>(1, MAX_PUBKEYS_PER_MULTISIG)};
321 : 9113 : std::vector<CPubKey> pubkeys;
322 [ + - + - ]: 9113 : pubkeys.emplace_back(key.GetPubKey());
323 [ + + ]: 82307 : for (size_t i = 1; i < num_keys; i++) {
324 [ + + ]: 73398 : if (fuzzed_data_provider.ConsumeBool()) {
325 [ + - + - ]: 68887 : pubkeys.emplace_back(key.GetPubKey());
326 : : } else {
327 : 4511 : CKey private_key{ConsumePrivateKey(fuzzed_data_provider, /*compressed=*/fuzzed_data_provider.ConsumeBool())};
328 [ + + ]: 4511 : if (!private_key.IsValid()) return;
329 [ + - + - ]: 4307 : pubkeys.emplace_back(private_key.GetPubKey());
330 : 4511 : }
331 : : }
332 [ - + + - ]: 8909 : if (pubkeys.size() < num_keys) return;
333 [ + - ]: 8909 : CScript multisig_script{GetScriptForMultisig(num_keys, pubkeys)};
334 [ + - + - : 8909 : if (!legacy_data.HaveCScript(CScriptID(multisig_script)) && legacy_data.AddCScript(multisig_script)) {
+ + + - +
+ ]
335 : 6464 : added_script++;
336 : : }
337 : 9398 : }
338 : : );
339 : : }
340 : :
341 [ + - ]: 1418 : auto result{legacy_data.MigrateToDescriptor()};
342 [ - + ]: 1418 : assert(result);
343 [ + + + + ]: 1418 : if ((add_hd_chain && version >= CHDChain::VERSION_HD_CHAIN_SPLIT) || (!add_hd_chain && add_inactive_hd_chain)) {
344 : 465 : added_chains *= 2;
345 : : }
346 [ - + ]: 1418 : size_t added_size{keys.size() + added_chains};
347 [ + + ]: 1418 : if (added_script > 0) {
348 [ - + - + ]: 1327 : assert(result->desc_spkms.size() >= added_size);
349 : : } else {
350 [ - + - + ]: 91 : assert(result->desc_spkms.size() == added_size);
351 : : }
352 [ + - - + ]: 1418 : if (watch_only) assert(!result->watch_descs.empty());
353 [ + + - + ]: 1418 : if (!result->solvable_descs.empty()) assert(added_script > 0);
354 [ + - + - ]: 3066 : }
355 : :
356 : : } // namespace
357 : : } // namespace wallet
|