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{ConsumeDeserializable<PartiallySignedTransaction>(fuzzed_data_provider)};
182 if (!opt_psbt) {
183 good_data = false;
184 return;
185 }
186 auto psbt{*opt_psbt};
188 std::optional<int> sighash_type{fuzzed_data_provider.ConsumeIntegralInRange<int>(0, 151)};
189 if (sighash_type == 151) sighash_type = std::nullopt;
191 auto bip32derivs = fuzzed_data_provider.ConsumeBool();
192 auto finalize = fuzzed_data_provider.ConsumeBool();
193 (void)spk_manager->FillPSBT(psbt, txdata, sighash_type, sign, bip32derivs, nullptr, finalize);
194 }
195 );
196 }
197
198 std::string descriptor;
199 (void)spk_manager->GetDescriptorString(descriptor, /*priv=*/fuzzed_data_provider.ConsumeBool());
200 (void)spk_manager->GetEndRange();
201 (void)spk_manager->GetKeyPoolSize();
202}
203
204FUZZ_TARGET(spkm_migration, .init = initialize_spkm_migration)
205{
207 FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
209 const auto& node{g_setup->m_node};
210 Chainstate& chainstate{node.chainman->ActiveChainstate()};
211
212 std::unique_ptr<CWallet> wallet_ptr{std::make_unique<CWallet>(node.chain.get(), "", CreateMockableWalletDatabase())};
213 CWallet& wallet{*wallet_ptr};
214 wallet.m_keypool_size = 1;
215 {
216 LOCK(wallet.cs_wallet);
217 wallet.UnsetWalletFlag(WALLET_FLAG_DESCRIPTORS);
218 wallet.SetLastBlockProcessed(chainstate.m_chain.Height(), chainstate.m_chain.Tip()->GetBlockHash());
219 }
220
221 auto& legacy_data{*wallet.GetOrCreateLegacyDataSPKM()};
222
223 std::vector<CKey> keys;
226 if (!key.IsValid()) return;
227 auto pub_key{key.GetPubKey()};
228 if (!pub_key.IsFullyValid()) return;
229 if (legacy_data.LoadKey(key, pub_key) && std::find(keys.begin(), keys.end(), key) == keys.end()) keys.push_back(key);
230 }
231
232 bool add_hd_chain{fuzzed_data_provider.ConsumeBool() && !keys.empty()};
233 CHDChain hd_chain;
235 CKey hd_key;
236 if (add_hd_chain) {
237 hd_key = PickValue(fuzzed_data_provider, keys);
238 hd_chain.nVersion = version;
239 hd_chain.seed_id = hd_key.GetPubKey().GetID();
240 legacy_data.LoadHDChain(hd_chain);
241 }
242
243 bool add_inactive_hd_chain{fuzzed_data_provider.ConsumeBool() && !keys.empty()};
244 if (add_inactive_hd_chain) {
245 hd_key = PickValue(fuzzed_data_provider, keys);
247 hd_chain.seed_id = hd_key.GetPubKey().GetID();
248 legacy_data.AddInactiveHDChain(hd_chain);
249 }
250
251 bool watch_only = false;
252 const auto pub_key = ConsumeDeserializable<CPubKey>(fuzzed_data_provider);
253 if (!pub_key || !pub_key->IsFullyValid()) return;
254 auto script_dest{GetScriptForDestination(WitnessV0KeyHash{*pub_key})};
256 script_dest = GetScriptForDestination(CTxDestination{PKHash(*pub_key)});
257 }
258 if (legacy_data.LoadWatchOnly(script_dest)) watch_only = true;
259
260 size_t added_script{0};
261 bool good_data{true};
263 CallOneOf(
265 [&] {
266 CKey key;
267 if (!keys.empty()) {
268 key = PickValue(fuzzed_data_provider, keys);
269 } else {
270 key = ConsumePrivateKey(fuzzed_data_provider, /*compressed=*/fuzzed_data_provider.ConsumeBool());
271 }
272 if (!key.IsValid()) return;
273 auto pub_key{key.GetPubKey()};
275 CallOneOf(
277 [&] {
279 },
280 [&] {
282 },
283 [&] {
284 std::optional<CScript> script_opt{ConsumeDeserializable<CScript>(fuzzed_data_provider)};
285 if (!script_opt) {
286 good_data = false;
287 return;
288 }
289 script = script_opt.value();
290 }
291 );
293 if (!legacy_data.HaveCScript(CScriptID(script)) && legacy_data.AddCScript(script)) added_script++;
294 },
295 [&] {
296 CKey key;
297 if (!keys.empty()) {
298 key = PickValue(fuzzed_data_provider, keys);
299 } else {
301 }
302 if (!key.IsValid()) return;
304 std::vector<CPubKey> pubkeys;
305 pubkeys.emplace_back(key.GetPubKey());
306 for (size_t i = 1; i < num_keys; i++) {
308 pubkeys.emplace_back(key.GetPubKey());
309 } else {
311 if (!private_key.IsValid()) return;
312 pubkeys.emplace_back(private_key.GetPubKey());
313 }
314 }
315 if (pubkeys.size() < num_keys) return;
316 CScript multisig_script{GetScriptForMultisig(num_keys, pubkeys)};
317 if (!legacy_data.HaveCScript(CScriptID(multisig_script)) && legacy_data.AddCScript(multisig_script)) {
318 added_script++;
319 }
320 }
321 );
322 }
323
324 auto result{legacy_data.MigrateToDescriptor()};
325 assert(result);
326 size_t added_chains{static_cast<size_t>(add_hd_chain) + static_cast<size_t>(add_inactive_hd_chain)};
327 if ((add_hd_chain && version >= CHDChain::VERSION_HD_CHAIN_SPLIT) || (!add_hd_chain && add_inactive_hd_chain)) {
328 added_chains *= 2;
329 }
330 size_t added_size{keys.size() + added_chains};
331 if (added_script > 0) {
332 assert(result->desc_spkms.size() >= added_size);
333 } else {
334 assert(result->desc_spkms.size() == added_size);
335 }
336 if (watch_only) assert(!result->watch_descs.empty());
337 if (!result->solvable_descs.empty()) assert(added_script > 0);
338}
339
340} // namespace
341} // 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:594
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:395
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
static int sign(const secp256k1_context *ctx, struct signer_secrets *signer_secrets, struct signer *signer, const secp256k1_musig_keyagg_cache *cache, const unsigned char *msg32, unsigned char *sig64)
Definition: musig.c:106
Definition: messages.h:21
wallet::DescriptorScriptPubKeyMan * CreateDescriptor(CWallet &keystore, const std::string &desc_str, const bool success)
Definition: util.cpp:221
FUZZ_TARGET(coin_grinder)
std::unique_ptr< WalletDatabase > CreateMockableWalletDatabase(MockableData records)
Definition: util.cpp:211
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:53
static constexpr TransactionSerParams TX_WITH_WITNESS
Definition: transaction.h:180
PrecomputedTransactionData PrecomputePSBTData(const PartiallySignedTransaction &psbt)
Compute a PrecomputedTransactionData object from a psbt.
Definition: psbt.cpp:385
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:66
A mutable version of CTransaction.
Definition: transaction.h:358
Testing setup that configures a complete environment.
Definition: setup_common.h:121
#define LOCK(cs)
Definition: sync.h:266
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:98
CKey ConsumePrivateKey(FuzzedDataProvider &fuzzed_data_provider, std::optional< bool > compressed) noexcept
Definition: util.cpp:235
std::map< COutPoint, Coin > ConsumeCoins(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: util.cpp:171
auto & PickValue(FuzzedDataProvider &fuzzed_data_provider, Collection &col)
Definition: util.h:47
size_t CallOneOf(FuzzedDataProvider &fuzzed_data_provider, Callables... callables)
Definition: util.h:35
uint160 ConsumeUInt160(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: util.h:158
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.
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition: time.cpp:44
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,...