Bitcoin Core 31.99.0
P2P Digital Currency
scriptpubkeyman.cpp
Go to the documentation of this file.
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>
10#include <psbt.h>
11#include <script/descriptor.h>
12#include <script/interpreter.h>
13#include <script/script.h>
15#include <sync.h>
17#include <test/fuzz/fuzz.h>
18#include <test/fuzz/util.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>
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
41namespace wallet {
42namespace {
44
47
48void initialize_spkm()
49{
50 static const auto testing_setup{MakeNoLogFileContext<const TestingSetup>()};
51 g_setup = testing_setup.get();
53}
54
55void initialize_spkm_migration()
56{
57 static const auto testing_setup{MakeNoLogFileContext<const TestingSetup>()};
58 g_setup = testing_setup.get();
59}
60
61static std::optional<std::pair<WalletDescriptor, FlatSigningProvider>> CreateWalletDescriptor(FuzzedDataProvider& fuzzed_data_provider)
62{
63 const std::string mocked_descriptor{fuzzed_data_provider.ConsumeRandomLengthString()};
64 const auto desc_str{MOCKED_DESC_CONVERTER.GetDescriptor(mocked_descriptor)};
65 if (!desc_str.has_value()) return std::nullopt;
66 if (IsTooExpensive(MakeUCharSpan(*desc_str))) return {};
67
69 std::string error;
70 std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str.value(), keys, error, false);
71 if (parsed_descs.empty()) return std::nullopt;
72
73 WalletDescriptor w_desc{std::move(parsed_descs.at(0)), /*creation_time=*/0, /*range_start=*/0, /*range_end=*/1, /*next_index=*/1};
74 return std::make_pair(w_desc, keys);
75}
76
77static DescriptorScriptPubKeyMan* CreateDescriptor(WalletDescriptor& wallet_desc, FlatSigningProvider& keys, CWallet& keystore)
78{
79 LOCK(keystore.cs_wallet);
80 auto spk_manager_res = keystore.AddWalletDescriptor(wallet_desc, keys, /*label=*/"", /*internal=*/false);
81 if (!spk_manager_res) return nullptr;
82 return &spk_manager_res.value().get();
83};
84
85FUZZ_TARGET(scriptpubkeyman, .init = initialize_spkm)
86{
88 FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
90 const auto& node{g_setup->m_node};
91 Chainstate& chainstate{node.chainman->ActiveChainstate()};
92 std::unique_ptr<CWallet> wallet_ptr{std::make_unique<CWallet>(node.chain.get(), "", CreateMockableWalletDatabase())};
93 CWallet& wallet{*wallet_ptr};
94 {
95 LOCK(wallet.cs_wallet);
96 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
97 wallet.SetLastBlockProcessed(chainstate.m_chain.Height(), chainstate.m_chain.Tip()->GetBlockHash());
98 wallet.m_keypool_size = 1;
99 }
100
101 auto wallet_desc{CreateWalletDescriptor(fuzzed_data_provider)};
102 if (!wallet_desc.has_value()) return;
103 auto spk_manager{CreateDescriptor(wallet_desc->first, wallet_desc->second, wallet)};
104 if (spk_manager == nullptr) return;
105
107 auto wallet_desc{CreateWalletDescriptor(fuzzed_data_provider)};
108 if (!wallet_desc.has_value()) {
109 return;
110 }
111 std::string error;
112 if (spk_manager->CanUpdateToWalletDescriptor(wallet_desc->first, error)) {
113 auto new_spk_manager{CreateDescriptor(wallet_desc->first, wallet_desc->second, wallet)};
114 if (new_spk_manager != nullptr) spk_manager = new_spk_manager;
115 }
116 }
117
118 bool good_data{true};
120 CallOneOf(
122 [&] {
124 if (spk_manager->IsMine(script)) {
125 assert(spk_manager->GetScriptPubKeys().contains(script));
126 }
127 },
128 [&] {
129 auto spks{spk_manager->GetScriptPubKeys()};
130 for (const CScript& spk : spks) {
131 assert(spk_manager->IsMine(spk));
132 CTxDestination dest;
133 bool extract_dest{ExtractDestination(spk, dest)};
134 if (extract_dest) {
136 PKHash pk_hash{std::get_if<PKHash>(&dest) && fuzzed_data_provider.ConsumeBool() ?
137 *std::get_if<PKHash>(&dest) :
139 std::string str_sig;
140 (void)spk_manager->SignMessage(msg, pk_hash, str_sig);
141 (void)spk_manager->GetMetadata(dest);
142 }
143 }
144 },
145 [&] {
146 auto spks{spk_manager->GetScriptPubKeys()};
147 if (!spks.empty()) {
148 auto& spk{PickValue(fuzzed_data_provider, spks)};
149 (void)spk_manager->MarkUnusedAddresses(spk);
150 }
151 },
152 [&] {
153 LOCK(spk_manager->cs_desc_man);
154 auto wallet_desc{spk_manager->GetWalletDescriptor()};
155 if (wallet_desc.descriptor->IsSingleType()) {
156 auto output_type{wallet_desc.descriptor->GetOutputType()};
157 if (output_type.has_value()) {
158 auto dest{spk_manager->GetNewDestination(*output_type)};
159 if (dest) {
161 assert(spk_manager->IsHDEnabled());
162 }
163 }
164 }
165 },
166 [&] {
168 const std::optional<CMutableTransaction> opt_tx_to{ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS)};
169 if (!opt_tx_to) {
170 good_data = false;
171 return;
172 }
173 tx_to = *opt_tx_to;
174
175 std::map<COutPoint, Coin> coins{ConsumeCoins(fuzzed_data_provider)};
176 const int sighash{fuzzed_data_provider.ConsumeIntegral<int>()};
177 std::map<int, bilingual_str> input_errors;
178 (void)spk_manager->SignTransaction(tx_to, coins, sighash, input_errors);
179 },
180 [&] {
181 std::optional<PartiallySignedTransaction> opt_psbt{ConsumeDeserializableConstructor<PartiallySignedTransaction>(fuzzed_data_provider)};
182 if (!opt_psbt) {
183 good_data = false;
184 return;
185 }
186 auto psbt{*opt_psbt};
187 std::optional<PrecomputedTransactionData> txdata_res = PrecomputePSBTData(psbt);
188 if (!txdata_res) {
189 return;
190 }
191 const PrecomputedTransactionData& txdata = *txdata_res;
194 .sighash_type = fuzzed_data_provider.ConsumeIntegralInRange<int>(0, 151),
195 .finalize = fuzzed_data_provider.ConsumeBool(),
196 .bip32_derivs = fuzzed_data_provider.ConsumeBool()
197 };
198 if (options.sighash_type == 151) options.sighash_type = std::nullopt;
199 (void)spk_manager->FillPSBT(psbt, txdata, options);
200 }
201 );
202 }
203
204 std::string descriptor;
205 (void)spk_manager->GetDescriptorString(descriptor, /*priv=*/fuzzed_data_provider.ConsumeBool());
206 (void)spk_manager->GetEndRange();
207 (void)spk_manager->GetKeyPoolSize();
208}
209
210FUZZ_TARGET(spkm_migration, .init = initialize_spkm_migration)
211{
213 FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
215 const auto& node{g_setup->m_node};
216 Chainstate& chainstate{node.chainman->ActiveChainstate()};
217
218 std::unique_ptr<CWallet> wallet_ptr{std::make_unique<CWallet>(node.chain.get(), "", CreateMockableWalletDatabase())};
219 CWallet& wallet{*wallet_ptr};
220 wallet.m_keypool_size = 1;
221 {
222 LOCK(wallet.cs_wallet);
223 wallet.UnsetWalletFlag(WALLET_FLAG_DESCRIPTORS);
224 wallet.SetLastBlockProcessed(chainstate.m_chain.Height(), chainstate.m_chain.Tip()->GetBlockHash());
225 }
226
227 auto& legacy_data{*wallet.GetOrCreateLegacyDataSPKM()};
228
229 std::vector<CKey> keys;
232 if (!key.IsValid()) return;
233 auto pub_key{key.GetPubKey()};
234 if (!pub_key.IsFullyValid()) return;
235 if (legacy_data.LoadKey(key, pub_key) && std::find(keys.begin(), keys.end(), key) == keys.end()) keys.push_back(key);
236 }
237
238 bool add_hd_chain{fuzzed_data_provider.ConsumeBool() && !keys.empty()};
239 CHDChain hd_chain;
241 CKey hd_key;
242 if (add_hd_chain) {
243 hd_key = PickValue(fuzzed_data_provider, keys);
244 hd_chain.nVersion = version;
245 hd_chain.seed_id = hd_key.GetPubKey().GetID();
246 legacy_data.LoadHDChain(hd_chain);
247 }
248
249 bool add_inactive_hd_chain{fuzzed_data_provider.ConsumeBool() && !keys.empty()};
250 if (add_inactive_hd_chain) {
251 hd_key = PickValue(fuzzed_data_provider, keys);
253 hd_chain.seed_id = hd_key.GetPubKey().GetID();
254 legacy_data.AddInactiveHDChain(hd_chain);
255 }
256
257 bool watch_only = false;
258 const auto pub_key = ConsumeDeserializable<CPubKey>(fuzzed_data_provider);
259 if (!pub_key || !pub_key->IsFullyValid()) return;
260 auto script_dest{GetScriptForDestination(WitnessV0KeyHash{*pub_key})};
262 script_dest = GetScriptForDestination(CTxDestination{PKHash(*pub_key)});
263 }
264 if (legacy_data.LoadWatchOnly(script_dest)) watch_only = true;
265
266 size_t added_script{0};
267 bool good_data{true};
269 CallOneOf(
271 [&] {
272 CKey key;
273 if (!keys.empty()) {
274 key = PickValue(fuzzed_data_provider, keys);
275 } else {
276 key = ConsumePrivateKey(fuzzed_data_provider, /*compressed=*/fuzzed_data_provider.ConsumeBool());
277 }
278 if (!key.IsValid()) return;
279 auto pub_key{key.GetPubKey()};
281 CallOneOf(
283 [&] {
285 },
286 [&] {
288 },
289 [&] {
290 std::optional<CScript> script_opt{ConsumeDeserializable<CScript>(fuzzed_data_provider)};
291 if (!script_opt) {
292 good_data = false;
293 return;
294 }
295 script = script_opt.value();
296 }
297 );
299 if (!legacy_data.HaveCScript(CScriptID(script)) && legacy_data.AddCScript(script)) added_script++;
300 },
301 [&] {
302 CKey key;
303 if (!keys.empty()) {
304 key = PickValue(fuzzed_data_provider, keys);
305 } else {
307 }
308 if (!key.IsValid()) return;
310 std::vector<CPubKey> pubkeys;
311 pubkeys.emplace_back(key.GetPubKey());
312 for (size_t i = 1; i < num_keys; i++) {
314 pubkeys.emplace_back(key.GetPubKey());
315 } else {
317 if (!private_key.IsValid()) return;
318 pubkeys.emplace_back(private_key.GetPubKey());
319 }
320 }
321 if (pubkeys.size() < num_keys) return;
322 CScript multisig_script{GetScriptForMultisig(num_keys, pubkeys)};
323 if (!legacy_data.HaveCScript(CScriptID(multisig_script)) && legacy_data.AddCScript(multisig_script)) {
324 added_script++;
325 }
326 }
327 );
328 }
329
330 auto result{legacy_data.MigrateToDescriptor()};
331 assert(result);
332 size_t added_chains{static_cast<size_t>(add_hd_chain) + static_cast<size_t>(add_inactive_hd_chain)};
333 if ((add_hd_chain && version >= CHDChain::VERSION_HD_CHAIN_SPLIT) || (!add_hd_chain && add_inactive_hd_chain)) {
334 added_chains *= 2;
335 }
336 size_t added_size{keys.size() + added_chains};
337 if (added_script > 0) {
338 assert(result->desc_spkms.size() >= added_size);
339 } else {
340 assert(result->desc_spkms.size() == added_size);
341 }
342 if (watch_only) assert(!result->watch_descs.empty());
343 if (!result->solvable_descs.empty()) assert(added_script > 0);
344}
345
346} // namespace
347} // namespace wallet
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a scriptPubKey for the destination.
Definition: addresstype.cpp:49
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination corresponds to one with an address.
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, PayToAnchor, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
Definition: addresstype.h:143
if(!SetupNetworking())
const TestingSetup * g_setup
An encapsulated private key.
Definition: key.h:36
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:124
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:183
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:160
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:405
A reference to a CScript: the Hash160 of its serialization.
Definition: script.h:596
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:551
std::string ConsumeRandomLengthString(size_t max_length)
T ConsumeIntegralInRange(T min, T max)
Converts a mocked descriptor string to a valid one.
Definition: descriptor.h:23
void Init()
When initializing the target, populate the list of keys.
Definition: descriptor.cpp:17
std::optional< std::string > GetDescriptor(std::string_view mocked_desc) const
Get an actual descriptor string from a descriptor string whose keys were mocked.
Definition: descriptor.cpp:59
Helper to initialize the global NodeClock, let a duration elapse, and reset it after use in a test.
Definition: time.h:40
static const int VERSION_HD_BASE
Definition: walletdb.h:102
static const int VERSION_HD_CHAIN_SPLIT
Definition: walletdb.h:103
static UniValue Parse(std::string_view raw, ParamFormat format=ParamFormat::JSON)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
Definition: client.cpp:400
MockedDescriptorConverter MOCKED_DESC_CONVERTER
The converter of mocked descriptors, needs to be initialized when the target is.
#define LIMITED_WHILE(condition, limit)
Can be used to limit a theoretically unbounded loop.
Definition: fuzz.h:22
Definition: basic.cpp:8
Definition: messages.h:21
wallet::DescriptorScriptPubKeyMan * CreateDescriptor(CWallet &keystore, const std::string &desc_str, const bool success)
Definition: util.cpp:127
std::unique_ptr< WalletDatabase > CreateMockableWalletDatabase()
Definition: util.cpp:122
FUZZ_TARGET(coin_grinder)
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:53
static constexpr TransactionSerParams TX_WITH_WITNESS
Definition: transaction.h:180
std::optional< PrecomputedTransactionData > PrecomputePSBTData(const PartiallySignedTransaction &psbt)
Compute a PrecomputedTransactionData object from a psbt.
Definition: psbt.cpp:623
static const int MAX_PUBKEYS_PER_MULTISIG
Definition: script.h:34
CScript GetScriptForMultisig(int nRequired, const std::vector< CPubKey > &keys)
Generate a multisig script.
Definition: solver.cpp:218
constexpr auto MakeUCharSpan(const V &v) -> decltype(UCharSpanCast(std::span{v}))
Like the std::span constructor, but for (const) unsigned char member types only.
Definition: span.h:111
node::NodeContext m_node
Definition: setup_common.h:63
A mutable version of CTransaction.
Definition: transaction.h:358
Testing setup that configures a complete environment.
Definition: setup_common.h:118
Instructions for how a PSBT should be signed or filled with information.
Definition: types.h:32
bool sign
Whether to sign or not.
Definition: types.h:36
#define LOCK(cs)
Definition: sync.h:268
bool IsTooExpensive(std::span< const uint8_t > buffer)
Deriving "expensive" descriptors will consume useful fuzz compute. The compute is better spent on a s...
Definition: descriptor.h:94
NodeSeconds ConsumeTime(FuzzedDataProvider &fuzzed_data_provider, const std::optional< int64_t > &min, const std::optional< int64_t > &max) noexcept
Definition: util.cpp:34
CScript ConsumeScript(FuzzedDataProvider &fuzzed_data_provider, const bool maybe_p2wsh) noexcept
Definition: util.cpp:93
CKey ConsumePrivateKey(FuzzedDataProvider &fuzzed_data_provider, std::optional< bool > compressed) noexcept
Definition: util.cpp:230
std::map< COutPoint, Coin > ConsumeCoins(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: util.cpp:166
auto & PickValue(FuzzedDataProvider &fuzzed_data_provider, Collection &col)
Definition: util.h:49
size_t CallOneOf(FuzzedDataProvider &fuzzed_data_provider, Callables... callables)
Definition: util.h:37
uint160 ConsumeUInt160(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: util.h:182
void SeedRandomStateForTest(SeedRand seedtype)
Seed the global RNG state for testing and log the seed value.
Definition: random.cpp:19
@ ZEROS
Seed with a compile time constant of zeros.
assert(!tx.IsCoinBase())
FuzzedDataProvider & fuzzed_data_provider
Definition: fees.cpp:39
is a home for public enum and struct type definitions that are used by internally by wallet code,...