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