Bitcoin Core 28.99.0
P2P Digital Currency
mini_miner.cpp
Go to the documentation of this file.
2#include <test/fuzz/fuzz.h>
3#include <test/fuzz/util.h>
5#include <test/util/script.h>
8#include <test/util/mining.h>
9
10#include <node/miner.h>
11#include <node/mini_miner.h>
13#include <random.h>
14#include <txmempool.h>
15#include <util/check.h>
16#include <util/translation.h>
17
18#include <deque>
19#include <vector>
20
21namespace {
22
23const TestingSetup* g_setup;
24std::deque<COutPoint> g_available_coins;
25void initialize_miner()
26{
27 static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>();
28 g_setup = testing_setup.get();
29 for (uint32_t i = 0; i < uint32_t{100}; ++i) {
30 g_available_coins.emplace_back(Txid::FromUint256(uint256::ZERO), i);
31 }
32}
33
34// Test that the MiniMiner can run with various outpoints and feerates.
35FUZZ_TARGET(mini_miner, .init = initialize_miner)
36{
38 FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
39 bilingual_str error;
40 CTxMemPool pool{CTxMemPool::Options{}, error};
41 Assert(error.empty());
42 std::vector<COutPoint> outpoints;
43 std::deque<COutPoint> available_coins = g_available_coins;
44 LOCK2(::cs_main, pool.cs);
45 // Cluster size cannot exceed 500
46 LIMITED_WHILE(!available_coins.empty(), 500)
47 {
49 const size_t num_inputs = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(1, available_coins.size());
50 const size_t num_outputs = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(1, 50);
51 for (size_t n{0}; n < num_inputs; ++n) {
52 auto prevout = available_coins.front();
53 mtx.vin.emplace_back(prevout, CScript());
54 available_coins.pop_front();
55 }
56 for (uint32_t n{0}; n < num_outputs; ++n) {
57 mtx.vout.emplace_back(100, P2WSH_OP_TRUE);
58 }
61 const CAmount fee{ConsumeMoney(fuzzed_data_provider, /*max=*/MAX_MONEY/100000)};
63 AddToMempool(pool, entry.Fee(fee).FromTx(tx));
64
65 // All outputs are available to spend
66 for (uint32_t n{0}; n < num_outputs; ++n) {
67 if (fuzzed_data_provider.ConsumeBool()) {
68 available_coins.emplace_back(tx->GetHash(), n);
69 }
70 }
71
72 if (fuzzed_data_provider.ConsumeBool() && !tx->vout.empty()) {
73 // Add outpoint from this tx (may or not be spent by a later tx)
74 outpoints.emplace_back(tx->GetHash(),
75 (uint32_t)fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, tx->vout.size()));
76 } else {
77 // Add some random outpoint (will be interpreted as confirmed or not yet submitted
78 // to mempool).
79 auto outpoint = ConsumeDeserializable<COutPoint>(fuzzed_data_provider);
80 if (outpoint.has_value() && std::find(outpoints.begin(), outpoints.end(), *outpoint) == outpoints.end()) {
81 outpoints.push_back(*outpoint);
82 }
83 }
84
85 }
86
87 const CFeeRate target_feerate{CFeeRate{ConsumeMoney(fuzzed_data_provider, /*max=*/MAX_MONEY/1000)}};
88 std::optional<CAmount> total_bumpfee;
89 CAmount sum_fees = 0;
90 {
91 node::MiniMiner mini_miner{pool, outpoints};
92 assert(mini_miner.IsReadyToCalculate());
93 const auto bump_fees = mini_miner.CalculateBumpFees(target_feerate);
94 for (const auto& outpoint : outpoints) {
95 auto it = bump_fees.find(outpoint);
96 assert(it != bump_fees.end());
97 assert(it->second >= 0);
98 sum_fees += it->second;
99 }
100 assert(!mini_miner.IsReadyToCalculate());
101 }
102 {
103 node::MiniMiner mini_miner{pool, outpoints};
104 assert(mini_miner.IsReadyToCalculate());
105 total_bumpfee = mini_miner.CalculateTotalBumpFees(target_feerate);
106 assert(total_bumpfee.has_value());
107 assert(!mini_miner.IsReadyToCalculate());
108 }
109 // Overlapping ancestry across multiple outpoints can only reduce the total bump fee.
110 assert (sum_fees >= *total_bumpfee);
111}
112
113// Test that MiniMiner and BlockAssembler build the same block given the same transactions and constraints.
114FUZZ_TARGET(mini_miner_selection, .init = initialize_miner)
115{
117 FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
118 bilingual_str error;
119 CTxMemPool pool{CTxMemPool::Options{}, error};
120 Assert(error.empty());
121 // Make a copy to preserve determinism.
122 std::deque<COutPoint> available_coins = g_available_coins;
123 std::vector<CTransactionRef> transactions;
124
125 LOCK2(::cs_main, pool.cs);
126 LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 100)
127 {
129 assert(!available_coins.empty());
130 const size_t num_inputs = std::min(size_t{2}, available_coins.size());
131 const size_t num_outputs = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(2, 5);
132 for (size_t n{0}; n < num_inputs; ++n) {
133 auto prevout = available_coins.at(0);
134 mtx.vin.emplace_back(prevout, CScript());
135 available_coins.pop_front();
136 }
137 for (uint32_t n{0}; n < num_outputs; ++n) {
138 mtx.vout.emplace_back(100, P2WSH_OP_TRUE);
139 }
141
142 // First 2 outputs are available to spend. The rest are added to outpoints to calculate bumpfees.
143 // There is no overlap between spendable coins and outpoints passed to MiniMiner because the
144 // MiniMiner interprets spent coins as to-be-replaced and excludes them.
145 for (uint32_t n{0}; n < num_outputs - 1; ++n) {
146 if (fuzzed_data_provider.ConsumeBool()) {
147 available_coins.emplace_front(tx->GetHash(), n);
148 } else {
149 available_coins.emplace_back(tx->GetHash(), n);
150 }
151 }
152
153 // Stop if pool reaches DEFAULT_BLOCK_MAX_WEIGHT because BlockAssembler will stop when the
154 // block template reaches that, but the MiniMiner will keep going.
155 if (pool.GetTotalTxSize() + GetVirtualTransactionSize(*tx) >= DEFAULT_BLOCK_MAX_WEIGHT) break;
157 const CAmount fee{ConsumeMoney(fuzzed_data_provider, /*max=*/MAX_MONEY/100000)};
159 AddToMempool(pool, entry.Fee(fee).FromTx(tx));
160 transactions.push_back(tx);
161 }
162 std::vector<COutPoint> outpoints;
163 for (const auto& coin : g_available_coins) {
164 if (!pool.GetConflictTx(coin)) outpoints.push_back(coin);
165 }
166 for (const auto& tx : transactions) {
167 assert(pool.exists(GenTxid::Txid(tx->GetHash())));
168 for (uint32_t n{0}; n < tx->vout.size(); ++n) {
169 COutPoint coin{tx->GetHash(), n};
170 if (!pool.GetConflictTx(coin)) outpoints.push_back(coin);
171 }
172 }
173 const CFeeRate target_feerate{ConsumeMoney(fuzzed_data_provider, /*max=*/MAX_MONEY/100000)};
174
175 node::BlockAssembler::Options miner_options;
176 miner_options.blockMinFeeRate = target_feerate;
178 miner_options.test_block_validity = false;
179 miner_options.coinbase_output_script = CScript() << OP_0;
180
181 node::BlockAssembler miner{g_setup->m_node.chainman->ActiveChainstate(), &pool, miner_options};
182 node::MiniMiner mini_miner{pool, outpoints};
183 assert(mini_miner.IsReadyToCalculate());
184
185 // Use BlockAssembler as oracle. BlockAssembler and MiniMiner should select the same
186 // transactions, stopping once packages do not meet target_feerate.
187 const auto blocktemplate{miner.CreateNewBlock()};
188 mini_miner.BuildMockTemplate(target_feerate);
189 assert(!mini_miner.IsReadyToCalculate());
190 auto mock_template_txids = mini_miner.GetMockTemplateTxids();
191 // MiniMiner doesn't add a coinbase tx.
192 assert(mock_template_txids.count(blocktemplate->block.vtx[0]->GetHash()) == 0);
193 auto [iter, new_entry] = mock_template_txids.emplace(blocktemplate->block.vtx[0]->GetHash());
194 assert(new_entry);
195
196 assert(mock_template_txids.size() == blocktemplate->block.vtx.size());
197 for (const auto& tx : blocktemplate->block.vtx) {
198 assert(mock_template_txids.count(tx->GetHash()));
199 }
200}
201} // namespace
static constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:26
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:27
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
#define Assert(val)
Identity function.
Definition: check.h:85
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:33
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:29
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:415
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:304
static GenTxid Txid(const uint256 &hash)
Definition: transaction.h:434
Generate a new block, without valid proof-of-work.
Definition: miner.h:140
A minimal version of BlockAssembler, using the same ancestor set scoring algorithm.
Definition: mini_miner.h:79
static transaction_identifier FromUint256(const uint256 &id)
static const uint256 ZERO
Definition: uint256.h:198
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
#define FUZZ_TARGET(...)
Definition: fuzz.h:35
#define LIMITED_WHILE(condition, limit)
Can be used to limit a theoretically unbounded loop.
Definition: fuzz.h:22
AddToMempool(pool, CTxMemPoolEntry(tx, fee, nTime, nHeight, sequence, spendsCoinbase, sigOpCost, lp))
uint64_t fee
int64_t GetVirtualTransactionSize(int64_t nWeight, int64_t nSigOpCost, unsigned int bytes_per_sigop)
Compute the virtual transaction size (weight reinterpreted as bytes).
Definition: policy.cpp:312
static constexpr unsigned int DEFAULT_BLOCK_MAX_WEIGHT
Default for -blockmaxweight, which controls the range of block weights the mining code will create.
Definition: policy.h:23
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:424
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
@ OP_0
Definition: script.h:76
node::NodeContext m_node
Definition: setup_common.h:65
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
Definition: txmempool.h:19
CTxMemPoolEntry FromTx(const CMutableTransaction &tx) const
Definition: txmempool.cpp:33
TestMemPoolEntryHelper & Fee(CAmount _fee)
Definition: txmempool.h:33
Testing setup that configures a complete environment.
Definition: setup_common.h:120
Bilingual messages:
Definition: translation.h:21
bool empty() const
Definition: translation.h:32
Options struct containing options for constructing a CTxMemPool.
CScript coinbase_output_script
Script to put in the coinbase transaction.
Definition: types.h:62
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:72
#define LOCK2(cs1, cs2)
Definition: sync.h:258
CAmount ConsumeMoney(FuzzedDataProvider &fuzzed_data_provider, const std::optional< CAmount > &max) noexcept
Definition: util.cpp:29
void SeedRandomStateForTest(SeedRand seedtype)
Seed the global RNG state for testing and log the seed value.
Definition: random.cpp:19
@ ZEROS
Seed with a compile time constant of zeros.
static const CScript P2WSH_OP_TRUE
Definition: script.h:12
assert(!tx.IsCoinBase())