Bitcoin Core 32.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 <addresstype.h>
6#include <bench/bench.h>
7#include <consensus/amount.h>
8#include <interfaces/wallet.h>
9#include <key.h>
10#include <primitives/block.h>
12#include <pubkey.h>
13#include <script/script.h>
14#include <sync.h>
16#include <tinyformat.h>
17#include <uint256.h>
18#include <util/check.h>
19#include <util/result.h>
20#include <wallet/db.h>
22#include <wallet/test/util.h>
23#include <wallet/transaction.h>
24#include <wallet/wallet.h>
25#include <wallet/walletdb.h>
26
27#include <algorithm>
28#include <cstdint>
29#include <cstddef>
30#include <memory>
31#include <optional>
32#include <string>
33#include <utility>
34#include <vector>
35
36namespace wallet{
37
39{
40 const auto test_setup{MakeNoLogFileContext<TestingSetup>()};
41 const auto loader{MakeWalletLoader(*test_setup->m_node.chain, test_setup->m_args)};
42
43 // Number of imported watch only addresses
44 int NUM_WATCH_ONLY_ADDR = 20;
45
46 // Add watch-only addresses
47 std::vector<std::pair<CScript, CTxDestination>> scripts_watch_only;
48 for (int w = 0; w < NUM_WATCH_ONLY_ADDR; ++w) {
49 CKey key = GenerateRandomKey();
50 const PKHash dest{key.GetPubKey()};
51 scripts_watch_only.emplace_back(GetScriptForDestination(dest), dest);
52 }
53
54 // Generate transactions and local addresses
55 std::vector<CKey> keys(500);
57
58 std::unique_ptr<CWallet> wallet;
59 size_t i = 0;
60 bench.epochs(/*numEpochs=*/1) // run the migration exactly once
61 .setup([&] {
62 // Setup legacy wallet
63 wallet = std::make_unique<CWallet>(test_setup->m_node.chain.get(), std::string(i++, 'A'), CreateMockableWalletDatabase());
64 LegacyDataSPKM* legacy_spkm = wallet->GetOrCreateLegacyDataSPKM();
65 WalletBatch batch{wallet->GetDatabase()};
66
67 LOCK(wallet->cs_wallet);
68
69 // Write a best block record as migration expects one to exist
70 CBlockLocator loc;
71 batch.WriteBestBlock(loc);
72
73 // Add watch-only addresses
74 for (size_t w = 0; w < scripts_watch_only.size(); ++w) {
75 const auto& [script, dest] = scripts_watch_only.at(w);
76 assert(legacy_spkm->LoadWatchOnly(script));
77 assert(wallet->SetAddressBook(dest, strprintf("watch_%d", w), /*purpose=*/std::nullopt));
78 batch.WriteWatchOnly(script, CKeyMetadata());
79 }
80
81 // Generate transactions and local addresses
82 for (size_t j = 0; j < keys.size(); ++j) {
83 const CKey& key = keys.at(j);
84 // Load key, scripts and create address book record
85 CPubKey pubkey = key.GetPubKey();
86 Assert(legacy_spkm->LoadKey(key, pubkey));
87 CTxDestination dest{PKHash(pubkey)};
88 Assert(wallet->SetAddressBook(dest, strprintf("legacy_%d", j), /*purpose=*/std::nullopt));
89
91 mtx.vout.emplace_back(COIN, GetScriptForDestination(dest));
92 mtx.vout.emplace_back(COIN, scripts_watch_only.at(j % NUM_WATCH_ONLY_ADDR).first);
93 // Use distinct dummy prevouts so all txs don't appear to spend the same null outpoint
94 mtx.vin.emplace_back(COutPoint(Txid::FromUint256(uint256{uint8_t(j + 1)}), 0));
95 mtx.vin.emplace_back(COutPoint(Txid::FromUint256(uint256{uint8_t(j + 1)}), 1));
96 wallet->AddToWallet(MakeTransactionRef(mtx), TxStateInactive{}, /*update_wtx=*/nullptr, /*rescanning_old_block=*/true);
97 batch.WriteKey(pubkey, key.GetPrivKey(), CKeyMetadata());
98 }
99 })
100 .run([&] {
101 auto res{MigrateLegacyToDescriptor(std::move(wallet), /*passphrase=*/"", *loader->context())};
102 assert(res);
103 assert(res->wallet);
104 assert(res->watchonly_wallet);
105 });
106}
107
109
110} // 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
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:40
CPrivKey GetPrivKey() const
Convert the private key to a CPrivKey (serialized OpenSSL private key data).
Definition: key.cpp:171
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:184
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:30
An encapsulated public key.
Definition: pubkey.h:40
Main entry point to nanobench's benchmarking facility.
Definition: nanobench.h:649
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:1302
static transaction_identifier FromUint256(const uint256 &id)
256-bit opaque blob.
Definition: uint256.h:196
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:197
CKey GenerateRandomKey(bool compressed) noexcept
Definition: key.cpp:354
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:121
util::Result< MigrationResult > MigrateLegacyToDescriptor(const std::string &wallet_name, const SecureString &passphrase, WalletContext &context, bool load_wallet)
Do all steps to migrate a legacy wallet to a descriptor wallet.
Definition: wallet.cpp:4145
static void WalletMigration(benchmark::Bench &bench)
BENCHMARK(CoinSelection)
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:418
static RPCMethod generate()
Definition: mining.cpp:288
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:372
std::vector< CTxOut > vout
Definition: transaction.h:374
std::vector< CTxIn > vin
Definition: transaction.h:373
State of transaction not confirmed or conflicting with a known block and not in the mempool.
Definition: transaction.h:61
#define LOCK(cs)
Definition: sync.h:268
std::vector< uint16_t > keys
Definition: dbwrapper.cpp:376
#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())