Bitcoin Core 29.99.0
P2P Digital Currency
wallet.h
Go to the documentation of this file.
1// Copyright (c) 2024-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#ifndef BITCOIN_TEST_FUZZ_UTIL_WALLET_H
6#define BITCOIN_TEST_FUZZ_UTIL_WALLET_H
7
9#include <test/fuzz/fuzz.h>
10#include <test/fuzz/util.h>
11#include <policy/policy.h>
12#include <wallet/coincontrol.h>
13#include <wallet/fees.h>
14#include <wallet/spend.h>
15#include <wallet/test/util.h>
16#include <wallet/wallet.h>
17
18namespace wallet {
19
24 std::shared_ptr<CWallet> wallet;
25 FuzzedWallet(interfaces::Chain& chain, const std::string& name, const std::string& seed_insecure)
26 {
27 wallet = std::make_shared<CWallet>(&chain, name, CreateMockableWalletDatabase());
28 {
29 LOCK(wallet->cs_wallet);
30 wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
31 auto height{*Assert(chain.getHeight())};
32 wallet->SetLastBlockProcessed(height, chain.getBlockHash(height));
33 }
34 wallet->m_keypool_size = 1; // Avoid timeout in TopUp()
35 assert(wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
36 ImportDescriptors(seed_insecure);
37 }
38 void ImportDescriptors(const std::string& seed_insecure)
39 {
40 const std::vector<std::string> DESCS{
41 "pkh(%s/%s/*)",
42 "sh(wpkh(%s/%s/*))",
43 "tr(%s/%s/*)",
44 "wpkh(%s/%s/*)",
45 };
46
47 for (const std::string& desc_fmt : DESCS) {
48 for (bool internal : {true, false}) {
49 const auto descriptor{strprintf(tfm::RuntimeFormat{desc_fmt}, "[5aa9973a/66h/4h/2h]" + seed_insecure, int{internal})};
50
52 std::string error;
53 auto parsed_desc = std::move(Parse(descriptor, keys, error, /*require_checksum=*/false).at(0));
54 assert(parsed_desc);
55 assert(error.empty());
56 assert(parsed_desc->IsRange());
57 assert(parsed_desc->IsSingleType());
58 assert(!keys.keys.empty());
59 WalletDescriptor w_desc{std::move(parsed_desc), /*creation_time=*/0, /*range_start=*/0, /*range_end=*/1, /*next_index=*/0};
60 assert(!wallet->GetDescriptorScriptPubKeyMan(w_desc));
61 LOCK(wallet->cs_wallet);
62 auto& spk_manager = Assert(wallet->AddWalletDescriptor(w_desc, keys, /*label=*/"", internal))->get();
63 wallet->AddActiveScriptPubKeyMan(spk_manager.GetID(), *Assert(w_desc.descriptor->GetOutputType()), internal);
64 }
65 }
66 }
68 {
69 auto type{fuzzed_data_provider.PickValueInArray(OUTPUT_TYPES)};
70 if (fuzzed_data_provider.ConsumeBool()) {
71 return *Assert(wallet->GetNewDestination(type, ""));
72 } else {
73 return *Assert(wallet->GetNewChangeDestination(type));
74 }
75 }
76 CScript GetScriptPubKey(FuzzedDataProvider& fuzzed_data_provider) { return GetScriptForDestination(GetDestination(fuzzed_data_provider)); }
77 void FundTx(FuzzedDataProvider& fuzzed_data_provider, CMutableTransaction tx)
78 {
79 // The fee of "tx" is 0, so this is the total input and output amount
80 const CAmount total_amt{
81 std::accumulate(tx.vout.begin(), tx.vout.end(), CAmount{}, [](CAmount t, const CTxOut& out) { return t + out.nValue; })};
82 const uint32_t tx_size(GetVirtualTransactionSize(CTransaction{tx}));
83 std::set<int> subtract_fee_from_outputs;
84 if (fuzzed_data_provider.ConsumeBool()) {
85 for (size_t i{}; i < tx.vout.size(); ++i) {
86 if (fuzzed_data_provider.ConsumeBool()) {
87 subtract_fee_from_outputs.insert(i);
88 }
89 }
90 }
91 std::vector<CRecipient> recipients;
92 for (size_t idx = 0; idx < tx.vout.size(); idx++) {
93 const CTxOut& tx_out = tx.vout[idx];
94 CTxDestination dest;
95 ExtractDestination(tx_out.scriptPubKey, dest);
96 CRecipient recipient = {dest, tx_out.nValue, subtract_fee_from_outputs.count(idx) == 1};
97 recipients.push_back(recipient);
98 }
99 CCoinControl coin_control;
100 coin_control.m_allow_other_inputs = fuzzed_data_provider.ConsumeBool();
101 CallOneOf(
102 fuzzed_data_provider, [&] { coin_control.destChange = GetDestination(fuzzed_data_provider); },
103 [&] { coin_control.m_change_type.emplace(fuzzed_data_provider.PickValueInArray(OUTPUT_TYPES)); },
104 [&] { /* no op (leave uninitialized) */ });
105 coin_control.fAllowWatchOnly = fuzzed_data_provider.ConsumeBool();
106 coin_control.m_include_unsafe_inputs = fuzzed_data_provider.ConsumeBool();
107 {
108 auto& r{coin_control.m_signal_bip125_rbf};
109 CallOneOf(
110 fuzzed_data_provider, [&] { r = true; }, [&] { r = false; }, [&] { r = std::nullopt; });
111 }
112 coin_control.m_feerate = CFeeRate{
113 // A fee of this range should cover all cases
114 fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(0, 2 * total_amt),
115 tx_size,
116 };
117 if (fuzzed_data_provider.ConsumeBool()) {
118 *coin_control.m_feerate += GetMinimumFeeRate(*wallet, coin_control, nullptr);
119 }
120 coin_control.fOverrideFeeRate = fuzzed_data_provider.ConsumeBool();
121 // Add solving data (m_external_provider and SelectExternal)?
122
123 int change_position{fuzzed_data_provider.ConsumeIntegralInRange<int>(-1, tx.vout.size() - 1)};
124 bilingual_str error;
125 // Clear tx.vout since it is not meant to be used now that we are passing outputs directly.
126 // This sets us up for a future PR to completely remove tx from the function signature in favor of passing inputs directly
127 tx.vout.clear();
128 (void)FundTransaction(*wallet, tx, recipients, change_position, /*lockUnspents=*/false, coin_control);
129 }
130};
131}
132
133#endif // BITCOIN_TEST_FUZZ_UTIL_WALLET_H
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a scriptPubKey for the destination.
Definition: addresstype.cpp:49
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
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
#define Assert(val)
Identity function.
Definition: check.h:106
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:33
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:415
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:296
An output of a transaction.
Definition: transaction.h:150
CScript scriptPubKey
Definition: transaction.h:153
CAmount nValue
Definition: transaction.h:152
T ConsumeIntegralInRange(T min, T max)
T PickValueInArray(const T(&array)[size])
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:130
virtual std::optional< int > getHeight()=0
Get current chain height, not including genesis block (returns 0 if chain only contains genesis block...
virtual uint256 getBlockHash(int height)=0
Get block hash. Height must be valid or this function will abort.
Coin Control Features.
Definition: coincontrol.h:81
std::optional< bool > m_signal_bip125_rbf
Override the wallet's m_signal_rbf if set.
Definition: coincontrol.h:101
std::optional< OutputType > m_change_type
Override the default change type if set, ignored if destChange is set.
Definition: coincontrol.h:86
bool m_allow_other_inputs
If true, the selection process can add extra unselected inputs from the wallet while requires all sel...
Definition: coincontrol.h:91
bool fOverrideFeeRate
Override automatic min/max checks on fee, m_feerate must be set if true.
Definition: coincontrol.h:95
std::optional< CFeeRate > m_feerate
Override the wallet's m_pay_tx_fee if set.
Definition: coincontrol.h:97
bool m_include_unsafe_inputs
If false, only safe inputs will be used.
Definition: coincontrol.h:88
bool fAllowWatchOnly
Includes watch only addresses which are solvable.
Definition: coincontrol.h:93
CTxDestination destChange
Custom change destination, if not set an address is generated.
Definition: coincontrol.h:84
Descriptor with some wallet metadata.
Definition: walletutil.h:85
static UniValue Parse(std::string_view raw)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
Definition: client.cpp:317
CreatedTransactionResult FundTransaction(CWallet &wallet, const CMutableTransaction &tx, const std::vector< CRecipient > &recipients, const UniValue &options, CCoinControl &coinControl, bool override_min_fee)
Definition: spend.cpp:507
CFeeRate GetMinimumFeeRate(const CWallet &wallet, const CCoinControl &coin_control, FeeCalculation *feeCalc)
Estimate the minimum fee rate considering user set parameters and the required fee.
Definition: fees.cpp:29
std::unique_ptr< WalletDatabase > CreateMockableWalletDatabase(MockableData records)
Definition: util.cpp:186
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:74
static constexpr auto OUTPUT_TYPES
Definition: outputtype.h:25
int64_t GetVirtualTransactionSize(int64_t nWeight, int64_t nSigOpCost, unsigned int bytes_per_sigop)
Compute the virtual transaction size (weight reinterpreted as bytes).
Definition: policy.cpp:310
const char * name
Definition: rest.cpp:49
A mutable version of CTransaction.
Definition: transaction.h:378
std::vector< CTxOut > vout
Definition: transaction.h:380
std::map< CKeyID, CKey > keys
Bilingual messages:
Definition: translation.h:24
Wraps a descriptor wallet for fuzzing.
Definition: wallet.h:23
void FundTx(FuzzedDataProvider &fuzzed_data_provider, CMutableTransaction tx)
Definition: wallet.h:77
FuzzedWallet(interfaces::Chain &chain, const std::string &name, const std::string &seed_insecure)
Definition: wallet.h:25
void ImportDescriptors(const std::string &seed_insecure)
Definition: wallet.h:38
CScript GetScriptPubKey(FuzzedDataProvider &fuzzed_data_provider)
Definition: wallet.h:76
CTxDestination GetDestination(FuzzedDataProvider &fuzzed_data_provider)
Definition: wallet.h:67
std::shared_ptr< CWallet > wallet
Definition: wallet.h:24
#define LOCK(cs)
Definition: sync.h:257
size_t CallOneOf(FuzzedDataProvider &fuzzed_data_provider, Callables... callables)
Definition: util.h:35
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
assert(!tx.IsCoinBase())