Bitcoin Core 32.99.0
P2P Digital Currency
miner_tests.cpp
Go to the documentation of this file.
1// Copyright (c) 2011-present The Bitcoin Core 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 <addresstype.h>
6#include <chain.h>
7#include <coins.h>
8#include <consensus/amount.h>
10#include <consensus/merkle.h>
11#include <consensus/tx_verify.h>
12#include <interfaces/mining.h>
13#include <interfaces/types.h>
14#include <kernel/chainparams.h>
16#include <node/miner.h>
17#include <node/mining_args.h>
18#include <node/mining_types.h>
19#include <policy/feerate.h>
20#include <policy/policy.h>
21#include <pow.h>
22#include <primitives/block.h>
24#include <random.h>
25#include <script/script.h>
26#include <serialize.h>
27#include <sync.h>
28#include <test/util/common.h>
31#include <test/util/time.h>
32#include <test/util/txmempool.h>
33#include <txmempool.h>
34#include <uint256.h>
35#include <util/check.h>
36#include <util/feefrac.h>
37#include <util/strencodings.h>
38#include <util/translation.h>
39#include <validation.h>
40#include <versionbits.h>
41
42#include <boost/test/unit_test.hpp>
43
44#include <cstddef>
45#include <cstdint>
46#include <iterator>
47#include <memory>
48#include <optional>
49#include <span>
50#include <stdexcept>
51#include <string>
52#include <vector>
53
54using namespace util::hex_literals;
58
59namespace miner_tests {
61 void TestPackageSelection(const CScript& scriptPubKey, const std::vector<CTransactionRef>& txFirst) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
62 void TestBasicMining(const CScript& scriptPubKey, const std::vector<CTransactionRef>& txFirst, int baseheight) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
63 void TestPrioritisedMining(const CScript& scriptPubKey, const std::vector<CTransactionRef>& txFirst) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
64 void TestSigOpsAdjustedWeightChunkLimit(const CScript& scriptPubKey, const std::vector<CTransactionRef>& txFirst) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
66 {
67 CCoinsViewMemPool view_mempool{&m_node.chainman->ActiveChainstate().CoinsTip(), tx_mempool};
68 CBlockIndex* tip{m_node.chainman->ActiveChain().Tip()};
69 const std::optional<LockPoints> lock_points{CalculateLockPointsAtTip(tip, view_mempool, tx)};
70 return lock_points.has_value() && CheckSequenceLocksAtTip(tip, *lock_points);
71 }
73 {
75 // Delete the previous mempool to ensure with valgrind that the old
76 // pointer is not accessed, when the new one should be accessed
77 // instead.
78 m_node.mempool.reset();
79 bilingual_str error;
80 auto opts = MemPoolOptionsForTest(m_node);
81 // The "block size > limit" test creates a cluster of 1192590 vbytes,
82 // so set the cluster vbytes limit big enough so that the txgraph
83 // doesn't become oversized.
84 opts.limits.cluster_size_vbytes = 1'200'000;
85 m_node.mempool = std::make_unique<CTxMemPool>(opts, error);
86 Assert(error.empty());
88 return *m_node.mempool;
89 }
90 std::unique_ptr<Mining> MakeMining()
91 {
92 return interfaces::MakeMining(m_node, /*wait_loaded=*/false);
93 }
94};
95} // namespace miner_tests
96
97BOOST_FIXTURE_TEST_SUITE(miner_tests, MinerTestingSetup)
98
100
101constexpr static struct {
102 unsigned int extranonce;
103 unsigned int nonce;
104} BLOCKINFO[]{{0, 3552706918}, {500, 37506755}, {1000, 948987788}, {400, 524762339}, {800, 258510074}, {300, 102309278},
105 {1300, 54365202}, {600, 1107740426}, {1000, 203094491}, {900, 391178848}, {800, 381177271}, {600, 87188412},
106 {0, 66522866}, {800, 874942736}, {1000, 89200838}, {400, 312638088}, {400, 66263693}, {500, 924648304},
107 {400, 369913599}, {500, 47630099}, {500, 115045364}, {100, 277026602}, {1100, 809621409}, {700, 155345322},
108 {800, 943579953}, {400, 28200730}, {900, 77200495}, {0, 105935488}, {400, 698721821}, {500, 111098863},
109 {1300, 445389594}, {500, 621849894}, {1400, 56010046}, {1100, 370669776}, {1200, 380301940}, {1200, 110654905},
110 {400, 213771024}, {1500, 120014726}, {1200, 835019014}, {1500, 624817237}, {900, 1404297}, {400, 189414558},
111 {400, 293178348}, {1100, 15393789}, {600, 396764180}, {800, 1387046371}, {800, 199368303}, {700, 111496662},
112 {100, 129759616}, {200, 536577982}, {500, 125881300}, {500, 101053391}, {1200, 471590548}, {900, 86957729},
113 {1200, 179604104}, {600, 68658642}, {1000, 203295701}, {500, 139615361}, {900, 233693412}, {300, 153225163},
114 {0, 27616254}, {1200, 9856191}, {100, 220392722}, {200, 66257599}, {1100, 145489641}, {1300, 37859442},
115 {400, 5816075}, {1200, 215752117}, {1400, 32361482}, {1400, 6529223}, {500, 143332977}, {800, 878392},
116 {700, 159290408}, {400, 123197595}, {700, 43988693}, {300, 304224916}, {700, 214771621}, {1100, 274148273},
117 {400, 285632418}, {1100, 923451065}, {600, 12818092}, {1200, 736282054}, {1000, 246683167}, {600, 92950402},
118 {1400, 29223405}, {1000, 841327192}, {700, 174301283}, {1400, 214009854}, {1000, 6989517}, {1200, 278226956},
119 {700, 540219613}, {400, 93663104}, {1100, 152345635}, {1500, 464194499}, {1300, 333850111}, {600, 258311263},
120 {600, 90173162}, {1000, 33590797}, {1500, 332866027}, {100, 204704427}, {1000, 463153545}, {800, 303244785},
121 {600, 88096214}, {0, 137477892}, {1200, 195514506}, {300, 704114595}, {900, 292087369}, {1400, 758684870},
122 {1300, 163493028}, {1200, 53151293}};
123
124static std::unique_ptr<CBlockIndex> CreateBlockIndex(int nHeight, CBlockIndex* active_chain_tip) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
125{
126 auto index{std::make_unique<CBlockIndex>()};
127 index->nHeight = nHeight;
128 index->pprev = active_chain_tip;
129 return index;
130}
131
132// Test suite for ancestor feerate transaction selection.
133// Implemented as an additional function, rather than a separate test case,
134// to allow reusing the blockchain created in CreateNewBlock_validity.
135void MinerTestingSetup::TestPackageSelection(const CScript& scriptPubKey, const std::vector<CTransactionRef>& txFirst)
136{
137 CTxMemPool& tx_mempool{MakeMempool()};
138 auto mining{MakeMining()};
139 BlockCreateOptions options{
140 .coinbase_output_script = scriptPubKey,
141 };
142
143 LOCK(tx_mempool.cs);
144 BOOST_CHECK(tx_mempool.size() == 0);
145
146 // Block template should only have a coinbase when there's nothing in the mempool
147 std::unique_ptr<BlockTemplate> block_template = mining->createNewBlock(options, /*cooldown=*/false);
148 BOOST_REQUIRE(block_template);
149 CBlock block{block_template->getBlock()};
150 BOOST_REQUIRE_EQUAL(block.vtx.size(), 1U);
151
152 // waitNext() on an empty mempool should return nullptr because there is no better template
153 auto should_be_nullptr = block_template->waitNext({.timeout = MillisecondsDouble{0}, .fee_threshold = 1});
154 BOOST_REQUIRE(should_be_nullptr == nullptr);
155
156 // Unless fee_threshold is 0
157 block_template = block_template->waitNext({.timeout = MillisecondsDouble{0}, .fee_threshold = 0});
158 BOOST_REQUIRE(block_template);
159
160 // Test the ancestor feerate transaction selection.
162
163 // Test that a medium fee transaction will be selected after a higher fee
164 // rate package with a low fee rate parent.
166 tx.vin.resize(1);
167 tx.vin[0].scriptSig = CScript() << OP_1;
168 tx.vin[0].prevout.hash = txFirst[0]->GetHash();
169 tx.vin[0].prevout.n = 0;
170 tx.vout.resize(1);
171 tx.vout[0].nValue = 5000000000LL - 1000;
172 // This tx has a low fee: 1000 satoshis
173 Txid hashParentTx = tx.GetHash(); // save this txid for later use
174 const auto parent_tx{entry.Fee(1000).Time(Now<NodeSeconds>()).SpendsCoinbase(true).FromTx(tx)};
175 TryAddToMempool(tx_mempool, parent_tx);
176
177 // This tx has a medium fee: 10000 satoshis
178 tx.vin[0].prevout.hash = txFirst[1]->GetHash();
179 tx.vout[0].nValue = 5000000000LL - 10000;
180 Txid hashMediumFeeTx = tx.GetHash();
181 const auto medium_fee_tx{entry.Fee(10000).Time(Now<NodeSeconds>()).SpendsCoinbase(true).FromTx(tx)};
182 TryAddToMempool(tx_mempool, medium_fee_tx);
183
184 // This tx has a high fee, but depends on the first transaction
185 tx.vin[0].prevout.hash = hashParentTx;
186 tx.vout[0].nValue = 5000000000LL - 1000 - 50000; // 50k satoshi fee
187 Txid hashHighFeeTx = tx.GetHash();
188 const auto high_fee_tx{entry.Fee(50000).Time(Now<NodeSeconds>()).SpendsCoinbase(false).FromTx(tx)};
189 TryAddToMempool(tx_mempool, high_fee_tx);
190
191 // Test getTransactionsByTxID()
192 const std::vector<Txid> tx_id_list{
193 hashParentTx,
194 Txid::FromUint256(uint256::ZERO) // non-existing tx
195 };
196 auto raw_txs = mining->getTransactionsByTxID(tx_id_list);
197 BOOST_REQUIRE_EQUAL(raw_txs.size(), tx_id_list.size());
198 BOOST_CHECK(raw_txs[0]);
199 BOOST_CHECK(raw_txs[0]->GetHash() == hashParentTx);
200 BOOST_CHECK(!raw_txs[1]);
201 // Test getTransactionsByWitnessID()
202 // tx has no witness, so just cast to Wtxid
203 const std::vector<Wtxid> wtx_id_list{
204 Wtxid::FromUint256(hashParentTx.ToUint256()),
206 };
207 raw_txs = mining->getTransactionsByWitnessID(wtx_id_list);
208 BOOST_REQUIRE_EQUAL(raw_txs.size(), tx_id_list.size());
209 BOOST_CHECK(raw_txs[0]);
210 BOOST_CHECK(raw_txs[0]->GetHash() == hashParentTx);
211 BOOST_CHECK(!raw_txs[1]);
212 block_template = mining->createNewBlock(options, /*cooldown=*/false);
213 BOOST_REQUIRE(block_template);
214 block = block_template->getBlock();
215 BOOST_REQUIRE_EQUAL(block.vtx.size(), 4U);
216 BOOST_CHECK(block.vtx[1]->GetHash() == hashParentTx);
217 BOOST_CHECK(block.vtx[2]->GetHash() == hashHighFeeTx);
218 BOOST_CHECK(block.vtx[3]->GetHash() == hashMediumFeeTx);
219
220 // Test the inclusion of package feerates in the block template and ensure they are sequential.
221 // Can't use the Mining interface because it needs access to m_package_feerates.
222 const auto block_package_feerates = Assert(m_node.block_template_manager)->CreateNewTemplate(options)->m_package_feerates;
223 BOOST_CHECK(block_package_feerates.size() == 2);
224
225 // parent_tx and high_fee_tx are added to the block as a package.
226 const auto combined_txs_fee = parent_tx.GetFee() + high_fee_tx.GetFee();
227 const auto combined_txs_size = parent_tx.GetTxSize() + high_fee_tx.GetTxSize();
228 FeeFrac package_feefrac{combined_txs_fee, combined_txs_size};
229 // The package should be added first.
230 BOOST_CHECK(block_package_feerates[0] == package_feefrac);
231
232 // The medium_fee_tx should be added next.
233 FeeFrac medium_tx_feefrac{medium_fee_tx.GetFee(), medium_fee_tx.GetTxSize()};
234 BOOST_CHECK(block_package_feerates[1] == medium_tx_feefrac);
235
236 // Test that a package below the block min tx fee doesn't get included
237 tx.vin[0].prevout.hash = hashHighFeeTx;
238 tx.vout[0].nValue = 5000000000LL - 1000 - 50000; // 0 fee
239 Txid hashFreeTx = tx.GetHash();
240 TryAddToMempool(tx_mempool, entry.Fee(0).FromTx(tx));
241 uint64_t freeTxSize{::GetSerializeSize(TX_WITH_WITNESS(tx))};
242
243 // Calculate a fee on child transaction that will put the package just
244 // below the block min tx fee (assuming 1 child tx of the same size).
245 CAmount feeToUse = blockMinFeeRate.GetFee(2*freeTxSize) - 1;
246
247 tx.vin[0].prevout.hash = hashFreeTx;
248 tx.vout[0].nValue = 5000000000LL - 1000 - 50000 - feeToUse;
249 Txid hashLowFeeTx = tx.GetHash();
250 TryAddToMempool(tx_mempool, entry.Fee(feeToUse).FromTx(tx));
251
252 // waitNext() should return nullptr because there is no better template
253 should_be_nullptr = block_template->waitNext({.timeout = MillisecondsDouble{0}, .fee_threshold = 1});
254 BOOST_REQUIRE(should_be_nullptr == nullptr);
255
256 block = block_template->getBlock();
257 // Verify that the free tx and the low fee tx didn't get selected
258 for (size_t i=0; i<block.vtx.size(); ++i) {
259 BOOST_CHECK(block.vtx[i]->GetHash() != hashFreeTx);
260 BOOST_CHECK(block.vtx[i]->GetHash() != hashLowFeeTx);
261 }
262
263 // Test that packages above the min relay fee do get included, even if one
264 // of the transactions is below the min relay fee
265 // Remove the low fee transaction and replace with a higher fee transaction
266 tx_mempool.removeRecursive(CTransaction(tx), MemPoolRemovalReason::REPLACED);
267 tx.vout[0].nValue -= 2; // Now we should be just over the min relay fee
268 hashLowFeeTx = tx.GetHash();
269 TryAddToMempool(tx_mempool, entry.Fee(feeToUse + 2).FromTx(tx));
270
271 // waitNext() should return if fees for the new template are at least 1 sat up
272 block_template = block_template->waitNext({.fee_threshold = 1});
273 BOOST_REQUIRE(block_template);
274 block = block_template->getBlock();
275 BOOST_REQUIRE_EQUAL(block.vtx.size(), 6U);
276 BOOST_CHECK(block.vtx[4]->GetHash() == hashFreeTx);
277 BOOST_CHECK(block.vtx[5]->GetHash() == hashLowFeeTx);
278
279 // Test that transaction selection properly updates ancestor fee
280 // calculations as ancestor transactions get included in a block.
281 // Add a 0-fee transaction that has 2 outputs.
282 tx.vin[0].prevout.hash = txFirst[2]->GetHash();
283 tx.vout.resize(2);
284 tx.vout[0].nValue = 5000000000LL - 100000000;
285 tx.vout[1].nValue = 100000000; // 1BTC output
286 // Increase size to avoid rounding errors: when the feerate is extremely small (i.e. 1sat/kvB), evaluating the fee
287 // at smaller sizes gives us rounded values that are equal to each other, which means we incorrectly include
288 // hashFreeTx2 + hashLowFeeTx2.
289 BulkTransaction(tx, 4000);
290 Txid hashFreeTx2 = tx.GetHash();
291 TryAddToMempool(tx_mempool, entry.Fee(0).SpendsCoinbase(true).FromTx(tx));
292
293 // This tx can't be mined by itself
294 tx.vin[0].prevout.hash = hashFreeTx2;
295 tx.vout.resize(1);
296 feeToUse = blockMinFeeRate.GetFee(freeTxSize);
297 tx.vout[0].nValue = 5000000000LL - 100000000 - feeToUse;
298 Txid hashLowFeeTx2 = tx.GetHash();
299 TryAddToMempool(tx_mempool, entry.Fee(feeToUse).SpendsCoinbase(false).FromTx(tx));
300 block_template = mining->createNewBlock(options, /*cooldown=*/false);
301 BOOST_REQUIRE(block_template);
302 block = block_template->getBlock();
303
304 // Verify that this tx isn't selected.
305 for (size_t i=0; i<block.vtx.size(); ++i) {
306 BOOST_CHECK(block.vtx[i]->GetHash() != hashFreeTx2);
307 BOOST_CHECK(block.vtx[i]->GetHash() != hashLowFeeTx2);
308 }
309
310 // This tx will be mineable, and should cause hashLowFeeTx2 to be selected
311 // as well.
312 tx.vin[0].prevout.n = 1;
313 tx.vout[0].nValue = 100000000 - 10000; // 10k satoshi fee
314 TryAddToMempool(tx_mempool, entry.Fee(10000).FromTx(tx));
315 block_template = mining->createNewBlock(options, /*cooldown=*/false);
316 BOOST_REQUIRE(block_template);
317 block = block_template->getBlock();
318 BOOST_REQUIRE_EQUAL(block.vtx.size(), 9U);
319 BOOST_CHECK(block.vtx[8]->GetHash() == hashLowFeeTx2);
320}
321
322// One sigop-dense tx spending `input`: num_outputs bare CHECKMULTISIG outputs,
323// i.e. 20 * num_outputs legacy sigops (OP_NOP forces the inaccurate max-20 count).
324static CMutableTransaction CreateBigSigOpsTx(const COutPoint& input, unsigned int num_outputs)
325{
327 tx.vin.resize(1);
328 tx.vin[0].prevout = input;
329 tx.vin[0].scriptSig = CScript() << OP_1;
330 tx.vout.resize(num_outputs);
331 for (auto& out : tx.vout) {
332 out.nValue = 0;
333 out.scriptPubKey = CScript() << OP_0 << OP_0 << OP_0 << OP_NOP << OP_CHECKMULTISIG << OP_1;
334 }
335 return tx;
336}
337
338std::vector<CTransactionRef> CreateBigSigOpsCluster(const CTransactionRef& first_tx)
339{
340 std::vector<CTransactionRef> ret;
341
343 // block sigops > limit: 1000 CHECKMULTISIG + 1
344 tx.vin.resize(1);
345 // NOTE: OP_NOP is used to force 20 SigOps for the CHECKMULTISIG
346 tx.vin[0].scriptSig = CScript() << OP_0 << OP_0 << OP_CHECKSIG << OP_1;
347 tx.vin[0].prevout.hash = first_tx->GetHash();
348 tx.vin[0].prevout.n = 0;
349 tx.vout.resize(50);
350 for (auto &out : tx.vout) {
351 out.nValue = first_tx->vout[0].nValue / 50;
352 out.scriptPubKey = CScript() << OP_1;
353 }
354
355 tx.vout[0].nValue -= CENT;
356 CTransactionRef parent_tx = MakeTransactionRef(tx);
357 ret.push_back(parent_tx);
358 assert(GetLegacySigOpCount(*parent_tx) == 1);
359
360 // Tx1 has 1 sigops, 1 input, 50 outputs.
361 // Tx2-51 has 400 sigops: 1 input, 20 CHECKMULTISIG outputs
362 // Total: 1000 CHECKMULTISIG + 1
363 for (unsigned int i = 0; i < 50; ++i) {
364 ret.push_back(MakeTransactionRef(CreateBigSigOpsTx(COutPoint{parent_tx->GetHash(), i}, /*num_outputs=*/20)));
365 }
366 return ret;
367}
368
369void MinerTestingSetup::TestSigOpsAdjustedWeightChunkLimit(const CScript& scriptPubKey, const std::vector<CTransactionRef>& txFirst)
370{
371 auto mining{MakeMining()};
372 BOOST_REQUIRE(mining);
373
374 CTxMemPool& tx_mempool{MakeMempool()};
375 LOCK(tx_mempool.cs);
377
378 const auto tx{CreateBigSigOpsTx(COutPoint{txFirst[0]->GetHash(), 0}, /*num_outputs=*/50)};
379 const auto sigop_entry{entry.Fee(COIN).SpendsCoinbase(true).SigOpsCost(GetLegacySigOpCount(CTransaction(tx)) * WITNESS_SCALE_FACTOR).FromTx(tx)};
380 BOOST_REQUIRE(sigop_entry.GetAdjustedWeight() > sigop_entry.GetTxWeight());
381 BOOST_REQUIRE(sigop_entry.GetSigOpCost() < MAX_BLOCK_SIGOPS_COST);
382 TryAddToMempool(tx_mempool, sigop_entry);
383
384 BlockCreateOptions options{
385 // +1 because TestChunkBlockLimits rejects on >= (exact fit doesn't count).
386 .block_max_weight = DEFAULT_BLOCK_RESERVED_WEIGHT + sigop_entry.GetTxWeight() + 1,
387 .coinbase_output_script = scriptPubKey,
388 };
389 const CBlock block{mining->createNewBlock(options, /*cooldown=*/false)->getBlock()};
390 BOOST_CHECK_EQUAL(block.vtx.size(), 2U);
391 BOOST_CHECK(block.vtx[1]->GetHash() == tx.GetHash());
392}
393
394void MinerTestingSetup::TestBasicMining(const CScript& scriptPubKey, const std::vector<CTransactionRef>& txFirst, int baseheight)
395{
397
398 Txid hash;
401 entry.nFee = 11;
402 entry.nHeight = 11;
403
404 const CAmount BLOCKSUBSIDY = 50 * COIN;
405 const CAmount LOWFEE = CENT;
406 const CAmount HIGHFEE = COIN;
407 const CAmount HIGHERFEE = 4 * COIN;
408
409 auto mining{MakeMining()};
410 BOOST_REQUIRE(mining);
411
412 BlockCreateOptions options{
413 .coinbase_output_script = scriptPubKey,
414 };
415
416 {
417 CTxMemPool& tx_mempool{MakeMempool()};
418 LOCK(tx_mempool.cs);
419
420 // Just to make sure we can still make simple blocks
421 auto block_template{mining->createNewBlock(options, /*cooldown=*/false)};
422 BOOST_REQUIRE(block_template);
423 CBlock block{block_template->getBlock()};
424
425 auto txs = CreateBigSigOpsCluster(txFirst[0]);
426
427 int64_t legacy_sigops = 0;
428 for (auto& t : txs) {
429 // If we don't set the number of sigops in the CTxMemPoolEntry,
430 // template creation fails during sanity checks.
431 TryAddToMempool(tx_mempool, entry.Fee(LOWFEE).Time(Now<NodeSeconds>()).SpendsCoinbase(true).FromTx(t));
432 legacy_sigops += GetLegacySigOpCount(*t);
433 BOOST_CHECK(tx_mempool.GetIter(t->GetHash()).has_value());
434 }
435 assert(tx_mempool.mapTx.size() == 51);
436 assert(legacy_sigops == 20001);
437 BOOST_CHECK_EXCEPTION(mining->createNewBlock(options, /*cooldown=*/false), std::runtime_error, HasReason("bad-blk-sigops"));
438 }
439
440 {
441 CTxMemPool& tx_mempool{MakeMempool()};
442 LOCK(tx_mempool.cs);
443
444 // Check that the mempool is empty.
445 assert(tx_mempool.mapTx.empty());
446
447 // Just to make sure we can still make simple blocks
448 auto block_template{mining->createNewBlock(options, /*cooldown=*/false)};
449 BOOST_REQUIRE(block_template);
450 CBlock block{block_template->getBlock()};
451
452 auto txs = CreateBigSigOpsCluster(txFirst[0]);
453
454 int64_t legacy_sigops = 0;
455 for (auto& t : txs) {
456 TryAddToMempool(tx_mempool, entry.Fee(LOWFEE).Time(Now<NodeSeconds>()).SpendsCoinbase(true).SigOpsCost(GetLegacySigOpCount(*t)*WITNESS_SCALE_FACTOR).FromTx(t));
457 legacy_sigops += GetLegacySigOpCount(*t);
458 BOOST_CHECK(tx_mempool.GetIter(t->GetHash()).has_value());
459 }
460 assert(tx_mempool.mapTx.size() == 51);
461 assert(legacy_sigops == 20001);
462
463 BOOST_REQUIRE(mining->createNewBlock(options, /*cooldown=*/false));
464 }
465
466 {
467 CTxMemPool& tx_mempool{MakeMempool()};
468 LOCK(tx_mempool.cs);
469
470 // block size > limit
471 tx.vin.resize(1);
472 tx.vout.resize(1);
473 tx.vout[0].nValue = BLOCKSUBSIDY;
474 // 36 * (520char + DROP) + OP_1 = 18757 bytes
475 std::vector<unsigned char> vchData(520);
476 for (unsigned int i = 0; i < 18; ++i) {
477 tx.vin[0].scriptSig << vchData << OP_DROP;
478 tx.vout[0].scriptPubKey << vchData << OP_DROP;
479 }
480 tx.vin[0].scriptSig << OP_1;
481 tx.vout[0].scriptPubKey << OP_1;
482 tx.vin[0].prevout.hash = txFirst[0]->GetHash();
483 tx.vin[0].prevout.n = 0;
484 tx.vout[0].nValue = BLOCKSUBSIDY;
485 for (unsigned int i = 0; i < 63; ++i) {
486 tx.vout[0].nValue -= LOWFEE;
487 hash = tx.GetHash();
488 bool spendsCoinbase = i == 0; // only first tx spends coinbase
489 TryAddToMempool(tx_mempool, entry.Fee(LOWFEE).Time(Now<NodeSeconds>()).SpendsCoinbase(spendsCoinbase).FromTx(tx));
490 BOOST_CHECK(tx_mempool.GetIter(hash).has_value());
491 tx.vin[0].prevout.hash = hash;
492 }
493 BOOST_REQUIRE(mining->createNewBlock(options, /*cooldown=*/false));
494 }
495
496 {
497 CTxMemPool& tx_mempool{MakeMempool()};
498 LOCK(tx_mempool.cs);
499
500 // orphan in tx_mempool, template creation fails
501 hash = tx.GetHash();
502 TryAddToMempool(tx_mempool, entry.Fee(LOWFEE).Time(Now<NodeSeconds>()).FromTx(tx));
503 BOOST_CHECK_EXCEPTION(mining->createNewBlock(options, /*cooldown=*/false), std::runtime_error, HasReason("bad-txns-inputs-missingorspent"));
504 }
505
506 {
507 CTxMemPool& tx_mempool{MakeMempool()};
508 LOCK(tx_mempool.cs);
509
510 // child with higher feerate than parent
511 tx.vin[0].scriptSig = CScript() << OP_1;
512 tx.vin[0].prevout.hash = txFirst[1]->GetHash();
513 tx.vout[0].nValue = BLOCKSUBSIDY - HIGHFEE;
514 hash = tx.GetHash();
515 TryAddToMempool(tx_mempool, entry.Fee(HIGHFEE).Time(Now<NodeSeconds>()).SpendsCoinbase(true).FromTx(tx));
516 tx.vin[0].prevout.hash = hash;
517 tx.vin.resize(2);
518 tx.vin[1].scriptSig = CScript() << OP_1;
519 tx.vin[1].prevout.hash = txFirst[0]->GetHash();
520 tx.vin[1].prevout.n = 0;
521 tx.vout[0].nValue = tx.vout[0].nValue + BLOCKSUBSIDY - HIGHERFEE; // First txn output + fresh coinbase - new txn fee
522 hash = tx.GetHash();
523 TryAddToMempool(tx_mempool, entry.Fee(HIGHERFEE).Time(Now<NodeSeconds>()).SpendsCoinbase(true).FromTx(tx));
524 BOOST_REQUIRE(mining->createNewBlock(options, /*cooldown=*/false));
525 }
526
527 {
528 CTxMemPool& tx_mempool{MakeMempool()};
529 LOCK(tx_mempool.cs);
530
531 // coinbase in tx_mempool, template creation fails
532 tx.vin.resize(1);
533 tx.vin[0].prevout.SetNull();
534 tx.vin[0].scriptSig = CScript() << OP_0 << OP_1;
535 tx.vout[0].nValue = 0;
536 hash = tx.GetHash();
537 // give it a fee so it'll get mined
538 TryAddToMempool(tx_mempool, entry.Fee(LOWFEE).Time(Now<NodeSeconds>()).SpendsCoinbase(false).FromTx(tx));
539 // Should throw bad-cb-multiple
540 BOOST_CHECK_EXCEPTION(mining->createNewBlock(options, /*cooldown=*/false), std::runtime_error, HasReason("bad-cb-multiple"));
541 }
542
543 {
544 CTxMemPool& tx_mempool{MakeMempool()};
545 LOCK(tx_mempool.cs);
546
547 // double spend txn pair in tx_mempool, template creation fails
548 tx.vin[0].prevout.hash = txFirst[0]->GetHash();
549 tx.vin[0].scriptSig = CScript() << OP_1;
550 tx.vout[0].nValue = BLOCKSUBSIDY - HIGHFEE;
551 tx.vout[0].scriptPubKey = CScript() << OP_1;
552 hash = tx.GetHash();
553 TryAddToMempool(tx_mempool, entry.Fee(HIGHFEE).Time(Now<NodeSeconds>()).SpendsCoinbase(true).FromTx(tx));
554 tx.vout[0].scriptPubKey = CScript() << OP_2;
555 hash = tx.GetHash();
556 TryAddToMempool(tx_mempool, entry.Fee(HIGHFEE).Time(Now<NodeSeconds>()).SpendsCoinbase(true).FromTx(tx));
557 BOOST_CHECK_EXCEPTION(mining->createNewBlock(options, /*cooldown=*/false), std::runtime_error, HasReason("bad-txns-inputs-missingorspent"));
558 }
559
560 {
561 CTxMemPool& tx_mempool{MakeMempool()};
562 LOCK(tx_mempool.cs);
563
564 // subsidy changing
565 int nHeight = m_node.chainman->ActiveChain().Height();
566 // Create an actual 209999-long block chain (without valid blocks).
567 while (m_node.chainman->ActiveChain().Tip()->nHeight < 209999) {
568 CBlockIndex* prev = m_node.chainman->ActiveChain().Tip();
569 CBlockIndex* next = new CBlockIndex();
570 next->phashBlock = new uint256(m_rng.rand256());
571 m_node.chainman->ActiveChainstate().CoinsTip().SetBestBlock(next->GetBlockHash());
572 next->pprev = prev;
573 next->nHeight = prev->nHeight + 1;
574 next->BuildSkip();
575 m_node.chainman->ActiveChain().SetTip(*next);
576 }
577 BOOST_REQUIRE(mining->createNewBlock(options, /*cooldown=*/false));
578 // Extend to a 210000-long block chain.
579 while (m_node.chainman->ActiveChain().Tip()->nHeight < 210000) {
580 CBlockIndex* prev = m_node.chainman->ActiveChain().Tip();
581 CBlockIndex* next = new CBlockIndex();
582 next->phashBlock = new uint256(m_rng.rand256());
583 m_node.chainman->ActiveChainstate().CoinsTip().SetBestBlock(next->GetBlockHash());
584 next->pprev = prev;
585 next->nHeight = prev->nHeight + 1;
586 next->BuildSkip();
587 m_node.chainman->ActiveChain().SetTip(*next);
588 }
589 BOOST_REQUIRE(mining->createNewBlock(options, /*cooldown=*/false));
590
591 // invalid p2sh txn in tx_mempool, template creation fails
592 tx.vin[0].prevout.hash = txFirst[0]->GetHash();
593 tx.vin[0].prevout.n = 0;
594 tx.vin[0].scriptSig = CScript() << OP_1;
595 tx.vout[0].nValue = BLOCKSUBSIDY - LOWFEE;
596 CScript script = CScript() << OP_0;
597 tx.vout[0].scriptPubKey = GetScriptForDestination(ScriptHash(script));
598 hash = tx.GetHash();
599 TryAddToMempool(tx_mempool, entry.Fee(LOWFEE).Time(Now<NodeSeconds>()).SpendsCoinbase(true).FromTx(tx));
600 tx.vin[0].prevout.hash = hash;
601 tx.vin[0].scriptSig = CScript() << std::vector<unsigned char>(script.begin(), script.end());
602 tx.vout[0].nValue -= LOWFEE;
603 hash = tx.GetHash();
604 TryAddToMempool(tx_mempool, entry.Fee(LOWFEE).Time(Now<NodeSeconds>()).SpendsCoinbase(false).FromTx(tx));
605 BOOST_CHECK_EXCEPTION(mining->createNewBlock(options, /*cooldown=*/false), std::runtime_error, HasReason("block-script-verify-flag-failed"));
606
607 // Delete the dummy blocks again.
608 while (m_node.chainman->ActiveChain().Tip()->nHeight > nHeight) {
609 CBlockIndex* del = m_node.chainman->ActiveChain().Tip();
610 m_node.chainman->ActiveChain().SetTip(*Assert(del->pprev));
611 m_node.chainman->ActiveChainstate().CoinsTip().SetBestBlock(del->pprev->GetBlockHash());
612 delete del->phashBlock;
613 delete del;
614 }
615 }
616
617 CTxMemPool& tx_mempool{MakeMempool()};
618 LOCK(tx_mempool.cs);
619
620 // non-final txs in mempool
621 clock.set(std::chrono::seconds{m_node.chainman->ActiveChain().Tip()->GetMedianTimePast() + 1});
623 // height map
624 std::vector<int> prevheights;
625
626 // relative height locked
627 tx.version = 2;
628 tx.vin.resize(1);
629 prevheights.resize(1);
630 tx.vin[0].prevout.hash = txFirst[0]->GetHash(); // only 1 transaction
631 tx.vin[0].prevout.n = 0;
632 tx.vin[0].scriptSig = CScript() << OP_1;
633 tx.vin[0].nSequence = m_node.chainman->ActiveChain().Tip()->nHeight + 1; // txFirst[0] is the 2nd block
634 prevheights[0] = baseheight + 1;
635 tx.vout.resize(1);
636 tx.vout[0].nValue = BLOCKSUBSIDY-HIGHFEE;
637 tx.vout[0].scriptPubKey = CScript() << OP_1;
638 tx.nLockTime = 0;
639 hash = tx.GetHash();
640 TryAddToMempool(tx_mempool, entry.Fee(HIGHFEE).Time(Now<NodeSeconds>()).SpendsCoinbase(true).FromTx(tx));
641 BOOST_CHECK(CheckFinalTxAtTip(*Assert(m_node.chainman->ActiveChain().Tip()), CTransaction{tx})); // Locktime passes
642 BOOST_CHECK(!TestSequenceLocks(CTransaction{tx}, tx_mempool)); // Sequence locks fail
643
644 {
645 CBlockIndex* active_chain_tip = m_node.chainman->ActiveChain().Tip();
646 BOOST_CHECK(SequenceLocks(CTransaction(tx), flags, prevheights, *CreateBlockIndex(active_chain_tip->nHeight + 2, active_chain_tip))); // Sequence locks pass on 2nd block
647 }
648
649 // relative time locked
650 tx.vin[0].prevout.hash = txFirst[1]->GetHash();
651 tx.vin[0].nSequence = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | (((m_node.chainman->ActiveChain().Tip()->GetMedianTimePast()+1-m_node.chainman->ActiveChain()[1]->GetMedianTimePast()) >> CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) + 1); // txFirst[1] is the 3rd block
652 prevheights[0] = baseheight + 2;
653 hash = tx.GetHash();
654 TryAddToMempool(tx_mempool, entry.Time(Now<NodeSeconds>()).FromTx(tx));
655 BOOST_CHECK(CheckFinalTxAtTip(*Assert(m_node.chainman->ActiveChain().Tip()), CTransaction{tx})); // Locktime passes
656 BOOST_CHECK(!TestSequenceLocks(CTransaction{tx}, tx_mempool)); // Sequence locks fail
657
658 const int SEQUENCE_LOCK_TIME = 512; // Sequence locks pass 512 seconds later
659 for (int i = 0; i < CBlockIndex::nMedianTimeSpan; ++i)
660 m_node.chainman->ActiveChain().Tip()->GetAncestor(m_node.chainman->ActiveChain().Tip()->nHeight - i)->nTime += SEQUENCE_LOCK_TIME; // Trick the MedianTimePast
661 {
662 CBlockIndex* active_chain_tip = m_node.chainman->ActiveChain().Tip();
663 BOOST_CHECK(SequenceLocks(CTransaction(tx), flags, prevheights, *CreateBlockIndex(active_chain_tip->nHeight + 1, active_chain_tip)));
664 }
665
666 for (int i = 0; i < CBlockIndex::nMedianTimeSpan; ++i) {
667 CBlockIndex* ancestor{Assert(m_node.chainman->ActiveChain().Tip()->GetAncestor(m_node.chainman->ActiveChain().Tip()->nHeight - i))};
668 ancestor->nTime -= SEQUENCE_LOCK_TIME; // undo tricked MTP
669 }
670
671 // absolute height locked
672 tx.vin[0].prevout.hash = txFirst[2]->GetHash();
673 tx.vin[0].nSequence = CTxIn::MAX_SEQUENCE_NONFINAL;
674 prevheights[0] = baseheight + 3;
675 tx.nLockTime = m_node.chainman->ActiveChain().Tip()->nHeight + 1;
676 hash = tx.GetHash();
677 TryAddToMempool(tx_mempool, entry.Time(Now<NodeSeconds>()).FromTx(tx));
678 BOOST_CHECK(!CheckFinalTxAtTip(*Assert(m_node.chainman->ActiveChain().Tip()), CTransaction{tx})); // Locktime fails
679 BOOST_CHECK(TestSequenceLocks(CTransaction{tx}, tx_mempool)); // Sequence locks pass
680 BOOST_CHECK(IsFinalTx(CTransaction(tx), m_node.chainman->ActiveChain().Tip()->nHeight + 2, m_node.chainman->ActiveChain().Tip()->GetMedianTimePast())); // Locktime passes on 2nd block
681
682 // ensure tx is final for a specific case where there is no locktime and block height is zero
683 tx.nLockTime = 0;
684 BOOST_CHECK(IsFinalTx(CTransaction(tx), /*nBlockHeight=*/0, m_node.chainman->ActiveChain().Tip()->GetMedianTimePast()));
685
686 // absolute time locked
687 tx.vin[0].prevout.hash = txFirst[3]->GetHash();
688 tx.nLockTime = m_node.chainman->ActiveChain().Tip()->GetMedianTimePast();
689 prevheights.resize(1);
690 prevheights[0] = baseheight + 4;
691 hash = tx.GetHash();
692 TryAddToMempool(tx_mempool, entry.Time(Now<NodeSeconds>()).FromTx(tx));
693 BOOST_CHECK(!CheckFinalTxAtTip(*Assert(m_node.chainman->ActiveChain().Tip()), CTransaction{tx})); // Locktime fails
694 BOOST_CHECK(TestSequenceLocks(CTransaction{tx}, tx_mempool)); // Sequence locks pass
695 BOOST_CHECK(IsFinalTx(CTransaction(tx), m_node.chainman->ActiveChain().Tip()->nHeight + 2, m_node.chainman->ActiveChain().Tip()->GetMedianTimePast() + 1)); // Locktime passes 1 second later
696
697 // mempool-dependent transactions (not added)
698 tx.vin[0].prevout.hash = hash;
699 prevheights[0] = m_node.chainman->ActiveChain().Tip()->nHeight + 1;
700 tx.nLockTime = 0;
701 tx.vin[0].nSequence = 0;
702 BOOST_CHECK(CheckFinalTxAtTip(*Assert(m_node.chainman->ActiveChain().Tip()), CTransaction{tx})); // Locktime passes
703 BOOST_CHECK(TestSequenceLocks(CTransaction{tx}, tx_mempool)); // Sequence locks pass
704 tx.vin[0].nSequence = 1;
705 BOOST_CHECK(!TestSequenceLocks(CTransaction{tx}, tx_mempool)); // Sequence locks fail
706 tx.vin[0].nSequence = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG;
707 BOOST_CHECK(TestSequenceLocks(CTransaction{tx}, tx_mempool)); // Sequence locks pass
708 tx.vin[0].nSequence = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | 1;
709 BOOST_CHECK(!TestSequenceLocks(CTransaction{tx}, tx_mempool)); // Sequence locks fail
710
711 auto block_template = mining->createNewBlock(options, /*cooldown=*/false);
712 BOOST_REQUIRE(block_template);
713
714 // None of the of the absolute height/time locked tx should have made
715 // it into the template because we still check IsFinalTx in CreateNewBlock,
716 // but relative locked txs will if inconsistently added to mempool.
717 // For now these will still generate a valid template until BIP68 soft fork
718 CBlock block{block_template->getBlock()};
719 BOOST_CHECK_EQUAL(block.vtx.size(), 3U);
720 // However if we advance height by 1 and time by SEQUENCE_LOCK_TIME, all of them should be mined
721 for (int i = 0; i < CBlockIndex::nMedianTimeSpan; ++i) {
722 CBlockIndex* ancestor{Assert(m_node.chainman->ActiveChain().Tip()->GetAncestor(m_node.chainman->ActiveChain().Tip()->nHeight - i))};
723 ancestor->nTime += SEQUENCE_LOCK_TIME; // Trick the MedianTimePast
724 }
725 m_node.chainman->ActiveChain().Tip()->nHeight++;
726 clock.set(std::chrono::seconds{m_node.chainman->ActiveChain().Tip()->GetMedianTimePast() + 1});
727
728 block_template = mining->createNewBlock(options, /*cooldown=*/false);
729 BOOST_REQUIRE(block_template);
730 block = block_template->getBlock();
731 BOOST_CHECK_EQUAL(block.vtx.size(), 5U);
732}
733
734void MinerTestingSetup::TestPrioritisedMining(const CScript& scriptPubKey, const std::vector<CTransactionRef>& txFirst)
735{
736 auto mining{MakeMining()};
737 BOOST_REQUIRE(mining);
738
739 BlockCreateOptions options{
740 .coinbase_output_script = scriptPubKey,
741 };
742
743 CTxMemPool& tx_mempool{MakeMempool()};
744 LOCK(tx_mempool.cs);
745
747
748 // Test that a tx below min fee but prioritised is included
750 tx.vin.resize(1);
751 tx.vin[0].prevout.hash = txFirst[0]->GetHash();
752 tx.vin[0].prevout.n = 0;
753 tx.vin[0].scriptSig = CScript() << OP_1;
754 tx.vout.resize(1);
755 tx.vout[0].nValue = 5000000000LL; // 0 fee
756 Txid hashFreePrioritisedTx = tx.GetHash();
757 TryAddToMempool(tx_mempool, entry.Fee(0).Time(Now<NodeSeconds>()).SpendsCoinbase(true).FromTx(tx));
758 tx_mempool.PrioritiseTransaction(hashFreePrioritisedTx, 5 * COIN);
759
760 tx.vin[0].prevout.hash = txFirst[1]->GetHash();
761 tx.vin[0].prevout.n = 0;
762 tx.vout[0].nValue = 5000000000LL - 1000;
763 // This tx has a low fee: 1000 satoshis
764 Txid hashParentTx = tx.GetHash(); // save this txid for later use
765 TryAddToMempool(tx_mempool, entry.Fee(1000).Time(Now<NodeSeconds>()).SpendsCoinbase(true).FromTx(tx));
766
767 // This tx has a medium fee: 10000 satoshis
768 tx.vin[0].prevout.hash = txFirst[2]->GetHash();
769 tx.vout[0].nValue = 5000000000LL - 10000;
770 Txid hashMediumFeeTx = tx.GetHash();
771 TryAddToMempool(tx_mempool, entry.Fee(10000).Time(Now<NodeSeconds>()).SpendsCoinbase(true).FromTx(tx));
772 tx_mempool.PrioritiseTransaction(hashMediumFeeTx, -5 * COIN);
773
774 // This tx also has a low fee, but is prioritised
775 tx.vin[0].prevout.hash = hashParentTx;
776 tx.vout[0].nValue = 5000000000LL - 1000 - 1000; // 1000 satoshi fee
777 Txid hashPrioritsedChild = tx.GetHash();
778 TryAddToMempool(tx_mempool, entry.Fee(1000).Time(Now<NodeSeconds>()).SpendsCoinbase(false).FromTx(tx));
779 tx_mempool.PrioritiseTransaction(hashPrioritsedChild, 2 * COIN);
780
781 // Test that transaction selection properly updates ancestor fee calculations as prioritised
782 // parents get included in a block. Create a transaction with two prioritised ancestors, each
783 // included by itself: FreeParent <- FreeChild <- FreeGrandchild.
784 // When FreeParent is added, a modified entry will be created for FreeChild + FreeGrandchild
785 // FreeParent's prioritisation should not be included in that entry.
786 // When FreeChild is included, FreeChild's prioritisation should also not be included.
787 tx.vin[0].prevout.hash = txFirst[3]->GetHash();
788 tx.vout[0].nValue = 5000000000LL; // 0 fee
789 Txid hashFreeParent = tx.GetHash();
790 TryAddToMempool(tx_mempool, entry.Fee(0).SpendsCoinbase(true).FromTx(tx));
791 tx_mempool.PrioritiseTransaction(hashFreeParent, 10 * COIN);
792
793 tx.vin[0].prevout.hash = hashFreeParent;
794 tx.vout[0].nValue = 5000000000LL; // 0 fee
795 Txid hashFreeChild = tx.GetHash();
796 TryAddToMempool(tx_mempool, entry.Fee(0).SpendsCoinbase(false).FromTx(tx));
797 tx_mempool.PrioritiseTransaction(hashFreeChild, 1 * COIN);
798
799 tx.vin[0].prevout.hash = hashFreeChild;
800 tx.vout[0].nValue = 5000000000LL; // 0 fee
801 Txid hashFreeGrandchild = tx.GetHash();
802 TryAddToMempool(tx_mempool, entry.Fee(0).SpendsCoinbase(false).FromTx(tx));
803
804 auto block_template = mining->createNewBlock(options, /*cooldown=*/false);
805 BOOST_REQUIRE(block_template);
806 CBlock block{block_template->getBlock()};
807 BOOST_REQUIRE_EQUAL(block.vtx.size(), 6U);
808 BOOST_CHECK(block.vtx[1]->GetHash() == hashFreeParent);
809 BOOST_CHECK(block.vtx[2]->GetHash() == hashFreePrioritisedTx);
810 BOOST_CHECK(block.vtx[3]->GetHash() == hashParentTx);
811 BOOST_CHECK(block.vtx[4]->GetHash() == hashPrioritsedChild);
812 BOOST_CHECK(block.vtx[5]->GetHash() == hashFreeChild);
813 for (size_t i=0; i<block.vtx.size(); ++i) {
814 // The FreeParent and FreeChild's prioritisations should not impact the child.
815 BOOST_CHECK(block.vtx[i]->GetHash() != hashFreeGrandchild);
816 // De-prioritised transaction should not be included.
817 BOOST_CHECK(block.vtx[i]->GetHash() != hashMediumFeeTx);
818 }
819}
820
821// NOTE: These tests rely on CreateNewBlock doing its own self-validation!
822BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
823{
824 auto mining{MakeMining()};
825 BOOST_REQUIRE(mining);
826
827 // Note that by default, these tests run with size accounting enabled.
828 CScript scriptPubKey = CScript() << "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f"_hex << OP_CHECKSIG;
829 BlockCreateOptions options{
830 .coinbase_output_script = scriptPubKey,
831 };
832
833 // Create and check a simple template
834 std::unique_ptr<BlockTemplate> block_template = mining->createNewBlock(options, /*cooldown=*/false);
835 BOOST_REQUIRE(block_template);
836
837 BlockCreateOptions invalid_options{options};
839 BOOST_CHECK_EXCEPTION(mining->createNewBlock(invalid_options, /*cooldown=*/false),
840 std::runtime_error,
841 HasReason("block_reserved_weight (8000) exceeds block_max_weight (7999)"));
842
843 {
844 CBlock block{block_template->getBlock()};
845 {
846 std::string reason;
847 std::string debug;
848 BOOST_REQUIRE(!mining->checkBlock(block, {.check_pow = false}, reason, debug));
849 BOOST_REQUIRE_EQUAL(reason, "bad-txnmrklroot");
850 BOOST_REQUIRE_EQUAL(debug, "hashMerkleRoot mismatch");
851 }
852
853 block.hashMerkleRoot = BlockMerkleRoot(block);
854
855 {
856 std::string reason;
857 std::string debug;
858 BOOST_REQUIRE(mining->checkBlock(block, {.check_pow = false}, reason, debug));
859 BOOST_REQUIRE_EQUAL(reason, "");
860 BOOST_REQUIRE_EQUAL(debug, "");
861 }
862
863 {
864 // A block template does not have proof-of-work, but it might pass
865 // verification by coincidence. Grind the nonce if needed:
866 while (CheckProofOfWork(block.GetHash(), block.nBits, Assert(m_node.chainman)->GetParams().GetConsensus())) {
867 block.nNonce++;
868 }
869
870 std::string reason;
871 std::string debug;
872 BOOST_REQUIRE(!mining->checkBlock(block, {.check_pow = true}, reason, debug));
873 BOOST_REQUIRE_EQUAL(reason, "high-hash");
874 BOOST_REQUIRE_EQUAL(debug, "proof of work failed");
875 }
876 }
877
878 // We can't make transactions until we have inputs
879 // Therefore, load 110 blocks :)
880 static_assert(std::size(BLOCKINFO) == 110, "Should have 110 blocks to import");
881 int baseheight = 0;
882 std::vector<CTransactionRef> txFirst;
883 for (const auto& bi : BLOCKINFO) {
884 const int current_height{mining->getTip()->height};
885
891 if (current_height % 2 == 0) {
892 block_template = mining->createNewBlock(options, /*cooldown=*/false);
893 BOOST_REQUIRE(block_template);
894 }
895
896 CBlock block{block_template->getBlock()};
897 CMutableTransaction txCoinbase(*block.vtx[0]);
898 {
899 LOCK(cs_main);
900 block.nVersion = VERSIONBITS_TOP_BITS;
901 block.nTime = Assert(m_node.chainman)->ActiveChain().Tip()->GetMedianTimePast()+1;
902 txCoinbase.version = 1;
903 txCoinbase.vin[0].scriptSig = CScript{} << (current_height + 1) << bi.extranonce;
904 txCoinbase.vout.resize(1); // Ignore the (optional) segwit commitment added by CreateNewBlock (as the hardcoded nonces don't account for this)
905 txCoinbase.vout[0].scriptPubKey = CScript();
906 block.vtx[0] = MakeTransactionRef(txCoinbase);
907 if (txFirst.size() == 0)
908 baseheight = current_height;
909 if (txFirst.size() < 4)
910 txFirst.push_back(block.vtx[0]);
911 block.hashMerkleRoot = BlockMerkleRoot(block);
912 block.nNonce = bi.nonce;
913 }
914 // Alternate calls between submitBlock and submitSolution via the
915 // Mining interface.
916 std::string reason{"stale reason"};
917 std::string debug{"stale debug"};
918 if (current_height % 2 == 0) {
919 BOOST_REQUIRE(mining->submitBlock(block, reason, debug));
920 BOOST_REQUIRE_EQUAL(reason, "");
921 BOOST_REQUIRE_EQUAL(debug, "");
922
923 reason = "stale reason";
924 debug = "stale debug";
925 BOOST_REQUIRE(!mining->submitBlock(block, reason, debug));
926 BOOST_REQUIRE_EQUAL(reason, "duplicate");
927 BOOST_REQUIRE_EQUAL(debug, "");
928 } else {
929 reason = "stale reason";
930 debug = "stale debug";
931 BOOST_REQUIRE(block_template->submitSolution(block.nVersion, block.nTime, block.nNonce, MakeTransactionRef(txCoinbase), reason, debug));
932 BOOST_REQUIRE_EQUAL(reason, "");
933 BOOST_REQUIRE_EQUAL(debug, "");
934 BOOST_CHECK_THROW(block_template->submitSolutionOld7(block.nVersion, block.nTime, block.nNonce,
935 MakeTransactionRef(txCoinbase)),
936 std::runtime_error);
937 }
938 {
939 LOCK(cs_main);
940 // The above calls don't guarantee the tip is actually updated, so
941 // we explicitly check this.
942 auto maybe_new_tip{Assert(m_node.chainman)->ActiveChain().Tip()};
943 BOOST_REQUIRE_EQUAL(maybe_new_tip->GetBlockHash(), block.GetHash());
944 }
945 if (current_height % 2 == 0) {
946 block_template = block_template->waitNext();
947 BOOST_REQUIRE(block_template);
948 } else {
949 // This just adds coverage
950 mining->waitTipChanged(block.hashPrevBlock);
951 }
952 }
953
954 LOCK(cs_main);
955
956 TestBasicMining(scriptPubKey, txFirst, baseheight);
957
958 m_node.chainman->ActiveChain().Tip()->nHeight--;
959
960 TestPackageSelection(scriptPubKey, txFirst);
961
962 m_node.chainman->ActiveChain().Tip()->nHeight--;
963
964 TestPrioritisedMining(scriptPubKey, txFirst);
965
966 TestSigOpsAdjustedWeightChunkLimit(scriptPubKey, txFirst);
967}
968
969BOOST_AUTO_TEST_CASE(block_template_manager)
970{
971 auto& block_template_manager = *Assert(m_node.block_template_manager);
972 BlockCreateOptions options;
973 options.use_mempool = false;
974 auto block_template = block_template_manager.CreateNewTemplate(options);
975 BOOST_REQUIRE(block_template);
976 const CBlock& block{block_template->block};
977 // Without the mempool the template holds only the coinbase, and the per-tx
978 // fee/sigops vectors exclude it.
979 BOOST_CHECK_EQUAL(block.vtx.size(), 1U);
980 BOOST_CHECK(block.vtx[0]->IsCoinBase());
981 BOOST_CHECK(block_template->vTxFees.empty());
982 BOOST_CHECK(block_template->vTxSigOpsCost.empty());
983}
984
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
constexpr CAmount COIN
The amount of satoshis in one BTC.
Definition: amount.h:15
TryAddToMempool(pool, CTxMemPoolEntry(tx, fee, 0, 1, 0, false, 4, lp))
int ret
node::NodeContext m_node
Definition: bitcoin-gui.cpp:48
int flags
Definition: bitcoin-tx.cpp:531
#define Assert(val)
Identity function.
Definition: check.h:116
Definition: block.h:74
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:94
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:100
void BuildSkip()
Build the skiplist pointer for this entry.
Definition: chain.cpp:114
uint256 GetBlockHash() const
Definition: chain.h:198
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:106
static constexpr int nMedianTimeSpan
Definition: chain.h:231
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Definition: chain.h:97
CCoinsView that brings transactions from a mempool into view.
Definition: txmempool.h:777
Fee rate in satoshis per virtualbyte: CAmount / vB the feerate is represented internally as FeeFrac.
Definition: feerate.h:32
CAmount GetFee(int32_t virtual_bytes) const
Return the fee in satoshis for the given vsize in vbytes.
Definition: feerate.cpp:21
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:30
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:406
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:287
static constexpr int SEQUENCE_LOCKTIME_GRANULARITY
In order to use the same number of bits to encode roughly the same wall-clock duration,...
Definition: transaction.h:115
static constexpr uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG
If CTxIn::nSequence encodes a relative lock-time and this flag is set, the relative lock-time has uni...
Definition: transaction.h:100
static constexpr uint32_t MAX_SEQUENCE_NONFINAL
This is the maximum sequence number that enables both nLockTime and OP_CHECKLOCKTIMEVERIFY (BIP 65).
Definition: transaction.h:83
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:187
Helper to initialize the global NodeClock, let a duration elapse, and reset it after use in a test.
Definition: time.h:54
void set(NodeSeconds t)
Set mocktime.
Definition: time.h:71
BOOST_CHECK_EXCEPTION predicates to check the specific validation error.
Definition: common.h:19
Block template interface.
Definition: mining.h:31
Interface giving clients (RPC, Stratum v2 Template Provider in the future) ability to create block te...
Definition: mining.h:108
const uint256 & ToUint256() const LIFETIMEBOUND
static transaction_identifier FromUint256(const uint256 &id)
256-bit opaque blob.
Definition: uint256.h:196
static const uint256 ZERO
Definition: uint256.h:204
uint32_t current_height
Current height in the simulation.
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:76
constexpr unsigned int LOCKTIME_VERIFY_SEQUENCE
Flags for nSequence and nLockTime locks.
Definition: consensus.h:28
constexpr int64_t MAX_BLOCK_SIGOPS_COST
The maximum allowed number of signature check operations in a block (network rule)
Definition: consensus.h:17
constexpr int WITNESS_SCALE_FACTOR
Definition: consensus.h:21
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
BOOST_FIXTURE_TEST_SUITE(cuckoocache_tests, BasicTestingSetup)
Test Suite for CuckooCache.
BOOST_AUTO_TEST_SUITE_END()
BOOST_CHECK_EQUAL(headers.FindFirst("key"), "value")
BOOST_CHECK_EXCEPTION(HTTPHeaders{}.Read(reader), std::runtime_error, HasReason{"Empty HTTP header name"})
unsigned int nHeight
bool spendsCoinbase
@ REPLACED
Removed for replacement.
std::vector< CTransactionRef > CreateBigSigOpsCluster(const CTransactionRef &first_tx)
BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
static CMutableTransaction CreateBigSigOpsTx(const COutPoint &input, unsigned int num_outputs)
unsigned int extranonce
static std::unique_ptr< CBlockIndex > CreateBlockIndex(int nHeight, CBlockIndex *active_chain_tip) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
static constexpr struct @14 BLOCKINFO[]
static CFeeRate blockMinFeeRate
Definition: miner_tests.cpp:99
unsigned int nonce
is used externally by mining IPC clients, so it should only declare simple data definitions.
std::unique_ptr< Mining > MakeMining(const node::NodeContext &node, bool wait_loaded=true)
Return implementation of Mining interface.
""_hex is a compile-time user-defined literal returning a std::array<std::byte>, equivalent to ParseH...
Definition: strencodings.h:386
#define BOOST_CHECK_THROW(stmt, excMatch)
Definition: object.cpp:18
#define BOOST_CHECK(expr)
Definition: object.cpp:16
constexpr unsigned int DEFAULT_BLOCK_MIN_TX_FEE
Default for -blockmintxfee, which sets the minimum feerate for a transaction in blocks created by min...
Definition: policy.h:36
constexpr unsigned int DEFAULT_BLOCK_RESERVED_WEIGHT
Default for -blockreservedweight.
Definition: policy.h:27
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params &params)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition: pow.cpp:140
constexpr TransactionSerParams TX_WITH_WITNESS
Definition: transaction.h:181
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:418
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:417
@ OP_2
Definition: script.h:86
@ OP_CHECKMULTISIG
Definition: script.h:193
@ OP_CHECKSIG
Definition: script.h:191
@ OP_NOP
Definition: script.h:103
@ OP_1
Definition: script.h:84
@ OP_DROP
Definition: script.h:125
@ OP_0
Definition: script.h:77
uint64_t GetSerializeSize(const T &t)
Definition: serialize.h:1157
constexpr CAmount CENT
Definition: setup_common.h:41
node::NodeContext m_node
Definition: setup_common.h:60
A mutable version of CTransaction.
Definition: transaction.h:372
std::vector< CTxOut > vout
Definition: transaction.h:374
Txid GetHash() const
Compute the hash of this CMutableTransaction.
Definition: transaction.cpp:69
std::vector< CTxIn > vin
Definition: transaction.h:373
void CreateBlockTemplateManager()
Create the block template manager.
Data structure storing a fee and size.
Definition: feefrac.h:21
Definition: txmempool.h:19
TestMemPoolEntryHelper & SigOpsCost(unsigned int _sigopsCost)
Definition: txmempool.h:38
TestMemPoolEntryHelper & Time(NodeSeconds tp)
Definition: txmempool.h:34
CAmount nFee
Definition: txmempool.h:21
CTxMemPoolEntry FromTx(const CMutableTransaction &tx) const
Definition: txmempool.cpp:34
TestMemPoolEntryHelper & SpendsCoinbase(bool _flag)
Definition: txmempool.h:37
unsigned int nHeight
Definition: txmempool.h:23
TestMemPoolEntryHelper & Fee(CAmount _fee)
Definition: txmempool.h:33
Testing setup that configures a complete environment.
Definition: setup_common.h:119
Bilingual messages:
Definition: translation.h:24
bool empty() const
Definition: translation.h:35
std::unique_ptr< Mining > MakeMining()
Definition: miner_tests.cpp:90
void TestPackageSelection(const CScript &scriptPubKey, const std::vector< CTransactionRef > &txFirst) EXCLUSIVE_LOCKS_REQUIRED(void TestBasicMining(const CScript &scriptPubKey, const std::vector< CTransactionRef > &txFirst, int baseheight) EXCLUSIVE_LOCKS_REQUIRED(void TestPrioritisedMining(const CScript &scriptPubKey, const std::vector< CTransactionRef > &txFirst) EXCLUSIVE_LOCKS_REQUIRED(void TestSigOpsAdjustedWeightChunkLimit(const CScript &scriptPubKey, const std::vector< CTransactionRef > &txFirst) EXCLUSIVE_LOCKS_REQUIRED(bool TestSequenceLocks(const CTransaction &tx, CTxMemPool &tx_mempool) EXCLUSIVE_LOCKS_REQUIRED(
Definition: miner_tests.cpp:65
Block template creation options.
Definition: mining_types.h:33
CScript coinbase_output_script
Script to put in the coinbase transaction.
Definition: mining_types.h:86
bool use_mempool
Set false to omit mempool transactions.
Definition: mining_types.h:37
std::optional< uint64_t > block_max_weight
Maximum block weight, defaults to -maxblockweight.
Definition: mining_types.h:65
std::unique_ptr< CTxMemPool > mempool
Definition: context.h:69
std::unique_ptr< BlockTemplateManager > block_template_manager
Must be destroyed before its dependencies (holds references to them).
Definition: context.h:87
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:74
#define LOCK(cs)
Definition: sync.h:268
CTxMemPool::Options MemPoolOptionsForTest(const NodeContext &node)
Definition: txmempool.cpp:21
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
void BulkTransaction(CMutableTransaction &tx, int32_t target_weight)
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Auxiliary functions for transaction validation (ideally should not be exposed)
Definition: tx_verify.cpp:118
bool SequenceLocks(const CTransaction &tx, int flags, std::vector< int > &prevHeights, const CBlockIndex &block)
Check if transaction is final per BIP 68 sequence numbers and can be included in a block.
Definition: tx_verify.cpp:113
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
Check if transaction is final and can be included in a block with the specified height and time.
Definition: tx_verify.cpp:23
std::chrono::duration< double, std::chrono::milliseconds::period > MillisecondsDouble
Definition: time.h:103
bool CheckFinalTxAtTip(const CBlockIndex &active_chain_tip, const CTransaction &tx)
Definition: validation.cpp:156
bool CheckSequenceLocksAtTip(CBlockIndex *tip, const LockPoints &lock_points)
Check if transaction will be BIP68 final in the next block to be created on top of tip.
Definition: validation.cpp:255
assert(!tx.IsCoinBase())
bool CheckFinalTxAtTip(const CBlockIndex &active_chain_tip, const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(std::optional< LockPoints > CalculateLockPointsAtTip(CBlockIndex *tip, const CCoinsView &coins_view, const CTransaction &tx)
Check if transaction will be final in the next block to be created.
Definition: validation.h:316
constexpr int32_t VERSIONBITS_TOP_BITS
What bits to set in version for versionbits blocks.
Definition: versionbits.h:21
FakeNodeClock clock