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