Merge bitcoin/bitcoin#36068: fuzz: reuse one fuzzed wallet across inputs
What changed, and why it matters
This commit is a performance improvement for Bitcoin Core's internal fuzz testing (automated randomized testing). It reuses a single test wallet across many fuzz inputs instead of rebuilding it each time, and adds a test-only helper to clear in-memory transaction state. There is no indication this fixes a security vulnerability or affects production wallet behavior.
No security action required. This is a test-only performance optimization. Reviewers may optionally verify that ClearInMemoryTxStateForTest is adequately guarded from production use (it is documented as test-only and requires cs_wallet lock).
Security signals we found
No strong security signals were identified.
Evidence from the diff
The merge commit refactors the FuzzedWallet harness used in fuzz targets (specifically wallet_create_transaction). Previously the wallet was constructed per-input, which was slow due to descriptor imports and BIP32 derivations. The change builds the wallet once in the .init hook, precomputes a pool of destinations, and resets in-memory state per input via a new test-only CWallet::ClearInMemoryTxStateForTest() method. The new helper clears mapWallet, wtxOrdered, mapTxSpends, m_txos, m_locked_coins, and resets nOrderPosNext, but does not touch the database, wallet flags, or ScriptPubKeyMans. A DriftCheck assertion is added in the fuzz target to verify descriptor range counters do not drift unexpectedly.
Changed components
src/test/fuzz/util/wallet.hsrc/wallet/test/fuzz/spend.cppsrc/wallet/wallet.cppsrc/wallet/wallet.hInspect captured patch +143 / −16
### src/test/fuzz/util/wallet.h
@@ -5,37 +5,128 @@
#ifndef BITCOIN_TEST_FUZZ_UTIL_WALLET_H
#define BITCOIN_TEST_FUZZ_UTIL_WALLET_H
+#include <outputtype.h>
#include <policy/policy.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
#include <util/check.h>
#include <wallet/coincontrol.h>
#include <wallet/fees.h>
+#include <wallet/scriptpubkeyman.h>
#include <wallet/spend.h>
#include <wallet/test/util.h>
#include <wallet/wallet.h>
+#include <array>
+#include <cstddef>
+#include <cstdint>
+#include <memory>
+#include <string>
+#include <vector>
+
namespace wallet {
/**
* Wraps a descriptor wallet for fuzzing.
*/
struct FuzzedWallet {
+ static constexpr size_t DESTINATION_POOL_SIZE{16};
+ static constexpr uint64_t REBUILD_INTERVAL{1000};
+
std::shared_ptr<CWallet> wallet;
+
FuzzedWallet(interfaces::Chain& chain, const std::string& name, const std::string& seed_insecure)
+ : m_chain{chain}, m_name{name}, m_seed_insecure{seed_insecure}
+ {
+ Build();
+ }
+
+ void Reset()
+ {
+ if (++m_iterations >= REBUILD_INTERVAL) {
+ Build();
+ return;
+ }
+ m_cursors.fill(0);
+ m_change_cursors.fill(0);
+ {
+ LOCK(wallet->cs_wallet);
+ wallet->ClearInMemoryTxStateForTest();
+ assert(wallet->mapWallet.empty());
+ assert(wallet->GetTXOs().empty());
+ }
+ }
+
+ CTxDestination GetDestination(FuzzedDataProvider& fuzzed_data_provider)
+ {
+ const auto type{fuzzed_data_provider.PickValueInArray(OUTPUT_TYPES)};
+ const bool external{fuzzed_data_provider.ConsumeBool()};
+ const size_t i{TypeIndex(type)};
+ auto& pool{external ? m_dests : m_change_dests};
+ auto& cursor{external ? m_cursors.at(i) : m_change_cursors.at(i)};
+ const CTxDestination& dest{pool.at(i).at(cursor % DESTINATION_POOL_SIZE)};
+ ++cursor;
+ return dest;
+ }
+
+ CScript GetScriptPubKey(FuzzedDataProvider& fuzzed_data_provider) { return GetScriptForDestination(GetDestination(fuzzed_data_provider)); }
+
+ int64_t RangeTotal() const
{
- wallet = std::make_shared<CWallet>(&chain, name, CreateMockableWalletDatabase());
+ int64_t total{0};
+ for (const DescriptorScriptPubKeyMan* spkm : m_spkms) total += spkm->GetEndRange();
+ return total;
+ }
+
+private:
+ using DestinationPool = std::array<std::vector<CTxDestination>, OUTPUT_TYPES.size()>;
+
+ interfaces::Chain& m_chain;
+ const std::string m_name;
+ const std::string m_seed_insecure;
+
+ using PoolCursors = std::array<size_t, OUTPUT_TYPES.size()>;
+
+ DestinationPool m_dests;
+ DestinationPool m_change_dests;
+ PoolCursors m_cursors{};
+ PoolCursors m_change_cursors{};
+
+ static size_t TypeIndex(OutputType type)
+ {
+ for (size_t i = 0; i < OUTPUT_TYPES.size(); ++i) {
+ if (OUTPUT_TYPES.at(i) == type) return i;
+ }
+ assert(false);
+ }
+
+ std::vector<DescriptorScriptPubKeyMan*> m_spkms;
+ uint64_t m_iterations{0};
+
+ void Build()
+ {
+ m_spkms.clear();
+ for (auto& pool : m_dests) pool.clear();
+ for (auto& pool : m_change_dests) pool.clear();
+ m_cursors.fill(0);
+ m_change_cursors.fill(0);
+
+ wallet = std::make_shared<CWallet>(&m_chain, m_name, CreateMockableWalletDatabase());
{
LOCK(wallet->cs_wallet);
wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
- auto height{*Assert(chain.getHeight())};
- wallet->SetLastBlockProcessed(height, chain.getBlockHash(height));
+ auto height{*Assert(m_chain.getHeight())};
+ wallet->SetLastBlockProcessed(height, m_chain.getBlockHash(height));
}
wallet->m_keypool_size = 1; // Avoid timeout in TopUp()
assert(wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
- ImportDescriptors(seed_insecure);
+ ImportDescriptors(m_seed_insecure);
+ PrecomputeDestinations();
+
+ m_iterations = 0;
}
+
void ImportDescriptors(const std::string& seed_insecure)
{
const std::vector<std::string> DESCS{
@@ -62,19 +153,22 @@ struct FuzzedWallet {
LOCK(wallet->cs_wallet);
auto& spk_manager = Assert(wallet->AddWalletDescriptor(w_desc, keys, /*label=*/"", internal))->get();
wallet->AddActiveScriptPubKeyMan(spk_manager.GetID(), *Assert(w_desc.descriptor->GetOutputType()), internal);
+ m_spkms.push_back(&spk_manager);
}
}
}
- CTxDestination GetDestination(FuzzedDataProvider& fuzzed_data_provider)
+
+ void PrecomputeDestinations()
{
- auto type{fuzzed_data_provider.PickValueInArray(OUTPUT_TYPES)};
- if (fuzzed_data_provider.ConsumeBool()) {
- return *Assert(wallet->GetNewDestination(type, ""));
- } else {
- return *Assert(wallet->GetNewChangeDestination(type));
+ for (size_t i = 0; i < OUTPUT_TYPES.size(); ++i) {
+ const OutputType type{OUTPUT_TYPES.at(i)};
+ for (size_t j = 0; j < DESTINATION_POOL_SIZE; ++j) {
+ m_dests.at(i).push_back(*Assert(wallet->GetNewDestination(type, "")));
+ m_change_dests.at(i).push_back(*Assert(wallet->GetNewChangeDestination(type)));
+ }
}
}
};
-}
+} // namespace wallet
#endif // BITCOIN_TEST_FUZZ_UTIL_WALLET_H
### src/wallet/test/fuzz/spend.cpp
@@ -25,11 +25,18 @@ using util::ToString;
namespace wallet {
namespace {
const TestingSetup* g_setup;
+FuzzedWallet* g_wallet;
void initialize_setup()
{
static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>();
g_setup = testing_setup.get();
+ static FuzzedWallet fuzzed_wallet{
+ *g_setup->m_node.chain,
+ "fuzzed_wallet_a",
+ "tprv8ZgxMBicQKsPd1QwsGgzfu2pcPYbBosZhJknqreRHgsWx32nNEhMjGQX2cgFL8n6wz9xdDYwLcs78N4nsCo32cxEX8RBtwGsEGgybLiQJfk",
+ };
+ g_wallet = &fuzzed_wallet;
}
FUZZ_TARGET(wallet_create_transaction, .init = initialize_setup)
@@ -41,11 +48,18 @@ FUZZ_TARGET(wallet_create_transaction, .init = initialize_setup)
Chainstate& chainstate{node.chainman->ActiveChainstate()};
ArgsManager& args = *node.args;
args.ForceSetArg("-dustrelayfee", ToString(fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(0, MAX_MONEY)));
- FuzzedWallet fuzzed_wallet{
- *g_setup->m_node.chain,
- "fuzzed_wallet_a",
- "tprv8ZgxMBicQKsPd1QwsGgzfu2pcPYbBosZhJknqreRHgsWx32nNEhMjGQX2cgFL8n6wz9xdDYwLcs78N4nsCo32cxEX8RBtwGsEGgybLiQJfk",
- };
+ FuzzedWallet& fuzzed_wallet{*g_wallet};
+ fuzzed_wallet.Reset();
+ struct DriftCheck {
+ FuzzedWallet& w;
+ int64_t before;
+ ~DriftCheck()
+ {
+ const int64_t drift{w.RangeTotal() - before};
+ assert(drift >= 0);
+ assert(drift <= 2);
+ }
+ } drift_check{fuzzed_wallet, fuzzed_wallet.RangeTotal()};
CCoinControl coin_control;
if (fuzzed_data_provider.ConsumeBool()) coin_control.m_version = fuzzed_data_provider.ConsumeIntegral<unsigned int>();
### src/wallet/wallet.cpp
@@ -2297,6 +2297,17 @@ util::Result<void> CWallet::RemoveTxs(WalletBatch& batch, std::vector<Txid>& txs
return {};
}
+void CWallet::ClearInMemoryTxStateForTest()
+{
+ AssertLockHeld(cs_wallet);
+ mapWallet.clear();
+ wtxOrdered.clear();
+ mapTxSpends.clear();
+ m_txos.clear();
+ m_locked_coins.clear();
+ nOrderPosNext = 0;
+}
+
bool CWallet::SetAddressBookWithDB(WalletBatch& batch, const CTxDestination& address, const std::string& strName, const std::optional<AddressPurpose>& new_purpose)
{
bool fUpdated = false;
### src/wallet/wallet.h
@@ -788,6 +788,14 @@ class CWallet final : public WalletStorage, public interfaces::Chain::Notificati
util::Result<void> RemoveTxs(std::vector<Txid>& txs_to_remove) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
util::Result<void> RemoveTxs(WalletBatch& batch, std::vector<Txid>& txs_to_remove) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
+ /**
+ * Drop all in-memory transaction state: the transactions themselves, the
+ * outputs derived from them, the spends index and any coin locks. The
+ * database, the wallet flags and the ScriptPubKeyMans are left untouched.
+ * This is test-only function for harnesses that reuse a single wallet.
+ */
+ void ClearInMemoryTxStateForTest() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
+
bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::optional<AddressPurpose>& purpose);
bool DelAddressBook(const CTxDestination& address);Why this scored 15/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.