Bitcoin Core  27.99.0
P2P Digital Currency
notifications.cpp
Go to the documentation of this file.
1 // Copyright (c) 2021-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 <consensus/amount.h>
7 #include <interfaces/chain.h>
8 #include <kernel/chain.h>
9 #include <outputtype.h>
10 #include <policy/feerate.h>
11 #include <policy/policy.h>
12 #include <primitives/block.h>
13 #include <primitives/transaction.h>
14 #include <script/descriptor.h>
15 #include <script/script.h>
16 #include <script/signingprovider.h>
17 #include <sync.h>
19 #include <test/fuzz/fuzz.h>
20 #include <test/fuzz/util.h>
21 #include <test/util/setup_common.h>
22 #include <tinyformat.h>
23 #include <uint256.h>
24 #include <util/check.h>
25 #include <util/result.h>
26 #include <util/translation.h>
27 #include <wallet/coincontrol.h>
28 #include <wallet/context.h>
29 #include <wallet/fees.h>
30 #include <wallet/receive.h>
31 #include <wallet/spend.h>
32 #include <wallet/test/util.h>
33 #include <wallet/wallet.h>
34 #include <wallet/walletutil.h>
35 
36 #include <cstddef>
37 #include <cstdint>
38 #include <limits>
39 #include <numeric>
40 #include <set>
41 #include <string>
42 #include <tuple>
43 #include <utility>
44 #include <vector>
45 
46 namespace wallet {
47 namespace {
48 const TestingSetup* g_setup;
49 
50 void initialize_setup()
51 {
52  static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>();
53  g_setup = testing_setup.get();
54 }
55 
56 void ImportDescriptors(CWallet& wallet, const std::string& seed_insecure)
57 {
58  const std::vector<std::string> DESCS{
59  "pkh(%s/%s/*)",
60  "sh(wpkh(%s/%s/*))",
61  "tr(%s/%s/*)",
62  "wpkh(%s/%s/*)",
63  };
64 
65  for (const std::string& desc_fmt : DESCS) {
66  for (bool internal : {true, false}) {
67  const auto descriptor{(strprintf)(desc_fmt, "[5aa9973a/66h/4h/2h]" + seed_insecure, int{internal})};
68 
70  std::string error;
71  auto parsed_desc = Parse(descriptor, keys, error, /*require_checksum=*/false);
72  assert(parsed_desc);
73  assert(error.empty());
74  assert(parsed_desc->IsRange());
75  assert(parsed_desc->IsSingleType());
76  assert(!keys.keys.empty());
77  WalletDescriptor w_desc{std::move(parsed_desc), /*creation_time=*/0, /*range_start=*/0, /*range_end=*/1, /*next_index=*/0};
78  assert(!wallet.GetDescriptorScriptPubKeyMan(w_desc));
79  LOCK(wallet.cs_wallet);
80  auto spk_manager{wallet.AddWalletDescriptor(w_desc, keys, /*label=*/"", internal)};
81  assert(spk_manager);
82  wallet.AddActiveScriptPubKeyMan(spk_manager->GetID(), *Assert(w_desc.descriptor->GetOutputType()), internal);
83  }
84  }
85 }
86 
90 struct FuzzedWallet {
91  std::shared_ptr<CWallet> wallet;
92  FuzzedWallet(const std::string& name, const std::string& seed_insecure)
93  {
94  auto& chain{*Assert(g_setup->m_node.chain)};
95  wallet = std::make_shared<CWallet>(&chain, name, CreateMockableWalletDatabase());
96  {
97  LOCK(wallet->cs_wallet);
98  wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
99  auto height{*Assert(chain.getHeight())};
100  wallet->SetLastBlockProcessed(height, chain.getBlockHash(height));
101  }
102  wallet->m_keypool_size = 1; // Avoid timeout in TopUp()
103  assert(wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
104  ImportDescriptors(*wallet, seed_insecure);
105  }
106  CTxDestination GetDestination(FuzzedDataProvider& fuzzed_data_provider)
107  {
108  auto type{fuzzed_data_provider.PickValueInArray(OUTPUT_TYPES)};
109  if (fuzzed_data_provider.ConsumeBool()) {
110  return *Assert(wallet->GetNewDestination(type, ""));
111  } else {
112  return *Assert(wallet->GetNewChangeDestination(type));
113  }
114  }
115  CScript GetScriptPubKey(FuzzedDataProvider& fuzzed_data_provider) { return GetScriptForDestination(GetDestination(fuzzed_data_provider)); }
116  void FundTx(FuzzedDataProvider& fuzzed_data_provider, CMutableTransaction tx)
117  {
118  // The fee of "tx" is 0, so this is the total input and output amount
119  const CAmount total_amt{
120  std::accumulate(tx.vout.begin(), tx.vout.end(), CAmount{}, [](CAmount t, const CTxOut& out) { return t + out.nValue; })};
121  const uint32_t tx_size(GetVirtualTransactionSize(CTransaction{tx}));
122  std::set<int> subtract_fee_from_outputs;
123  if (fuzzed_data_provider.ConsumeBool()) {
124  for (size_t i{}; i < tx.vout.size(); ++i) {
125  if (fuzzed_data_provider.ConsumeBool()) {
126  subtract_fee_from_outputs.insert(i);
127  }
128  }
129  }
130  std::vector<CRecipient> recipients;
131  for (size_t idx = 0; idx < tx.vout.size(); idx++) {
132  const CTxOut& tx_out = tx.vout[idx];
133  CTxDestination dest;
134  ExtractDestination(tx_out.scriptPubKey, dest);
135  CRecipient recipient = {dest, tx_out.nValue, subtract_fee_from_outputs.count(idx) == 1};
136  recipients.push_back(recipient);
137  }
138  CCoinControl coin_control;
139  coin_control.m_allow_other_inputs = fuzzed_data_provider.ConsumeBool();
140  CallOneOf(
141  fuzzed_data_provider, [&] { coin_control.destChange = GetDestination(fuzzed_data_provider); },
142  [&] { coin_control.m_change_type.emplace(fuzzed_data_provider.PickValueInArray(OUTPUT_TYPES)); },
143  [&] { /* no op (leave uninitialized) */ });
144  coin_control.fAllowWatchOnly = fuzzed_data_provider.ConsumeBool();
145  coin_control.m_include_unsafe_inputs = fuzzed_data_provider.ConsumeBool();
146  {
147  auto& r{coin_control.m_signal_bip125_rbf};
148  CallOneOf(
149  fuzzed_data_provider, [&] { r = true; }, [&] { r = false; }, [&] { r = std::nullopt; });
150  }
151  coin_control.m_feerate = CFeeRate{
152  // A fee of this range should cover all cases
153  fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(0, 2 * total_amt),
154  tx_size,
155  };
156  if (fuzzed_data_provider.ConsumeBool()) {
157  *coin_control.m_feerate += GetMinimumFeeRate(*wallet, coin_control, nullptr);
158  }
159  coin_control.fOverrideFeeRate = fuzzed_data_provider.ConsumeBool();
160  // Add solving data (m_external_provider and SelectExternal)?
161 
162  int change_position{fuzzed_data_provider.ConsumeIntegralInRange<int>(-1, tx.vout.size() - 1)};
163  bilingual_str error;
164  // Clear tx.vout since it is not meant to be used now that we are passing outputs directly.
165  // This sets us up for a future PR to completely remove tx from the function signature in favor of passing inputs directly
166  tx.vout.clear();
167  (void)FundTransaction(*wallet, tx, recipients, change_position, /*lockUnspents=*/false, coin_control);
168  }
169 };
170 
171 FUZZ_TARGET(wallet_notifications, .init = initialize_setup)
172 {
173  FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
174  // The total amount, to be distributed to the wallets a and b in txs
175  // without fee. Thus, the balance of the wallets should always equal the
176  // total amount.
177  const auto total_amount{ConsumeMoney(fuzzed_data_provider, /*max=*/MAX_MONEY / 100000)};
178  FuzzedWallet a{
179  "fuzzed_wallet_a",
180  "tprv8ZgxMBicQKsPd1QwsGgzfu2pcPYbBosZhJknqreRHgsWx32nNEhMjGQX2cgFL8n6wz9xdDYwLcs78N4nsCo32cxEX8RBtwGsEGgybLiQJfk",
181  };
182  FuzzedWallet b{
183  "fuzzed_wallet_b",
184  "tprv8ZgxMBicQKsPfCunYTF18sEmEyjz8TfhGnZ3BoVAhkqLv7PLkQgmoG2Ecsp4JuqciWnkopuEwShit7st743fdmB9cMD4tznUkcs33vK51K9",
185  };
186 
187  // Keep track of all coins in this test.
188  // Each tuple in the chain represents the coins and the block created with
189  // those coins. Once the block is mined, the next tuple will have an empty
190  // block and the freshly mined coins.
191  using Coins = std::set<std::tuple<CAmount, COutPoint>>;
192  std::vector<std::tuple<Coins, CBlock>> chain;
193  {
194  // Add the initial entry
195  chain.emplace_back();
196  auto& [coins, block]{chain.back()};
197  coins.emplace(total_amount, COutPoint{Txid::FromUint256(uint256::ONE), 1});
198  }
199  LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 200)
200  {
201  CallOneOf(
202  fuzzed_data_provider,
203  [&] {
204  auto& [coins_orig, block]{chain.back()};
205  // Copy the coins for this block and consume all of them
206  Coins coins = coins_orig;
207  while (!coins.empty()) {
208  // Create a new tx
209  CMutableTransaction tx{};
210  // Add some coins as inputs to it
211  auto num_inputs{fuzzed_data_provider.ConsumeIntegralInRange<int>(1, coins.size())};
212  CAmount in{0};
213  while (num_inputs-- > 0) {
214  const auto& [coin_amt, coin_outpoint]{*coins.begin()};
215  in += coin_amt;
216  tx.vin.emplace_back(coin_outpoint);
217  coins.erase(coins.begin());
218  }
219  // Create some outputs spending all inputs, without fee
220  LIMITED_WHILE(in > 0 && fuzzed_data_provider.ConsumeBool(), 10)
221  {
222  const auto out_value{ConsumeMoney(fuzzed_data_provider, in)};
223  in -= out_value;
224  auto& wallet{fuzzed_data_provider.ConsumeBool() ? a : b};
225  tx.vout.emplace_back(out_value, wallet.GetScriptPubKey(fuzzed_data_provider));
226  }
227  // Spend the remaining input value, if any
228  auto& wallet{fuzzed_data_provider.ConsumeBool() ? a : b};
229  tx.vout.emplace_back(in, wallet.GetScriptPubKey(fuzzed_data_provider));
230  // Add tx to block
231  block.vtx.emplace_back(MakeTransactionRef(tx));
232  // Check that funding the tx doesn't crash the wallet
233  a.FundTx(fuzzed_data_provider, tx);
234  b.FundTx(fuzzed_data_provider, tx);
235  }
236  // Mine block
237  const uint256& hash = block.GetHash();
238  interfaces::BlockInfo info{hash};
239  info.prev_hash = &block.hashPrevBlock;
240  info.height = chain.size();
241  info.data = &block;
242  // Ensure that no blocks are skipped by the wallet by setting the chain's accumulated
243  // time to the maximum value. This ensures that the wallet's birth time is always
244  // earlier than this maximum time.
245  info.chain_time_max = std::numeric_limits<unsigned int>::max();
246  a.wallet->blockConnected(ChainstateRole::NORMAL, info);
247  b.wallet->blockConnected(ChainstateRole::NORMAL, info);
248  // Store the coins for the next block
249  Coins coins_new;
250  for (const auto& tx : block.vtx) {
251  uint32_t i{0};
252  for (const auto& out : tx->vout) {
253  coins_new.emplace(out.nValue, COutPoint{tx->GetHash(), i++});
254  }
255  }
256  chain.emplace_back(coins_new, CBlock{});
257  },
258  [&] {
259  if (chain.size() <= 1) return; // The first entry can't be removed
260  auto& [coins, block]{chain.back()};
261  if (block.vtx.empty()) return; // Can only disconnect if the block was submitted first
262  // Disconnect block
263  const uint256& hash = block.GetHash();
264  interfaces::BlockInfo info{hash};
265  info.prev_hash = &block.hashPrevBlock;
266  info.height = chain.size() - 1;
267  info.data = &block;
268  a.wallet->blockDisconnected(info);
269  b.wallet->blockDisconnected(info);
270  chain.pop_back();
271  });
272  auto& [coins, first_block]{chain.front()};
273  if (!first_block.vtx.empty()) {
274  // Only check balance when at least one block was submitted
275  const auto bal_a{GetBalance(*a.wallet).m_mine_trusted};
276  const auto bal_b{GetBalance(*b.wallet).m_mine_trusted};
277  assert(total_amount == bal_a + bal_b);
278  }
279  }
280 }
281 } // namespace
282 } // namespace wallet
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, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
Definition: addresstype.h:131
static constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:26
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
#define Assert(val)
Identity function.
Definition: check.h:77
Definition: block.h:69
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:33
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:29
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:414
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])
static constexpr unsigned int size()
Definition: uint256.h:74
static transaction_identifier FromUint256(const uint256 &id)
256-bit opaque blob.
Definition: uint256.h:106
static const uint256 ONE
Definition: uint256.h:112
static UniValue Parse(std::string_view raw)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
Definition: client.cpp:318
#define LIMITED_WHILE(condition, limit)
Can be used to limit a theoretically unbounded loop.
Definition: fuzz.h:23
Balance GetBalance(const CWallet &wallet, const int min_depth, bool avoid_reuse)
Definition: receive.cpp:293
CreatedTransactionResult FundTransaction(CWallet &wallet, const CMutableTransaction &tx, const std::vector< CRecipient > &recipients, const UniValue &options, CCoinControl &coinControl, bool override_min_fee)
Definition: spend.cpp:493
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
FUZZ_TARGET(coin_grinder)
std::unique_ptr< WalletDatabase > CreateMockableWalletDatabase(MockableData records)
Definition: util.cpp:190
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:74
std::shared_ptr< CWallet > wallet
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:295
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:424
const char * name
Definition: rest.cpp:48
node::NodeContext m_node
Definition: setup_common.h:56
A mutable version of CTransaction.
Definition: transaction.h:378
std::vector< CTxOut > vout
Definition: transaction.h:380
std::vector< CTxIn > vin
Definition: transaction.h:379
std::map< CKeyID, CKey > keys
Testing setup that configures a complete environment.
Definition: setup_common.h:85
Bilingual messages:
Definition: translation.h:18
Block data sent with blockConnected, blockDisconnected notifications.
Definition: chain.h:84
std::unique_ptr< interfaces::Chain > chain
Definition: context.h:71
CAmount m_mine_trusted
Trusted, at depth=GetBalance.min_depth or more.
Definition: receive.h:52
#define LOCK(cs)
Definition: sync.h:257
CAmount ConsumeMoney(FuzzedDataProvider &fuzzed_data_provider, const std::optional< CAmount > &max) noexcept
Definition: util.cpp:29
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:1162
assert(!tx.IsCoinBase())