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