Bitcoin Core 31.99.0
P2P Digital Currency
wallet_migration.cpp
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 https://www.opensource.org/licenses/mit-license.php.
4
5#include <bench/bench.h>
6#include <interfaces/chain.h>
7#include <interfaces/wallet.h>
8#include <kernel/chain.h>
9#include <kernel/types.h>
10#include <node/context.h>
11#include <test/util/mining.h>
13#include <wallet/context.h>
14#include <wallet/receive.h>
15#include <wallet/test/util.h>
16#include <wallet/wallet.h>
17
18#include <optional>
19
20namespace wallet{
21
23{
24 const auto test_setup{MakeNoLogFileContext<TestingSetup>()};
25 const auto loader{MakeWalletLoader(*test_setup->m_node.chain, test_setup->m_args)};
26
27 // Number of imported watch only addresses
28 int NUM_WATCH_ONLY_ADDR = 20;
29
30 // Add watch-only addresses
31 std::vector<std::pair<CScript, CTxDestination>> scripts_watch_only;
32 for (int w = 0; w < NUM_WATCH_ONLY_ADDR; ++w) {
33 CKey key = GenerateRandomKey();
34 const PKHash dest{key.GetPubKey()};
35 scripts_watch_only.emplace_back(GetScriptForDestination(dest), dest);
36 }
37
38 // Generate transactions and local addresses
39 std::vector<CKey> keys(500);
40 std::ranges::generate(keys, []{ return GenerateRandomKey(); });
41
42 std::unique_ptr<CWallet> wallet;
43 size_t i = 0;
44 bench.epochs(/*numEpochs=*/1) // run the migration exactly once
45 .setup([&] {
46 // Setup legacy wallet
47 wallet = std::make_unique<CWallet>(test_setup->m_node.chain.get(), std::string(i++, 'A'), CreateMockableWalletDatabase());
48 LegacyDataSPKM* legacy_spkm = wallet->GetOrCreateLegacyDataSPKM();
49 WalletBatch batch{wallet->GetDatabase()};
50
51 LOCK(wallet->cs_wallet);
52
53 // Write a best block record as migration expects one to exist
54 CBlockLocator loc;
55 batch.WriteBestBlock(loc);
56
57 // Add watch-only addresses
58 for (size_t w = 0; w < scripts_watch_only.size(); ++w) {
59 const auto& [script, dest] = scripts_watch_only.at(w);
60 assert(legacy_spkm->LoadWatchOnly(script));
61 assert(wallet->SetAddressBook(dest, strprintf("watch_%d", w), /*purpose=*/std::nullopt));
62 batch.WriteWatchOnly(script, CKeyMetadata());
63 }
64
65 // Generate transactions and local addresses
66 for (size_t j = 0; j < keys.size(); ++j) {
67 const CKey& key = keys.at(j);
68 // Load key, scripts and create address book record
69 CPubKey pubkey = key.GetPubKey();
70 Assert(legacy_spkm->LoadKey(key, pubkey));
71 CTxDestination dest{PKHash(pubkey)};
72 Assert(wallet->SetAddressBook(dest, strprintf("legacy_%d", j), /*purpose=*/std::nullopt));
73
75 mtx.vout.emplace_back(COIN, GetScriptForDestination(dest));
76 mtx.vout.emplace_back(COIN, scripts_watch_only.at(j % NUM_WATCH_ONLY_ADDR).first);
77 mtx.vin.resize(2);
78 wallet->AddToWallet(MakeTransactionRef(mtx), TxStateInactive{}, /*update_wtx=*/nullptr, /*rescanning_old_block=*/true);
79 batch.WriteKey(pubkey, key.GetPrivKey(), CKeyMetadata());
80 }
81 })
82 .run([&] {
83 auto res{MigrateLegacyToDescriptor(std::move(wallet), /*passphrase=*/"", *loader->context())};
84 assert(res);
85 assert(res->wallet);
86 assert(res->watchonly_wallet);
87 });
88}
89
91
92} // namespace wallet
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
static constexpr CAmount COIN
The amount of satoshis in one BTC.
Definition: amount.h:15
#define Assert(val)
Identity function.
Definition: check.h:116
An encapsulated private key.
Definition: key.h:36
CPrivKey GetPrivKey() const
Convert the private key to a CPrivKey (serialized OpenSSL private key data).
Definition: key.cpp:170
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:183
An encapsulated public key.
Definition: pubkey.h:34
Main entry point to nanobench's benchmarking facility.
Definition: nanobench.h:633
Bench & epochs(size_t numEpochs) noexcept
Controls number of epochs, the number of measurements to perform.
detail::SetupRunner< SetupOp > setup(SetupOp setupOp)
Configure an untimed setup step per epoch (forces single-iteration epochs).
Definition: nanobench.h:1286
bool LoadKey(const CKey &key, const CPubKey &pubkey)
Adds a key to the store, without saving it to disk (used by LoadWallet)
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
Access to the wallet database.
Definition: walletdb.h:192
is a home for simple enum and struct type definitions that can be used internally by functions in the...
CKey GenerateRandomKey(bool compressed) noexcept
Definition: key.cpp:475
std::unique_ptr< WalletLoader > MakeWalletLoader(Chain &chain, ArgsManager &args)
Return implementation of ChainClient interface for a wallet loader.
Definition: dummywallet.cpp:59
std::unique_ptr< WalletDatabase > CreateMockableWalletDatabase()
Definition: util.cpp:122
static void WalletMigration(benchmark::Bench &bench)
util::Result< MigrationResult > MigrateLegacyToDescriptor(const std::string &wallet_name, const SecureString &passphrase, WalletContext &context)
Do all steps to migrate a legacy wallet to a descriptor wallet.
Definition: wallet.cpp:4295
BENCHMARK(CoinSelection)
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:404
static RPCMethod generate()
Definition: mining.cpp:257
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:117
A mutable version of CTransaction.
Definition: transaction.h:358
std::vector< CTxOut > vout
Definition: transaction.h:360
std::vector< CTxIn > vin
Definition: transaction.h:359
State of transaction not confirmed or conflicting with a known block and not in the mempool.
Definition: transaction.h:59
#define LOCK(cs)
Definition: sync.h:268
#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())