Bitcoin Core 28.99.0
P2P Digital Currency
wallet_create_tx.cpp
Go to the documentation of this file.
1// Copyright (c) 2022 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 <node/blockstorage.h>
15#include <outputtype.h>
16#include <policy/feerate.h>
17#include <primitives/block.h>
19#include <script/script.h>
20#include <sync.h>
22#include <uint256.h>
23#include <util/result.h>
24#include <util/time.h>
25#include <validation.h>
26#include <versionbits.h>
27#include <wallet/coincontrol.h>
29#include <wallet/spend.h>
30#include <wallet/test/util.h>
31#include <wallet/wallet.h>
32#include <wallet/walletutil.h>
33
34#include <cassert>
35#include <cstdint>
36#include <map>
37#include <memory>
38#include <optional>
39#include <utility>
40#include <vector>
41
42using wallet::CWallet;
45
47{
51};
52
53TipBlock getTip(const CChainParams& params, const node::NodeContext& context)
54{
55 auto tip = WITH_LOCK(::cs_main, return context.chainman->ActiveTip());
56 return (tip) ? TipBlock{tip->GetBlockHash(), tip->GetBlockTime(), tip->nHeight} :
57 TipBlock{params.GenesisBlock().GetHash(), params.GenesisBlock().GetBlockTime(), 0};
58}
59
61 const node::NodeContext& context,
63 const CScript& coinbase_out_script)
64{
65 TipBlock tip{getTip(params, context)};
66
67 // Create block
68 CBlock block;
69 CMutableTransaction coinbase_tx;
70 coinbase_tx.vin.resize(1);
71 coinbase_tx.vin[0].prevout.SetNull();
72 coinbase_tx.vout.resize(2);
73 coinbase_tx.vout[0].scriptPubKey = coinbase_out_script;
74 coinbase_tx.vout[0].nValue = 49 * COIN;
75 coinbase_tx.vin[0].scriptSig = CScript() << ++tip.tip_height << OP_0;
76 coinbase_tx.vout[1].scriptPubKey = coinbase_out_script; // extra output
77 coinbase_tx.vout[1].nValue = 1 * COIN;
78 block.vtx = {MakeTransactionRef(std::move(coinbase_tx))};
79
81 block.hashPrevBlock = tip.prev_block_hash;
82 block.hashMerkleRoot = BlockMerkleRoot(block);
83 block.nTime = ++tip.prev_block_time;
84 block.nBits = params.GenesisBlock().nBits;
85 block.nNonce = 0;
86
87 {
89 // Add it to the index
90 CBlockIndex* pindex{context.chainman->m_blockman.AddToBlockIndex(block, context.chainman->m_best_header)};
91 // add it to the chain
92 context.chainman->ActiveChain().SetTip(*pindex);
93 }
94
95 // notify wallet
96 const auto& pindex = WITH_LOCK(::cs_main, return context.chainman->ActiveChain().Tip());
97 wallet.blockConnected(ChainstateRole::NORMAL, kernel::MakeBlockInfo(pindex, &block));
98}
99
101 // How many coins from the wallet the process should select
103 // future: this could have external inputs as well.
104};
105
106static void WalletCreateTx(benchmark::Bench& bench, const OutputType output_type, bool allow_other_inputs, std::optional<PreSelectInputs> preset_inputs)
107{
108 const auto test_setup = MakeNoLogFileContext<const TestingSetup>();
109
110 // Set clock to genesis block, so the descriptors/keys creation time don't interfere with the blocks scanning process.
111 SetMockTime(test_setup->m_node.chainman->GetParams().GenesisBlock().nTime);
112 CWallet wallet{test_setup->m_node.chain.get(), "", CreateMockableWalletDatabase()};
113 {
114 LOCK(wallet.cs_wallet);
115 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
116 wallet.SetupDescriptorScriptPubKeyMans();
117 }
118
119 // Generate destinations
120 const auto dest{getNewDestination(wallet, output_type)};
121
122 // Generate chain; each coinbase will have two outputs to fill-up the wallet
123 const auto& params = Params();
124 const CScript coinbase_out{GetScriptForDestination(dest)};
125 unsigned int chain_size = 5000; // 5k blocks means 10k UTXO for the wallet (minus 200 due COINBASE_MATURITY)
126 for (unsigned int i = 0; i < chain_size; ++i) {
127 generateFakeBlock(params, test_setup->m_node, wallet, coinbase_out);
128 }
129
130 // Check available balance
131 auto bal = WITH_LOCK(wallet.cs_wallet, return wallet::AvailableCoins(wallet).GetTotalAmount()); // Cache
132 assert(bal == 50 * COIN * (chain_size - COINBASE_MATURITY));
133
134 wallet::CCoinControl coin_control;
135 coin_control.m_allow_other_inputs = allow_other_inputs;
136
137 CAmount target = 0;
138 if (preset_inputs) {
139 // Select inputs, each has 49 BTC
140 wallet::CoinFilterParams filter_coins;
141 filter_coins.max_count = preset_inputs->num_of_internal_inputs;
142 const auto& res = WITH_LOCK(wallet.cs_wallet,
143 return wallet::AvailableCoins(wallet, /*coinControl=*/nullptr, /*feerate=*/std::nullopt, filter_coins));
144 for (int i=0; i < preset_inputs->num_of_internal_inputs; i++) {
145 const auto& coin{res.coins.at(output_type)[i]};
146 target += coin.txout.nValue;
147 coin_control.Select(coin.outpoint);
148 }
149 }
150
151 // If automatic coin selection is enabled, add the value of another UTXO to the target
152 if (coin_control.m_allow_other_inputs) target += 50 * COIN;
153 std::vector<wallet::CRecipient> recipients = {{dest, target, true}};
154
155 bench.epochIterations(5).run([&] {
156 LOCK(wallet.cs_wallet);
157 const auto& tx_res = CreateTransaction(wallet, recipients, /*change_pos=*/std::nullopt, coin_control);
158 assert(tx_res);
159 });
160}
161
162static void AvailableCoins(benchmark::Bench& bench, const std::vector<OutputType>& output_type)
163{
164 const auto test_setup = MakeNoLogFileContext<const TestingSetup>();
165 // Set clock to genesis block, so the descriptors/keys creation time don't interfere with the blocks scanning process.
166 SetMockTime(test_setup->m_node.chainman->GetParams().GenesisBlock().nTime);
167 CWallet wallet{test_setup->m_node.chain.get(), "", CreateMockableWalletDatabase()};
168 {
169 LOCK(wallet.cs_wallet);
170 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
171 wallet.SetupDescriptorScriptPubKeyMans();
172 }
173
174 // Generate destinations
175 std::vector<CScript> dest_wallet;
176 dest_wallet.reserve(output_type.size());
177 for (auto type : output_type) {
178 dest_wallet.emplace_back(GetScriptForDestination(getNewDestination(wallet, type)));
179 }
180
181 // Generate chain; each coinbase will have two outputs to fill-up the wallet
182 const auto& params = Params();
183 unsigned int chain_size = 1000;
184 for (unsigned int i = 0; i < chain_size / dest_wallet.size(); ++i) {
185 for (const auto& dest : dest_wallet) {
186 generateFakeBlock(params, test_setup->m_node, wallet, dest);
187 }
188 }
189
190 // Check available balance
191 auto bal = WITH_LOCK(wallet.cs_wallet, return wallet::AvailableCoins(wallet).GetTotalAmount()); // Cache
192 assert(bal == 50 * COIN * (chain_size - COINBASE_MATURITY));
193
194 bench.epochIterations(2).run([&] {
195 LOCK(wallet.cs_wallet);
196 const auto& res = wallet::AvailableCoins(wallet);
197 assert(res.All().size() == (chain_size - COINBASE_MATURITY) * 2);
198 });
199}
200
201static void WalletCreateTxUseOnlyPresetInputs(benchmark::Bench& bench) { WalletCreateTx(bench, OutputType::BECH32, /*allow_other_inputs=*/false,
202 {{/*num_of_internal_inputs=*/4}}); }
203
205 {{/*num_of_internal_inputs=*/4}}); }
206
208
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:30
uint32_t nBits
Definition: block.h:29
uint32_t nTime
Definition: block.h:28
int64_t GetBlockTime() const
Definition: block.h:61
int32_t nVersion
Definition: block.h:25
uint256 hashPrevBlock
Definition: block.h:26
uint256 hashMerkleRoot
Definition: block.h:27
uint256 GetHash() const
Definition: block.cpp:11
Definition: block.h:69
std::vector< CTransactionRef > vtx
Definition: block.h:72
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:141
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:81
const CBlock & GenesisBlock() const
Definition: chainparams.h:98
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:415
Main entry point to nanobench's benchmarking facility.
Definition: nanobench.h:627
Bench & run(char const *benchmarkName, Op &&op)
Repeatedly calls op() based on the configuration, and performs measurements.
Definition: nanobench.h:1234
Bench & epochIterations(uint64_t numIters) noexcept
Sets exactly the number of iterations for each epoch.
256-bit opaque blob.
Definition: uint256.h:190
Coin Control Features.
Definition: coincontrol.h:81
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:91
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:300
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
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:66
PriorityLevel
Definition: bench.h:46
@ LOW
Definition: bench.h:47
interfaces::BlockInfo MakeBlockInfo(const CBlockIndex *index, const CBlock *data)
Return data from block index.
Definition: chain.cpp:14
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:1370
std::unique_ptr< WalletDatabase > CreateMockableWalletDatabase(MockableData records)
Definition: util.cpp:186
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:74
CTxDestination getNewDestination(CWallet &w, OutputType output_type)
Returns a new destination, of an specific type, from the wallet.
Definition: util.cpp:92
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:314
OutputType
Definition: outputtype.h:17
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:424
@ OP_0
Definition: script.h:76
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
uint256 prev_block_hash
int64_t prev_block_time
NodeContext struct containing references to chain state and connection state.
Definition: context.h:56
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:72
uint64_t max_count
Definition: spend.h:74
CAmount GetTotalAmount()
Definition: spend.h:56
#define LOCK(cs)
Definition: sync.h:257
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:301
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition: time.cpp:35
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:14
static void WalletCreateTxUsePresetInputsAndCoinSelection(benchmark::Bench &bench)
BENCHMARK(WalletAvailableCoins, benchmark::PriorityLevel::LOW)
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)