mini_miner.cpp raw
1 // Copyright (c) The Limenka developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5 #include <test/fuzz/FuzzedDataProvider.h>
6 #include <test/fuzz/fuzz.h>
7 #include <test/fuzz/util.h>
8 #include <test/fuzz/util/mempool.h>
9 #include <test/util/script.h>
10 #include <test/util/setup_common.h>
11 #include <test/util/txmempool.h>
12 #include <test/util/mining.h>
13
14 #include <node/miner.h>
15 #include <node/mini_miner.h>
16 #include <node/types.h>
17 #include <primitives/transaction.h>
18 #include <random.h>
19 #include <txmempool.h>
20 #include <util/check.h>
21 #include <util/time.h>
22 #include <util/translation.h>
23
24 #include <deque>
25 #include <vector>
26
27 namespace {
28
29 const TestingSetup* g_setup;
30 std::deque<COutPoint> g_available_coins;
31 void initialize_miner()
32 {
33 static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>();
34 g_setup = testing_setup.get();
35 MineBlock(g_setup->m_node, {.coinbase_output_script = CScript() << OP_FALSE});
36 for (uint32_t i = 0; i < uint32_t{100}; ++i) {
37 g_available_coins.emplace_back(Txid::FromUint256(uint256::ZERO), i);
38 }
39 g_setup->m_node.args->ForceSetArg("-blockprioritysize", "0");
40 }
41
42 // Test that the MiniMiner can run with various outpoints and feerates.
43 FUZZ_TARGET(mini_miner, .init = initialize_miner)
44 {
45 SeedRandomStateForTest(SeedRand::ZEROS);
46 FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
47 SetMockTime(ConsumeTime(fuzzed_data_provider));
48 bilingual_str error;
49 CTxMemPool pool{CTxMemPool::Options{}, error};
50 Assert(error.empty());
51 std::vector<COutPoint> outpoints;
52 std::deque<COutPoint> available_coins = g_available_coins;
53 LOCK2(::cs_main, pool.cs);
54 // Cluster size cannot exceed 500
55 LIMITED_WHILE(!available_coins.empty(), 500)
56 {
57 CMutableTransaction mtx = CMutableTransaction();
58 const size_t num_inputs = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(1, available_coins.size());
59 const size_t num_outputs = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(1, 50);
60 for (size_t n{0}; n < num_inputs; ++n) {
61 auto prevout = available_coins.front();
62 mtx.vin.emplace_back(prevout, CScript());
63 available_coins.pop_front();
64 }
65 for (uint32_t n{0}; n < num_outputs; ++n) {
66 mtx.vout.emplace_back(100, P2WSH_OP_TRUE);
67 }
68 CTransactionRef tx = MakeTransactionRef(mtx);
69 TestMemPoolEntryHelper entry;
70 const CAmount fee{ConsumeMoney(fuzzed_data_provider, /*max=*/MAX_MONEY/100000)};
71 assert(MoneyRange(fee));
72 AddToMempool(pool, entry.Fee(fee).FromTx(tx));
73
74 // All outputs are available to spend
75 for (uint32_t n{0}; n < num_outputs; ++n) {
76 if (fuzzed_data_provider.ConsumeBool()) {
77 available_coins.emplace_back(tx->GetHash(), n);
78 }
79 }
80
81 if (fuzzed_data_provider.ConsumeBool() && !tx->vout.empty()) {
82 // Add outpoint from this tx (may or not be spent by a later tx)
83 outpoints.emplace_back(tx->GetHash(),
84 (uint32_t)fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, tx->vout.size()));
85 } else {
86 // Add some random outpoint (will be interpreted as confirmed or not yet submitted
87 // to mempool).
88 auto outpoint = ConsumeDeserializable<COutPoint>(fuzzed_data_provider);
89 if (outpoint.has_value() && std::find(outpoints.begin(), outpoints.end(), *outpoint) == outpoints.end()) {
90 outpoints.push_back(*outpoint);
91 }
92 }
93
94 }
95
96 const CFeeRate target_feerate{CFeeRate{ConsumeMoney(fuzzed_data_provider, /*max=*/MAX_MONEY/1000)}};
97 std::optional<CAmount> total_bumpfee;
98 CAmount sum_fees = 0;
99 {
100 node::MiniMiner mini_miner{pool, outpoints};
101 assert(mini_miner.IsReadyToCalculate());
102 const auto bump_fees = mini_miner.CalculateBumpFees(target_feerate);
103 for (const auto& outpoint : outpoints) {
104 auto it = bump_fees.find(outpoint);
105 assert(it != bump_fees.end());
106 assert(it->second >= 0);
107 sum_fees += it->second;
108 }
109 assert(!mini_miner.IsReadyToCalculate());
110 }
111 {
112 node::MiniMiner mini_miner{pool, outpoints};
113 assert(mini_miner.IsReadyToCalculate());
114 total_bumpfee = mini_miner.CalculateTotalBumpFees(target_feerate);
115 assert(total_bumpfee.has_value());
116 assert(!mini_miner.IsReadyToCalculate());
117 }
118 // Overlapping ancestry across multiple outpoints can only reduce the total bump fee.
119 assert (sum_fees >= *total_bumpfee);
120 }
121
122 // Test that MiniMiner and BlockAssembler build the same block given the same transactions and constraints.
123 FUZZ_TARGET(mini_miner_selection, .init = initialize_miner)
124 {
125 SeedRandomStateForTest(SeedRand::ZEROS);
126 FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
127 SetMockTime(ConsumeTime(fuzzed_data_provider));
128 bilingual_str error;
129 CTxMemPool pool{CTxMemPool::Options{}, error};
130 Assert(error.empty());
131 // Make a copy to preserve determinism.
132 std::deque<COutPoint> available_coins = g_available_coins;
133 std::vector<CTransactionRef> transactions;
134
135 LOCK2(::cs_main, pool.cs);
136 LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 100)
137 {
138 CMutableTransaction mtx = CMutableTransaction();
139 assert(!available_coins.empty());
140 const size_t num_inputs = std::min(size_t{2}, available_coins.size());
141 const size_t num_outputs = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(2, 5);
142 for (size_t n{0}; n < num_inputs; ++n) {
143 auto prevout = available_coins.at(0);
144 mtx.vin.emplace_back(prevout, CScript());
145 available_coins.pop_front();
146 }
147 for (uint32_t n{0}; n < num_outputs; ++n) {
148 mtx.vout.emplace_back(100, P2WSH_OP_TRUE);
149 }
150 CTransactionRef tx = MakeTransactionRef(mtx);
151
152 // First 2 outputs are available to spend. The rest are added to outpoints to calculate bumpfees.
153 // There is no overlap between spendable coins and outpoints passed to MiniMiner because the
154 // MiniMiner interprets spent coins as to-be-replaced and excludes them.
155 for (uint32_t n{0}; n < num_outputs - 1; ++n) {
156 if (fuzzed_data_provider.ConsumeBool()) {
157 available_coins.emplace_front(tx->GetHash(), n);
158 } else {
159 available_coins.emplace_back(tx->GetHash(), n);
160 }
161 }
162
163 const auto block_adjusted_max_weight = MAX_BLOCK_WEIGHT - DEFAULT_BLOCK_RESERVED_WEIGHT;
164 // Stop if pool reaches block_adjusted_max_weight because BlockAssembler will stop when the
165 // block template reaches that, but the MiniMiner will keep going.
166 if (pool.GetTotalTxSize() + GetVirtualTransactionSize(*tx) >= block_adjusted_max_weight) break;
167 TestMemPoolEntryHelper entry;
168 const CAmount fee{ConsumeMoney(fuzzed_data_provider, /*max=*/MAX_MONEY/100000)};
169 assert(MoneyRange(fee));
170 AddToMempool(pool, entry.Fee(fee).FromTx(tx));
171 transactions.push_back(tx);
172 }
173 std::vector<COutPoint> outpoints;
174 for (const auto& coin : g_available_coins) {
175 if (!pool.GetConflictTx(coin)) outpoints.push_back(coin);
176 }
177 for (const auto& tx : transactions) {
178 assert(pool.exists(GenTxid::Txid(tx->GetHash())));
179 for (uint32_t n{0}; n < tx->vout.size(); ++n) {
180 COutPoint coin{tx->GetHash(), n};
181 if (!pool.GetConflictTx(coin)) outpoints.push_back(coin);
182 }
183 }
184 const CFeeRate target_feerate{ConsumeMoney(fuzzed_data_provider, /*max=*/MAX_MONEY/100000)};
185
186 node::BlockAssembler::Options miner_options;
187 miner_options.blockMinFeeRate = target_feerate;
188 miner_options.nBlockMaxWeight = MAX_BLOCK_WEIGHT;
189 miner_options.test_block_validity = false;
190 miner_options.coinbase_output_script = CScript() << OP_0;
191
192 node::BlockAssembler miner{g_setup->m_node.chainman->ActiveChainstate(), &pool, miner_options, g_setup->m_node};
193 node::MiniMiner mini_miner{pool, outpoints};
194 assert(mini_miner.IsReadyToCalculate());
195
196 // Use BlockAssembler as oracle. BlockAssembler and MiniMiner should select the same
197 // transactions, stopping once packages do not meet target_feerate.
198 const auto blocktemplate{miner.CreateNewBlock()};
199 mini_miner.BuildMockTemplate(target_feerate);
200 assert(!mini_miner.IsReadyToCalculate());
201 auto mock_template_txids = mini_miner.GetMockTemplateTxids();
202 // MiniMiner doesn't add a coinbase tx.
203 assert(mock_template_txids.count(blocktemplate->block.vtx[0]->GetHash()) == 0);
204 auto [iter, new_entry] = mock_template_txids.emplace(blocktemplate->block.vtx[0]->GetHash());
205 assert(new_entry);
206
207 assert(mock_template_txids.size() == blocktemplate->block.vtx.size());
208 for (const auto& tx : blocktemplate->block.vtx) {
209 assert(mock_template_txids.count(tx->GetHash()));
210 }
211 }
212 } // namespace
213