Bitcoin Core 31.99.0
P2P Digital Currency
wallet_create_tx.cpp
Go to the documentation of this file.
1// Copyright (c) 2022-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 <chain.h>
8#include <chainparams.h>
9#include <consensus/amount.h>
10#include <consensus/consensus.h>
11#include <consensus/merkle.h>
12#include <interfaces/chain.h>
13#include <kernel/chain.h>
14#include <kernel/types.h>
15#include <node/blockstorage.h>
16#include <outputtype.h>
17#include <policy/feerate.h>
18#include <primitives/block.h>
20#include <script/script.h>
21#include <sync.h>
23#include <test/util/time.h>
24#include <uint256.h>
25#include <util/result.h>
26#include <util/time.h>
27#include <validation.h>
28#include <versionbits.h>
29#include <wallet/coincontrol.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 <cassert>
37#include <cstdint>
38#include <map>
39#include <memory>
40#include <optional>
41#include <utility>
42#include <vector>
43
45using wallet::CWallet;
48
50{
54};
55
56TipBlock getTip(const CChainParams& params, const node::NodeContext& context)
57{
58 auto tip = WITH_LOCK(::cs_main, return context.chainman->ActiveTip());
59 return (tip) ? TipBlock{tip->GetBlockHash(), tip->GetBlockTime(), tip->nHeight} :
60 TipBlock{params.GenesisBlock().GetHash(), params.GenesisBlock().GetBlockTime(), 0};
61}
62
64 const node::NodeContext& context,
66 const CScript& coinbase_out_script)
67{
68 TipBlock tip{getTip(params, context)};
69
70 // Create block
71 CBlock block;
72 CMutableTransaction coinbase_tx;
73 coinbase_tx.vin.resize(1);
74 coinbase_tx.vin[0].prevout.SetNull();
75 coinbase_tx.vout.resize(2);
76 coinbase_tx.vout[0].scriptPubKey = coinbase_out_script;
77 coinbase_tx.vout[0].nValue = 48 * COIN;
78 coinbase_tx.vin[0].scriptSig = CScript() << ++tip.tip_height << OP_0;
79 coinbase_tx.vout[1].scriptPubKey = coinbase_out_script; // extra output
80 coinbase_tx.vout[1].nValue = 1 * COIN;
81
82 // Fill the coinbase with outputs that don't belong to the wallet in order to benchmark
83 // AvailableCoins' behavior with unnecessary TXOs
84 for (int i = 0; i < 50; ++i) {
85 coinbase_tx.vout.emplace_back(1 * COIN / 50, CScript(OP_TRUE));
86 }
87
88 block.vtx = {MakeTransactionRef(std::move(coinbase_tx))};
89
91 block.hashPrevBlock = tip.prev_block_hash;
92 block.hashMerkleRoot = BlockMerkleRoot(block);
93 block.nTime = ++tip.prev_block_time;
94 block.nBits = params.GenesisBlock().nBits;
95 block.nNonce = 0;
96
97 {
99 // Add it to the index
100 CBlockIndex* pindex{context.chainman->m_blockman.AddToBlockIndex(block, context.chainman->m_best_header)};
101 // add it to the chain
102 context.chainman->ActiveChain().SetTip(*pindex);
103 }
104
105 // notify wallet
106 const auto& pindex = WITH_LOCK(::cs_main, return context.chainman->ActiveChain().Tip());
107 wallet.blockConnected(ChainstateRole{}, kernel::MakeBlockInfo(pindex, &block));
108}
109
111 // How many coins from the wallet the process should select
113 // future: this could have external inputs as well.
114};
115
116static void WalletCreateTx(benchmark::Bench& bench, const OutputType output_type, bool allow_other_inputs, std::optional<PreSelectInputs> preset_inputs)
117{
118 const auto test_setup = MakeNoLogFileContext<const TestingSetup>();
119
120 // Set clock to genesis block, so the descriptors/keys creation time don't interfere with the blocks scanning process.
121 NodeClockContext clock_ctx{test_setup->m_node.chainman->GetParams().GenesisBlock().Time()};
122 CWallet wallet{test_setup->m_node.chain.get(), "", CreateMockableWalletDatabase()};
123 {
124 LOCK(wallet.cs_wallet);
125 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
126 wallet.SetupDescriptorScriptPubKeyMans();
127 }
128
129 // Generate destinations
130 const auto dest{getNewDestination(wallet, output_type)};
131
132 // Generate chain; each coinbase will have two outputs to fill-up the wallet
133 const auto& params = Params();
134 const CScript coinbase_out{GetScriptForDestination(dest)};
135 unsigned int chain_size = 5000; // 5k blocks means 10k UTXO for the wallet (minus 200 due COINBASE_MATURITY)
136 for (unsigned int i = 0; i < chain_size; ++i) {
137 generateFakeBlock(params, test_setup->m_node, wallet, coinbase_out);
138 }
139
140 // Check available balance
141 auto bal = WITH_LOCK(wallet.cs_wallet, return wallet::AvailableCoins(wallet).GetTotalAmount()); // Cache
142 assert(bal == 49 * COIN * (chain_size - COINBASE_MATURITY));
143
144 wallet::CCoinControl coin_control;
145 coin_control.m_allow_other_inputs = allow_other_inputs;
146
147 CAmount target = 0;
148 if (preset_inputs) {
149 // Select inputs, each has 48 BTC
150 wallet::CoinFilterParams filter_coins;
151 filter_coins.max_count = preset_inputs->num_of_internal_inputs;
152 const auto& res = WITH_LOCK(wallet.cs_wallet,
153 return wallet::AvailableCoins(wallet, /*coinControl=*/nullptr, /*feerate=*/std::nullopt, filter_coins));
154 for (int i=0; i < preset_inputs->num_of_internal_inputs; i++) {
155 const auto& coin{res.coins.at(output_type)[i]};
156 target += coin.txout.nValue;
157 coin_control.Select(coin.outpoint);
158 }
159 }
160
161 // If automatic coin selection is enabled, add the value of another UTXO to the target
162 if (coin_control.m_allow_other_inputs) target += 50 * COIN;
163 std::vector<wallet::CRecipient> recipients = {{dest, target, true}};
164
165 bench.run([&] {
166 LOCK(wallet.cs_wallet);
167 const auto& tx_res = CreateTransaction(wallet, recipients, /*change_pos=*/std::nullopt, coin_control);
168 assert(tx_res);
169 });
170}
171
172static void AvailableCoins(benchmark::Bench& bench, const std::vector<OutputType>& output_type)
173{
174 const auto test_setup = MakeNoLogFileContext<const TestingSetup>();
175 // Set clock to genesis block, so the descriptors/keys creation time don't interfere with the blocks scanning process.
176 NodeClockContext clock_ctx{test_setup->m_node.chainman->GetParams().GenesisBlock().Time()};
177 CWallet wallet{test_setup->m_node.chain.get(), "", CreateMockableWalletDatabase()};
178 {
179 LOCK(wallet.cs_wallet);
180 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
181 wallet.SetupDescriptorScriptPubKeyMans();
182 }
183
184 // Generate destinations
185 std::vector<CScript> dest_wallet;
186 dest_wallet.reserve(output_type.size());
187 for (auto type : output_type) {
188 dest_wallet.emplace_back(GetScriptForDestination(getNewDestination(wallet, type)));
189 }
190
191 // Generate chain; each coinbase will have two outputs to fill-up the wallet
192 const auto& params = Params();
193 unsigned int chain_size = 1000;
194 for (unsigned int i = 0; i < chain_size / dest_wallet.size(); ++i) {
195 for (const auto& dest : dest_wallet) {
196 generateFakeBlock(params, test_setup->m_node, wallet, dest);
197 }
198 }
199
200 // Check available balance
201 auto bal = WITH_LOCK(wallet.cs_wallet, return wallet::AvailableCoins(wallet).GetTotalAmount()); // Cache
202 assert(bal == 49 * COIN * (chain_size - COINBASE_MATURITY));
203
204 bench.run([&] {
205 LOCK(wallet.cs_wallet);
206 const auto& res = wallet::AvailableCoins(wallet);
207 assert(res.All().size() == (chain_size - COINBASE_MATURITY) * 2);
208 });
209}
210
211static void WalletCreateTxUseOnlyPresetInputs(benchmark::Bench& bench) { WalletCreateTx(bench, OutputType::BECH32, /*allow_other_inputs=*/false,
212 {{/*num_of_internal_inputs=*/4}}); }
213
215 {{/*num_of_internal_inputs=*/4}}); }
216
218
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
static constexpr CAmount COIN
The amount of satoshis in one BTC.
Definition: amount.h:15
const CChainParams & Params()
Return the currently selected parameters.
uint32_t nNonce
Definition: block.h:35
uint32_t nBits
Definition: block.h:34
uint32_t nTime
Definition: block.h:33
int64_t GetBlockTime() const
Definition: block.h:66
int32_t nVersion
Definition: block.h:30
uint256 hashPrevBlock
Definition: block.h:31
uint256 hashMerkleRoot
Definition: block.h:32
uint256 GetHash() const
Definition: block.cpp:14
Definition: block.h:74
std::vector< CTransactionRef > vtx
Definition: block.h:77
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:94
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:77
const CBlock & GenesisBlock() const
Definition: chainparams.h:94
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:405
Helper to initialize the global NodeClock, let a duration elapse, and reset it after use in a test.
Definition: time.h:40
Main entry point to nanobench's benchmarking facility.
Definition: nanobench.h:632
Bench & run(char const *benchmarkName, Op &&op)
Repeatedly calls op() based on the configuration, and performs measurements.
Definition: nanobench.h:1288
256-bit opaque blob.
Definition: uint256.h:196
Coin Control Features.
Definition: coincontrol.h:84
PreselectedInput & Select(const COutPoint &outpoint)
Lock-in the given output for spending.
Definition: coincontrol.cpp:40
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:94
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:309
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:66
static const int COINBASE_MATURITY
Coinbase transaction outputs can only be spent after this number of new blocks (network rule)
Definition: consensus.h:19
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
is a home for simple enum and struct type definitions that can be used internally by functions in the...
interfaces::BlockInfo MakeBlockInfo(const CBlockIndex *index, const CBlock *data)
Return data from block index.
Definition: chain.cpp:18
util::Result< CreatedTransactionResult > CreateTransaction(CWallet &wallet, const std::vector< CRecipient > &vecSend, std::optional< unsigned int > change_pos, const CCoinControl &coin_control, bool sign)
Create a new transaction paying the recipients with a set of coins selected by SelectCoins(); Also cr...
Definition: spend.cpp:1451
std::unique_ptr< WalletDatabase > CreateMockableWalletDatabase(MockableData records)
Definition: util.cpp:211
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:53
CTxDestination getNewDestination(CWallet &w, OutputType output_type)
Returns a new destination, of an specific type, from the wallet.
Definition: util.cpp:117
CoinsResult AvailableCoins(const CWallet &wallet, const CCoinControl *coinControl, std::optional< CFeeRate > feerate, const CoinFilterParams &params)
Populate the CoinsResult struct with vectors of available COutputs, organized by OutputType.
Definition: spend.cpp:320
OutputType
Definition: outputtype.h:18
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:404
@ OP_TRUE
Definition: script.h:84
@ OP_0
Definition: script.h:76
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
uint256 prev_block_hash
int64_t prev_block_time
Information about chainstate that notifications are sent from.
Definition: types.h:18
NodeContext struct containing references to chain state and connection state.
Definition: context.h:57
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:74
uint64_t max_count
Definition: spend.h:84
CAmount GetTotalAmount() const
Definition: spend.h:62
#define LOCK(cs)
Definition: sync.h:268
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:299
assert(!tx.IsCoinBase())
static const int32_t VERSIONBITS_LAST_OLD_BLOCK_VERSION
What block version to use for new blocks (pre versionbits)
Definition: versionbits.h:19
static void WalletCreateTxUsePresetInputsAndCoinSelection(benchmark::Bench &bench)
BENCHMARK(WalletCreateTxUseOnlyPresetInputs)
static void WalletAvailableCoins(benchmark::Bench &bench)
TipBlock getTip(const CChainParams &params, const node::NodeContext &context)
void generateFakeBlock(const CChainParams &params, const node::NodeContext &context, CWallet &wallet, const CScript &coinbase_out_script)
static void WalletCreateTx(benchmark::Bench &bench, const OutputType output_type, bool allow_other_inputs, std::optional< PreSelectInputs > preset_inputs)
static void AvailableCoins(benchmark::Bench &bench, const std::vector< OutputType > &output_type)
static void WalletCreateTxUseOnlyPresetInputs(benchmark::Bench &bench)