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 : 17036 : static std::optional<std::pair<WalletDescriptor, FlatSigningProvider>> CreateWalletDescriptor(FuzzedDataProvider& fuzzed_data_provider)
62 : : {
63 : 17036 : const std::string mocked_descriptor{fuzzed_data_provider.ConsumeRandomLengthString()};
64 [ - + + - ]: 17036 : const auto desc_str{MOCKED_DESC_CONVERTER.GetDescriptor(mocked_descriptor)};
65 [ + + ]: 17036 : if (!desc_str.has_value()) return std::nullopt;
66 [ + - + + ]: 16876 : if (IsTooExpensive(MakeUCharSpan(*desc_str))) return {};
67 : :
68 : 16860 : FlatSigningProvider keys;
69 [ + - ]: 16860 : std::string error;
70 [ + - - + : 16860 : std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str.value(), keys, error, false);
+ - ]
71 [ + + ]: 16860 : if (parsed_descs.empty()) return std::nullopt;
72 : :
73 : : // Verify expand succeeds before making WalletDescriptor
74 : : // Expansion results are not needed
75 : 14347 : FlatSigningProvider out_keys;
76 : 14347 : std::vector<CScript> scripts_temp;
77 : 14347 : DescriptorCache temp_cache;
78 [ + - + - : 14347 : if (!parsed_descs.at(0)->Expand(0, keys, scripts_temp, out_keys, &temp_cache)) return std::nullopt;
+ + ]
79 : :
80 [ + - + - : 14237 : WalletDescriptor w_desc{std::move(parsed_descs.at(0)), /*creation_time=*/0, /*range_start=*/0, /*range_end=*/1, /*next_index=*/1};
+ - ]
81 [ + - ]: 14237 : return std::make_pair(w_desc, keys);
82 : 33896 : }
83 : :
84 : 12012 : static DescriptorScriptPubKeyMan* CreateDescriptor(WalletDescriptor& wallet_desc, FlatSigningProvider& keys, CWallet& keystore)
85 : : {
86 : 12012 : LOCK(keystore.cs_wallet);
87 [ + - + - ]: 12012 : auto spk_manager_res = keystore.AddWalletDescriptor(wallet_desc, keys, /*label=*/"", /*internal=*/false);
88 [ + - ]: 12012 : if (!spk_manager_res) return nullptr;
89 : 12012 : return &spk_manager_res.value().get();
90 [ + - ]: 24024 : };
91 : :
92 [ + - ]: 14884 : FUZZ_TARGET(scriptpubkeyman, .init = initialize_spkm)
93 : : {
94 : 14408 : SeedRandomStateForTest(SeedRand::ZEROS);
95 : 14408 : FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
96 : 14408 : FakeNodeClock clock{ConsumeTime(fuzzed_data_provider)};
97 : 14408 : const auto& node{g_setup->m_node};
98 [ + - ]: 14408 : Chainstate& chainstate{node.chainman->ActiveChainstate()};
99 [ + - + - ]: 14408 : std::unique_ptr<CWallet> wallet_ptr{std::make_unique<CWallet>(node.chain.get(), "", CreateMockableWalletDatabase())};
100 [ + - ]: 14408 : CWallet& wallet{*wallet_ptr};
101 : 14408 : {
102 [ + - ]: 14408 : LOCK(wallet.cs_wallet);
103 [ + - ]: 14408 : wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
104 [ - + + - ]: 28816 : wallet.SetLastBlockProcessed(chainstate.m_chain.Height(), chainstate.m_chain.Tip()->GetBlockHash());
105 [ + - ]: 14408 : wallet.m_keypool_size = 1;
106 : 0 : }
107 : :
108 [ + - ]: 14408 : auto wallet_desc{CreateWalletDescriptor(fuzzed_data_provider)};
109 [ + + ]: 14408 : if (!wallet_desc.has_value()) return;
110 [ + - ]: 11887 : auto spk_manager{CreateDescriptor(wallet_desc->first, wallet_desc->second, wallet)};
111 [ + - ]: 11887 : if (spk_manager == nullptr) return;
112 : :
113 [ + + ]: 11887 : if (fuzzed_data_provider.ConsumeBool()) {
114 [ + - ]: 2628 : auto wallet_desc{CreateWalletDescriptor(fuzzed_data_provider)};
115 [ + + ]: 2628 : if (!wallet_desc.has_value()) {
116 : 278 : return;
117 : : }
118 [ + - ]: 2350 : std::string error;
119 [ + - + + ]: 2350 : if (spk_manager->CanUpdateToWalletDescriptor(wallet_desc->first, error)) {
120 [ + - ]: 125 : auto new_spk_manager{CreateDescriptor(wallet_desc->first, wallet_desc->second, wallet)};
121 [ + - ]: 125 : if (new_spk_manager != nullptr) spk_manager = new_spk_manager;
122 : : }
123 [ + - ]: 4978 : }
124 : :
125 : 11609 : bool good_data{true};
126 [ + + + + : 130435 : LIMITED_WHILE (good_data && fuzzed_data_provider.ConsumeBool(), 20) {
+ + ]
127 [ + - ]: 54885 : CallOneOf(
128 : : fuzzed_data_provider,
129 : 1974 : [&] {
130 : 1974 : const CScript script{ConsumeScript(fuzzed_data_provider)};
131 [ + - + + ]: 1974 : if (spk_manager->IsMine(script)) {
132 [ + - + - : 126 : assert(spk_manager->GetScriptPubKeys().contains(script));
- + ]
133 : : }
134 : 1974 : },
135 : 10549 : [&] {
136 : 10549 : auto spks{spk_manager->GetScriptPubKeys()};
137 [ + + + - ]: 44210 : for (const CScript& spk : spks) {
138 [ - + + - ]: 33661 : assert(spk_manager->IsMine(spk));
139 : 33661 : CTxDestination dest;
140 [ + - ]: 33661 : bool extract_dest{ExtractDestination(spk, dest)};
141 [ + + ]: 33661 : if (extract_dest) {
142 [ + - ]: 26284 : const std::string msg{fuzzed_data_provider.ConsumeRandomLengthString()};
143 [ + + + + ]: 26284 : PKHash pk_hash{std::get_if<PKHash>(&dest) && fuzzed_data_provider.ConsumeBool() ?
144 : 6244 : *std::get_if<PKHash>(&dest) :
145 : 26284 : PKHash{ConsumeUInt160(fuzzed_data_provider)}};
146 [ + - ]: 26284 : std::string str_sig;
147 [ + - ]: 26284 : (void)spk_manager->SignMessage(msg, pk_hash, str_sig);
148 [ + - ]: 26284 : (void)spk_manager->GetMetadata(dest);
149 : 26284 : }
150 : 33661 : }
151 : 10549 : },
152 : 4116 : [&] {
153 : 4116 : auto spks{spk_manager->GetScriptPubKeys()};
154 [ + + ]: 4116 : if (!spks.empty()) {
155 : 4060 : auto& spk{PickValue(fuzzed_data_provider, spks)};
156 [ + - ]: 4060 : (void)spk_manager->MarkUnusedAddresses(spk);
157 : : }
158 : 4116 : },
159 : 20812 : [&] {
160 : 20812 : LOCK(spk_manager->cs_desc_man);
161 [ + - ]: 20812 : auto wallet_desc{spk_manager->GetWalletDescriptor()};
162 [ + - + + ]: 20812 : if (wallet_desc.descriptor->IsSingleType()) {
163 [ + - ]: 20548 : auto output_type{wallet_desc.descriptor->GetOutputType()};
164 [ + + ]: 20548 : if (output_type.has_value()) {
165 [ + - ]: 16854 : auto dest{spk_manager->GetNewDestination(*output_type)};
166 [ + + ]: 16854 : if (dest) {
167 [ + - - + ]: 15582 : assert(IsValidDestination(*dest));
168 [ + - - + ]: 15582 : assert(spk_manager->IsHDEnabled());
169 : : }
170 : 16854 : }
171 : : }
172 [ + - ]: 41624 : },
173 : 6326 : [&] {
174 : 6326 : CMutableTransaction tx_to;
175 : 6326 : const std::optional<CMutableTransaction> opt_tx_to{ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS)};
176 [ + + ]: 6326 : if (!opt_tx_to) {
177 : 256 : good_data = false;
178 [ - + ]: 256 : return;
179 : : }
180 [ + - ]: 6070 : tx_to = *opt_tx_to;
181 : :
182 : 6070 : std::map<COutPoint, Coin> coins{ConsumeCoins(fuzzed_data_provider)};
183 : 6070 : const int sighash{fuzzed_data_provider.ConsumeIntegral<int>()};
184 [ + - ]: 6070 : std::map<int, bilingual_str> input_errors;
185 [ + - ]: 6070 : (void)spk_manager->SignTransaction(tx_to, coins, sighash, input_errors);
186 [ + - ]: 18722 : },
187 : 11108 : [&] {
188 : 11108 : std::optional<PartiallySignedTransaction> opt_psbt{ConsumeDeserializableConstructor<PartiallySignedTransaction>(fuzzed_data_provider)};
189 [ + + ]: 11108 : if (!opt_psbt) {
190 : 2297 : good_data = false;
191 : 2297 : return;
192 : : }
193 [ + - ]: 8811 : auto psbt{*opt_psbt};
194 [ + - ]: 8811 : std::optional<PrecomputedTransactionData> txdata_res = PrecomputePSBTData(psbt);
195 [ - + ]: 8811 : if (!txdata_res) {
196 : 0 : return;
197 : : }
198 : 8811 : const PrecomputedTransactionData& txdata = *txdata_res;
199 : 8811 : common::PSBTFillOptions options{
200 : 8811 : .sign = fuzzed_data_provider.ConsumeBool(),
201 : 8811 : .sighash_type = fuzzed_data_provider.ConsumeIntegralInRange<int>(0, 151),
202 : 17622 : .finalize = fuzzed_data_provider.ConsumeBool(),
203 : 17622 : .bip32_derivs = fuzzed_data_provider.ConsumeBool()
204 : 8811 : };
205 [ + - ]: 8818 : if (options.sighash_type == 151) options.sighash_type = std::nullopt;
206 [ + - ]: 8811 : (void)spk_manager->FillPSBT(psbt, txdata, options);
207 : 11108 : }
208 : : );
209 : : }
210 : :
211 : 11609 : std::string descriptor;
212 [ + - ]: 11609 : (void)spk_manager->GetDescriptorString(descriptor, /*priv=*/fuzzed_data_provider.ConsumeBool());
213 [ + - ]: 11609 : (void)spk_manager->GetEndRange();
214 [ + - ]: 11609 : (void)spk_manager->GetKeyPoolSize();
215 [ + - + - : 40425 : }
+ - ]
216 : :
217 [ + - ]: 2766 : FUZZ_TARGET(spkm_migration, .init = initialize_spkm_migration)
218 : : {
219 : 2290 : SeedRandomStateForTest(SeedRand::ZEROS);
220 : 2290 : FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
221 : 2290 : FakeNodeClock clock{ConsumeTime(fuzzed_data_provider)};
222 : 2290 : const auto& node{g_setup->m_node};
223 [ + - ]: 2290 : Chainstate& chainstate{node.chainman->ActiveChainstate()};
224 : :
225 [ + - + - ]: 2290 : std::unique_ptr<CWallet> wallet_ptr{std::make_unique<CWallet>(node.chain.get(), "", CreateMockableWalletDatabase())};
226 [ + - ]: 2290 : CWallet& wallet{*wallet_ptr};
227 : 2290 : wallet.m_keypool_size = 1;
228 : 2290 : {
229 [ + - ]: 2290 : LOCK(wallet.cs_wallet);
230 [ + - ]: 2290 : wallet.UnsetWalletFlag(WALLET_FLAG_DESCRIPTORS);
231 [ - + + - ]: 4580 : wallet.SetLastBlockProcessed(chainstate.m_chain.Height(), chainstate.m_chain.Tip()->GetBlockHash());
232 : 0 : }
233 : :
234 [ + - ]: 2290 : auto& legacy_data{*wallet.GetOrCreateLegacyDataSPKM()};
235 : :
236 : 2290 : std::vector<CKey> keys;
237 [ + + + + ]: 12493 : LIMITED_WHILE (fuzzed_data_provider.ConsumeBool(), 30) {
238 : 10209 : const auto key{ConsumePrivateKey(fuzzed_data_provider)};
239 [ + + ]: 10209 : if (!key.IsValid()) return;
240 [ + - ]: 10203 : auto pub_key{key.GetPubKey()};
241 [ + - + - ]: 10203 : if (!pub_key.IsFullyValid()) return;
242 [ + - + - : 10203 : if (legacy_data.LoadKey(key, pub_key) && std::find(keys.begin(), keys.end(), key) == keys.end()) keys.push_back(key);
+ + + - ]
243 : 10209 : }
244 : :
245 : 2284 : size_t added_chains = 0;
246 [ + + + + ]: 2284 : bool add_hd_chain{fuzzed_data_provider.ConsumeBool() && !keys.empty()};
247 : 2284 : CHDChain hd_chain;
248 [ + + ]: 2284 : auto version{fuzzed_data_provider.ConsumeBool() ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE};
249 : 2284 : CKey hd_key;
250 [ + + ]: 2284 : if (add_hd_chain) {
251 [ + - ]: 688 : hd_key = PickValue(fuzzed_data_provider, keys);
252 : 688 : hd_chain.nVersion = version;
253 [ + - + - ]: 688 : hd_chain.seed_id = hd_key.GetPubKey().GetID();
254 [ + - ]: 688 : legacy_data.LoadHDChain(hd_chain);
255 : : added_chains++;
256 : : }
257 : :
258 [ + + + + ]: 2284 : bool add_inactive_hd_chain{fuzzed_data_provider.ConsumeBool() && !keys.empty()};
259 : 680 : if (add_inactive_hd_chain) {
260 [ + - ]: 680 : CKey inactive_hd_key = PickValue(fuzzed_data_provider, keys);
261 [ + + ]: 680 : hd_chain.nVersion = fuzzed_data_provider.ConsumeBool() ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
262 [ + + + + ]: 1257 : bool dup_chain = hd_key.IsValid() && std::equal(hd_key.begin(), hd_key.end(), inactive_hd_key.begin());
263 [ + - + - ]: 680 : hd_chain.seed_id = inactive_hd_key.GetPubKey().GetID();
264 [ + - ]: 680 : legacy_data.AddInactiveHDChain(hd_chain);
265 [ + + ]: 680 : if (!dup_chain) added_chains++;
266 : 680 : }
267 : :
268 : 2284 : bool watch_only = false;
269 : 2284 : const auto pub_key = ConsumeDeserializable<CPubKey>(fuzzed_data_provider);
270 [ + + + - : 2284 : if (!pub_key || !pub_key->IsFullyValid()) return;
+ + ]
271 [ + - + - ]: 2150 : auto script_dest{GetScriptForDestination(WitnessV0KeyHash{*pub_key})};
272 [ + + ]: 2150 : if (fuzzed_data_provider.ConsumeBool()) {
273 [ + - + - ]: 2444 : script_dest = GetScriptForDestination(CTxDestination{PKHash(*pub_key)});
274 : : }
275 [ + - + - ]: 2150 : if (legacy_data.LoadWatchOnly(script_dest)) watch_only = true;
276 : :
277 : 2150 : size_t added_script{0};
278 : 2150 : bool good_data{true};
279 [ + + + + : 42407 : LIMITED_WHILE (good_data && fuzzed_data_provider.ConsumeBool(), 30) {
+ + ]
280 [ + - ]: 19096 : CallOneOf(
281 : : fuzzed_data_provider,
282 : 5608 : [&] {
283 : 5608 : CKey key;
284 [ + + ]: 5608 : if (!keys.empty()) {
285 [ + - ]: 1465 : key = PickValue(fuzzed_data_provider, keys);
286 : : } else {
287 : 4143 : key = ConsumePrivateKey(fuzzed_data_provider, /*compressed=*/fuzzed_data_provider.ConsumeBool());
288 : : }
289 [ + + ]: 5608 : if (!key.IsValid()) return;
290 [ + - ]: 5545 : auto pub_key{key.GetPubKey()};
291 : 5545 : CScript script;
292 [ + - ]: 5545 : CallOneOf(
293 : : fuzzed_data_provider,
294 : 1144 : [&] {
295 [ + - ]: 1144 : script = GetScriptForDestination(CTxDestination{PKHash(pub_key)});
296 : 1144 : },
297 : 843 : [&] {
298 [ + - ]: 843 : script = GetScriptForDestination(WitnessV0KeyHash(pub_key));
299 : 843 : },
300 : 3558 : [&] {
301 : 3558 : std::optional<CScript> script_opt{ConsumeDeserializable<CScript>(fuzzed_data_provider)};
302 [ + + ]: 3558 : if (!script_opt) {
303 : 85 : good_data = false;
304 : 85 : return;
305 : : }
306 : 3473 : script = script_opt.value();
307 : 3558 : }
308 : : );
309 [ + + + - : 7036 : if (fuzzed_data_provider.ConsumeBool()) script = GetScriptForDestination(ScriptHash(script));
+ - ]
310 [ + - + - : 5545 : if (!legacy_data.HaveCScript(CScriptID(script)) && legacy_data.AddCScript(script)) added_script++;
+ + + - +
+ ]
311 : 5608 : },
312 : 13488 : [&] {
313 : 13488 : CKey key;
314 [ + + ]: 13488 : if (!keys.empty()) {
315 [ + - ]: 11821 : key = PickValue(fuzzed_data_provider, keys);
316 : : } else {
317 : 1667 : key = ConsumePrivateKey(fuzzed_data_provider, /*compressed=*/fuzzed_data_provider.ConsumeBool());
318 : : }
319 [ + + ]: 13488 : if (!key.IsValid()) return;
320 : 13383 : const auto num_keys{fuzzed_data_provider.ConsumeIntegralInRange<size_t>(1, MAX_PUBKEYS_PER_MULTISIG)};
321 : 13383 : std::vector<CPubKey> pubkeys;
322 [ + - + - ]: 13383 : pubkeys.emplace_back(key.GetPubKey());
323 [ + + ]: 116272 : for (size_t i = 1; i < num_keys; i++) {
324 [ + + ]: 103204 : if (fuzzed_data_provider.ConsumeBool()) {
325 [ + - + - ]: 96106 : pubkeys.emplace_back(key.GetPubKey());
326 : : } else {
327 : 7098 : CKey private_key{ConsumePrivateKey(fuzzed_data_provider, /*compressed=*/fuzzed_data_provider.ConsumeBool())};
328 [ + + ]: 7098 : if (!private_key.IsValid()) return;
329 [ + - + - ]: 6783 : pubkeys.emplace_back(private_key.GetPubKey());
330 : 7098 : }
331 : : }
332 [ - + + - ]: 13068 : if (pubkeys.size() < num_keys) return;
333 [ + - ]: 13068 : CScript multisig_script{GetScriptForMultisig(num_keys, pubkeys)};
334 [ + - + - : 13068 : if (!legacy_data.HaveCScript(CScriptID(multisig_script)) && legacy_data.AddCScript(multisig_script)) {
+ + + - +
+ ]
335 : 9686 : added_script++;
336 : : }
337 : 13803 : }
338 : : );
339 : : }
340 : :
341 [ + - ]: 2150 : auto result{legacy_data.MigrateToDescriptor()};
342 [ - + ]: 2150 : assert(result);
343 [ + + + + ]: 2150 : if ((add_hd_chain && version >= CHDChain::VERSION_HD_CHAIN_SPLIT) || (!add_hd_chain && add_inactive_hd_chain)) {
344 : 672 : added_chains *= 2;
345 : : }
346 [ - + ]: 2150 : size_t added_size{keys.size() + added_chains};
347 [ + + ]: 2150 : if (added_script > 0) {
348 [ - + - + ]: 2017 : assert(result->desc_spkms.size() >= added_size);
349 : : } else {
350 [ - + - + ]: 133 : assert(result->desc_spkms.size() == added_size);
351 : : }
352 [ + - - + ]: 2150 : if (watch_only) assert(!result->watch_descs.empty());
353 [ + + - + ]: 2150 : if (!result->solvable_descs.empty()) assert(added_script > 0);
354 [ + - + - ]: 4580 : }
355 : :
356 : : } // namespace
357 : : } // namespace wallet
|