Bitcoin Core  24.99.0
P2P Digital Currency
miner_tests.cpp
Go to the documentation of this file.
1 // Copyright (c) 2011-2021 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 <chainparams.h>
6 #include <coins.h>
7 #include <consensus/consensus.h>
8 #include <consensus/merkle.h>
9 #include <consensus/tx_verify.h>
10 #include <node/miner.h>
11 #include <policy/policy.h>
12 #include <script/standard.h>
13 #include <timedata.h>
14 #include <txmempool.h>
15 #include <uint256.h>
16 #include <util/strencodings.h>
17 #include <util/system.h>
18 #include <util/time.h>
19 #include <validation.h>
20 #include <versionbits.h>
21 
22 #include <test/util/setup_common.h>
23 
24 #include <memory>
25 
26 #include <boost/test/unit_test.hpp>
27 
30 
31 namespace miner_tests {
33  void TestPackageSelection(const CChainParams& chainparams, const CScript& scriptPubKey, const std::vector<CTransactionRef>& txFirst) EXCLUSIVE_LOCKS_REQUIRED(::cs_main, m_node.mempool->cs);
34  void TestBasicMining(const CChainParams& chainparams, const CScript& scriptPubKey, const std::vector<CTransactionRef>& txFirst, int baseheight) EXCLUSIVE_LOCKS_REQUIRED(::cs_main, m_node.mempool->cs);
35  void TestPrioritisedMining(const CChainParams& chainparams, const CScript& scriptPubKey, const std::vector<CTransactionRef>& txFirst) EXCLUSIVE_LOCKS_REQUIRED(::cs_main, m_node.mempool->cs);
37  {
38  CCoinsViewMemPool view_mempool(&m_node.chainman->ActiveChainstate().CoinsTip(), *m_node.mempool);
39  return CheckSequenceLocksAtTip(m_node.chainman->ActiveChain().Tip(), view_mempool, tx);
40  }
42 };
43 } // namespace miner_tests
44 
45 BOOST_FIXTURE_TEST_SUITE(miner_tests, MinerTestingSetup)
46 
48 
49 BlockAssembler MinerTestingSetup::AssemblerForTest(const CChainParams& params)
50 {
51  BlockAssembler::Options options;
52 
53  options.nBlockMaxWeight = MAX_BLOCK_WEIGHT;
54  options.blockMinFeeRate = blockMinFeeRate;
55  return BlockAssembler{m_node.chainman->ActiveChainstate(), m_node.mempool.get(), options};
56 }
57 
58 constexpr static struct {
59  unsigned char extranonce;
60  unsigned int nonce;
61 } BLOCKINFO[]{{8, 582909131}, {0, 971462344}, {2, 1169481553}, {6, 66147495}, {7, 427785981}, {8, 80538907},
62  {8, 207348013}, {2, 1951240923}, {4, 215054351}, {1, 491520534}, {8, 1282281282}, {4, 639565734},
63  {3, 248274685}, {8, 1160085976}, {6, 396349768}, {5, 393780549}, {5, 1096899528}, {4, 965381630},
64  {0, 728758712}, {5, 318638310}, {3, 164591898}, {2, 274234550}, {2, 254411237}, {7, 561761812},
65  {2, 268342573}, {0, 402816691}, {1, 221006382}, {6, 538872455}, {7, 393315655}, {4, 814555937},
66  {7, 504879194}, {6, 467769648}, {3, 925972193}, {2, 200581872}, {3, 168915404}, {8, 430446262},
67  {5, 773507406}, {3, 1195366164}, {0, 433361157}, {3, 297051771}, {0, 558856551}, {2, 501614039},
68  {3, 528488272}, {2, 473587734}, {8, 230125274}, {2, 494084400}, {4, 357314010}, {8, 60361686},
69  {7, 640624687}, {3, 480441695}, {8, 1424447925}, {4, 752745419}, {1, 288532283}, {6, 669170574},
70  {5, 1900907591}, {3, 555326037}, {3, 1121014051}, {0, 545835650}, {8, 189196651}, {5, 252371575},
71  {0, 199163095}, {6, 558895874}, {6, 1656839784}, {6, 815175452}, {6, 718677851}, {5, 544000334},
72  {0, 340113484}, {6, 850744437}, {4, 496721063}, {8, 524715182}, {6, 574361898}, {6, 1642305743},
73  {6, 355110149}, {5, 1647379658}, {8, 1103005356}, {7, 556460625}, {3, 1139533992}, {5, 304736030},
74  {2, 361539446}, {2, 143720360}, {6, 201939025}, {7, 423141476}, {4, 574633709}, {3, 1412254823},
75  {4, 873254135}, {0, 341817335}, {6, 53501687}, {3, 179755410}, {5, 172209688}, {8, 516810279},
76  {4, 1228391489}, {8, 325372589}, {6, 550367589}, {0, 876291812}, {7, 412454120}, {7, 717202854},
77  {2, 222677843}, {6, 251778867}, {7, 842004420}, {7, 194762829}, {4, 96668841}, {1, 925485796},
78  {0, 792342903}, {6, 678455063}, {6, 773251385}, {5, 186617471}, {6, 883189502}, {7, 396077336},
79  {8, 254702874}, {0, 455592851}};
80 
82 {
83  CBlockIndex index;
84  index.nHeight = nHeight;
85  index.pprev = active_chain_tip;
86  return index;
87 }
88 
89 // Test suite for ancestor feerate transaction selection.
90 // Implemented as an additional function, rather than a separate test case,
91 // to allow reusing the blockchain created in CreateNewBlock_validity.
92 void MinerTestingSetup::TestPackageSelection(const CChainParams& chainparams, const CScript& scriptPubKey, const std::vector<CTransactionRef>& txFirst)
93 {
94  // Test the ancestor feerate transaction selection.
96 
97  // Test that a medium fee transaction will be selected after a higher fee
98  // rate package with a low fee rate parent.
100  tx.vin.resize(1);
101  tx.vin[0].scriptSig = CScript() << OP_1;
102  tx.vin[0].prevout.hash = txFirst[0]->GetHash();
103  tx.vin[0].prevout.n = 0;
104  tx.vout.resize(1);
105  tx.vout[0].nValue = 5000000000LL - 1000;
106  // This tx has a low fee: 1000 satoshis
107  uint256 hashParentTx = tx.GetHash(); // save this txid for later use
108  m_node.mempool->addUnchecked(entry.Fee(1000).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
109 
110  // This tx has a medium fee: 10000 satoshis
111  tx.vin[0].prevout.hash = txFirst[1]->GetHash();
112  tx.vout[0].nValue = 5000000000LL - 10000;
113  uint256 hashMediumFeeTx = tx.GetHash();
114  m_node.mempool->addUnchecked(entry.Fee(10000).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
115 
116  // This tx has a high fee, but depends on the first transaction
117  tx.vin[0].prevout.hash = hashParentTx;
118  tx.vout[0].nValue = 5000000000LL - 1000 - 50000; // 50k satoshi fee
119  uint256 hashHighFeeTx = tx.GetHash();
120  m_node.mempool->addUnchecked(entry.Fee(50000).Time(GetTime()).SpendsCoinbase(false).FromTx(tx));
121 
122  std::unique_ptr<CBlockTemplate> pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey);
123  BOOST_REQUIRE_EQUAL(pblocktemplate->block.vtx.size(), 4U);
124  BOOST_CHECK(pblocktemplate->block.vtx[1]->GetHash() == hashParentTx);
125  BOOST_CHECK(pblocktemplate->block.vtx[2]->GetHash() == hashHighFeeTx);
126  BOOST_CHECK(pblocktemplate->block.vtx[3]->GetHash() == hashMediumFeeTx);
127 
128  // Test that a package below the block min tx fee doesn't get included
129  tx.vin[0].prevout.hash = hashHighFeeTx;
130  tx.vout[0].nValue = 5000000000LL - 1000 - 50000; // 0 fee
131  uint256 hashFreeTx = tx.GetHash();
132  m_node.mempool->addUnchecked(entry.Fee(0).FromTx(tx));
133  size_t freeTxSize = ::GetSerializeSize(tx, PROTOCOL_VERSION);
134 
135  // Calculate a fee on child transaction that will put the package just
136  // below the block min tx fee (assuming 1 child tx of the same size).
137  CAmount feeToUse = blockMinFeeRate.GetFee(2*freeTxSize) - 1;
138 
139  tx.vin[0].prevout.hash = hashFreeTx;
140  tx.vout[0].nValue = 5000000000LL - 1000 - 50000 - feeToUse;
141  uint256 hashLowFeeTx = tx.GetHash();
142  m_node.mempool->addUnchecked(entry.Fee(feeToUse).FromTx(tx));
143  pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey);
144  // Verify that the free tx and the low fee tx didn't get selected
145  for (size_t i=0; i<pblocktemplate->block.vtx.size(); ++i) {
146  BOOST_CHECK(pblocktemplate->block.vtx[i]->GetHash() != hashFreeTx);
147  BOOST_CHECK(pblocktemplate->block.vtx[i]->GetHash() != hashLowFeeTx);
148  }
149 
150  // Test that packages above the min relay fee do get included, even if one
151  // of the transactions is below the min relay fee
152  // Remove the low fee transaction and replace with a higher fee transaction
154  tx.vout[0].nValue -= 2; // Now we should be just over the min relay fee
155  hashLowFeeTx = tx.GetHash();
156  m_node.mempool->addUnchecked(entry.Fee(feeToUse+2).FromTx(tx));
157  pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey);
158  BOOST_REQUIRE_EQUAL(pblocktemplate->block.vtx.size(), 6U);
159  BOOST_CHECK(pblocktemplate->block.vtx[4]->GetHash() == hashFreeTx);
160  BOOST_CHECK(pblocktemplate->block.vtx[5]->GetHash() == hashLowFeeTx);
161 
162  // Test that transaction selection properly updates ancestor fee
163  // calculations as ancestor transactions get included in a block.
164  // Add a 0-fee transaction that has 2 outputs.
165  tx.vin[0].prevout.hash = txFirst[2]->GetHash();
166  tx.vout.resize(2);
167  tx.vout[0].nValue = 5000000000LL - 100000000;
168  tx.vout[1].nValue = 100000000; // 1BTC output
169  uint256 hashFreeTx2 = tx.GetHash();
170  m_node.mempool->addUnchecked(entry.Fee(0).SpendsCoinbase(true).FromTx(tx));
171 
172  // This tx can't be mined by itself
173  tx.vin[0].prevout.hash = hashFreeTx2;
174  tx.vout.resize(1);
175  feeToUse = blockMinFeeRate.GetFee(freeTxSize);
176  tx.vout[0].nValue = 5000000000LL - 100000000 - feeToUse;
177  uint256 hashLowFeeTx2 = tx.GetHash();
178  m_node.mempool->addUnchecked(entry.Fee(feeToUse).SpendsCoinbase(false).FromTx(tx));
179  pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey);
180 
181  // Verify that this tx isn't selected.
182  for (size_t i=0; i<pblocktemplate->block.vtx.size(); ++i) {
183  BOOST_CHECK(pblocktemplate->block.vtx[i]->GetHash() != hashFreeTx2);
184  BOOST_CHECK(pblocktemplate->block.vtx[i]->GetHash() != hashLowFeeTx2);
185  }
186 
187  // This tx will be mineable, and should cause hashLowFeeTx2 to be selected
188  // as well.
189  tx.vin[0].prevout.n = 1;
190  tx.vout[0].nValue = 100000000 - 10000; // 10k satoshi fee
191  m_node.mempool->addUnchecked(entry.Fee(10000).FromTx(tx));
192  pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey);
193  BOOST_REQUIRE_EQUAL(pblocktemplate->block.vtx.size(), 9U);
194  BOOST_CHECK(pblocktemplate->block.vtx[8]->GetHash() == hashLowFeeTx2);
195 }
196 
197 void MinerTestingSetup::TestBasicMining(const CChainParams& chainparams, const CScript& scriptPubKey, const std::vector<CTransactionRef>& txFirst, int baseheight)
198 {
199  uint256 hash;
202  entry.nFee = 11;
203  entry.nHeight = 11;
204 
205  // Just to make sure we can still make simple blocks
206  auto pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey);
207  BOOST_CHECK(pblocktemplate);
208 
209  const CAmount BLOCKSUBSIDY = 50*COIN;
210  const CAmount LOWFEE = CENT;
211  const CAmount HIGHFEE = COIN;
212  const CAmount HIGHERFEE = 4*COIN;
213 
214  // block sigops > limit: 1000 CHECKMULTISIG + 1
215  tx.vin.resize(1);
216  // NOTE: OP_NOP is used to force 20 SigOps for the CHECKMULTISIG
217  tx.vin[0].scriptSig = CScript() << OP_0 << OP_0 << OP_0 << OP_NOP << OP_CHECKMULTISIG << OP_1;
218  tx.vin[0].prevout.hash = txFirst[0]->GetHash();
219  tx.vin[0].prevout.n = 0;
220  tx.vout.resize(1);
221  tx.vout[0].nValue = BLOCKSUBSIDY;
222  for (unsigned int i = 0; i < 1001; ++i)
223  {
224  tx.vout[0].nValue -= LOWFEE;
225  hash = tx.GetHash();
226  bool spendsCoinbase = i == 0; // only first tx spends coinbase
227  // If we don't set the # of sig ops in the CTxMemPoolEntry, template creation fails
228  m_node.mempool->addUnchecked(entry.Fee(LOWFEE).Time(GetTime()).SpendsCoinbase(spendsCoinbase).FromTx(tx));
229  tx.vin[0].prevout.hash = hash;
230  }
231 
232  BOOST_CHECK_EXCEPTION(AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey), std::runtime_error, HasReason("bad-blk-sigops"));
233  m_node.mempool->clear();
234 
235  tx.vin[0].prevout.hash = txFirst[0]->GetHash();
236  tx.vout[0].nValue = BLOCKSUBSIDY;
237  for (unsigned int i = 0; i < 1001; ++i)
238  {
239  tx.vout[0].nValue -= LOWFEE;
240  hash = tx.GetHash();
241  bool spendsCoinbase = i == 0; // only first tx spends coinbase
242  // If we do set the # of sig ops in the CTxMemPoolEntry, template creation passes
243  m_node.mempool->addUnchecked(entry.Fee(LOWFEE).Time(GetTime()).SpendsCoinbase(spendsCoinbase).SigOpsCost(80).FromTx(tx));
244  tx.vin[0].prevout.hash = hash;
245  }
246  BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey));
247  m_node.mempool->clear();
248 
249  // block size > limit
250  tx.vin[0].scriptSig = CScript();
251  // 18 * (520char + DROP) + OP_1 = 9433 bytes
252  std::vector<unsigned char> vchData(520);
253  for (unsigned int i = 0; i < 18; ++i)
254  tx.vin[0].scriptSig << vchData << OP_DROP;
255  tx.vin[0].scriptSig << OP_1;
256  tx.vin[0].prevout.hash = txFirst[0]->GetHash();
257  tx.vout[0].nValue = BLOCKSUBSIDY;
258  for (unsigned int i = 0; i < 128; ++i)
259  {
260  tx.vout[0].nValue -= LOWFEE;
261  hash = tx.GetHash();
262  bool spendsCoinbase = i == 0; // only first tx spends coinbase
263  m_node.mempool->addUnchecked(entry.Fee(LOWFEE).Time(GetTime()).SpendsCoinbase(spendsCoinbase).FromTx(tx));
264  tx.vin[0].prevout.hash = hash;
265  }
266  BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey));
267  m_node.mempool->clear();
268 
269  // orphan in *m_node.mempool, template creation fails
270  hash = tx.GetHash();
271  m_node.mempool->addUnchecked(entry.Fee(LOWFEE).Time(GetTime()).FromTx(tx));
272  BOOST_CHECK_EXCEPTION(AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey), std::runtime_error, HasReason("bad-txns-inputs-missingorspent"));
273  m_node.mempool->clear();
274 
275  // child with higher feerate than parent
276  tx.vin[0].scriptSig = CScript() << OP_1;
277  tx.vin[0].prevout.hash = txFirst[1]->GetHash();
278  tx.vout[0].nValue = BLOCKSUBSIDY-HIGHFEE;
279  hash = tx.GetHash();
280  m_node.mempool->addUnchecked(entry.Fee(HIGHFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
281  tx.vin[0].prevout.hash = hash;
282  tx.vin.resize(2);
283  tx.vin[1].scriptSig = CScript() << OP_1;
284  tx.vin[1].prevout.hash = txFirst[0]->GetHash();
285  tx.vin[1].prevout.n = 0;
286  tx.vout[0].nValue = tx.vout[0].nValue+BLOCKSUBSIDY-HIGHERFEE; //First txn output + fresh coinbase - new txn fee
287  hash = tx.GetHash();
288  m_node.mempool->addUnchecked(entry.Fee(HIGHERFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
289  BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey));
290  m_node.mempool->clear();
291 
292  // coinbase in *m_node.mempool, template creation fails
293  tx.vin.resize(1);
294  tx.vin[0].prevout.SetNull();
295  tx.vin[0].scriptSig = CScript() << OP_0 << OP_1;
296  tx.vout[0].nValue = 0;
297  hash = tx.GetHash();
298  // give it a fee so it'll get mined
299  m_node.mempool->addUnchecked(entry.Fee(LOWFEE).Time(GetTime()).SpendsCoinbase(false).FromTx(tx));
300  // Should throw bad-cb-multiple
301  BOOST_CHECK_EXCEPTION(AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey), std::runtime_error, HasReason("bad-cb-multiple"));
302  m_node.mempool->clear();
303 
304  // double spend txn pair in *m_node.mempool, template creation fails
305  tx.vin[0].prevout.hash = txFirst[0]->GetHash();
306  tx.vin[0].scriptSig = CScript() << OP_1;
307  tx.vout[0].nValue = BLOCKSUBSIDY-HIGHFEE;
308  tx.vout[0].scriptPubKey = CScript() << OP_1;
309  hash = tx.GetHash();
310  m_node.mempool->addUnchecked(entry.Fee(HIGHFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
311  tx.vout[0].scriptPubKey = CScript() << OP_2;
312  hash = tx.GetHash();
313  m_node.mempool->addUnchecked(entry.Fee(HIGHFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
314  BOOST_CHECK_EXCEPTION(AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey), std::runtime_error, HasReason("bad-txns-inputs-missingorspent"));
315  m_node.mempool->clear();
316 
317  // subsidy changing
318  int nHeight = m_node.chainman->ActiveChain().Height();
319  // Create an actual 209999-long block chain (without valid blocks).
320  while (m_node.chainman->ActiveChain().Tip()->nHeight < 209999) {
321  CBlockIndex* prev = m_node.chainman->ActiveChain().Tip();
322  CBlockIndex* next = new CBlockIndex();
323  next->phashBlock = new uint256(InsecureRand256());
324  m_node.chainman->ActiveChainstate().CoinsTip().SetBestBlock(next->GetBlockHash());
325  next->pprev = prev;
326  next->nHeight = prev->nHeight + 1;
327  next->BuildSkip();
328  m_node.chainman->ActiveChain().SetTip(*next);
329  }
330  BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey));
331  // Extend to a 210000-long block chain.
332  while (m_node.chainman->ActiveChain().Tip()->nHeight < 210000) {
333  CBlockIndex* prev = m_node.chainman->ActiveChain().Tip();
334  CBlockIndex* next = new CBlockIndex();
335  next->phashBlock = new uint256(InsecureRand256());
336  m_node.chainman->ActiveChainstate().CoinsTip().SetBestBlock(next->GetBlockHash());
337  next->pprev = prev;
338  next->nHeight = prev->nHeight + 1;
339  next->BuildSkip();
340  m_node.chainman->ActiveChain().SetTip(*next);
341  }
342  BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey));
343 
344  // invalid p2sh txn in *m_node.mempool, template creation fails
345  tx.vin[0].prevout.hash = txFirst[0]->GetHash();
346  tx.vin[0].prevout.n = 0;
347  tx.vin[0].scriptSig = CScript() << OP_1;
348  tx.vout[0].nValue = BLOCKSUBSIDY-LOWFEE;
349  CScript script = CScript() << OP_0;
350  tx.vout[0].scriptPubKey = GetScriptForDestination(ScriptHash(script));
351  hash = tx.GetHash();
352  m_node.mempool->addUnchecked(entry.Fee(LOWFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
353  tx.vin[0].prevout.hash = hash;
354  tx.vin[0].scriptSig = CScript() << std::vector<unsigned char>(script.begin(), script.end());
355  tx.vout[0].nValue -= LOWFEE;
356  hash = tx.GetHash();
357  m_node.mempool->addUnchecked(entry.Fee(LOWFEE).Time(GetTime()).SpendsCoinbase(false).FromTx(tx));
358  // Should throw block-validation-failed
359  BOOST_CHECK_EXCEPTION(AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey), std::runtime_error, HasReason("block-validation-failed"));
360  m_node.mempool->clear();
361 
362  // Delete the dummy blocks again.
363  while (m_node.chainman->ActiveChain().Tip()->nHeight > nHeight) {
364  CBlockIndex* del = m_node.chainman->ActiveChain().Tip();
365  m_node.chainman->ActiveChain().SetTip(*Assert(del->pprev));
366  m_node.chainman->ActiveChainstate().CoinsTip().SetBestBlock(del->pprev->GetBlockHash());
367  delete del->phashBlock;
368  delete del;
369  }
370 
371  // non-final txs in mempool
372  SetMockTime(m_node.chainman->ActiveChain().Tip()->GetMedianTimePast() + 1);
373  const int flags{LOCKTIME_VERIFY_SEQUENCE};
374  // height map
375  std::vector<int> prevheights;
376 
377  // relative height locked
378  tx.nVersion = 2;
379  tx.vin.resize(1);
380  prevheights.resize(1);
381  tx.vin[0].prevout.hash = txFirst[0]->GetHash(); // only 1 transaction
382  tx.vin[0].prevout.n = 0;
383  tx.vin[0].scriptSig = CScript() << OP_1;
384  tx.vin[0].nSequence = m_node.chainman->ActiveChain().Tip()->nHeight + 1; // txFirst[0] is the 2nd block
385  prevheights[0] = baseheight + 1;
386  tx.vout.resize(1);
387  tx.vout[0].nValue = BLOCKSUBSIDY-HIGHFEE;
388  tx.vout[0].scriptPubKey = CScript() << OP_1;
389  tx.nLockTime = 0;
390  hash = tx.GetHash();
391  m_node.mempool->addUnchecked(entry.Fee(HIGHFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
392  BOOST_CHECK(CheckFinalTxAtTip(*Assert(m_node.chainman->ActiveChain().Tip()), CTransaction{tx})); // Locktime passes
393  BOOST_CHECK(!TestSequenceLocks(CTransaction{tx})); // Sequence locks fail
394 
395  {
396  CBlockIndex* active_chain_tip = m_node.chainman->ActiveChain().Tip();
397  BOOST_CHECK(SequenceLocks(CTransaction(tx), flags, prevheights, CreateBlockIndex(active_chain_tip->nHeight + 2, active_chain_tip))); // Sequence locks pass on 2nd block
398  }
399 
400  // relative time locked
401  tx.vin[0].prevout.hash = txFirst[1]->GetHash();
402  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
403  prevheights[0] = baseheight + 2;
404  hash = tx.GetHash();
405  m_node.mempool->addUnchecked(entry.Time(GetTime()).FromTx(tx));
406  BOOST_CHECK(CheckFinalTxAtTip(*Assert(m_node.chainman->ActiveChain().Tip()), CTransaction{tx})); // Locktime passes
407  BOOST_CHECK(!TestSequenceLocks(CTransaction{tx})); // Sequence locks fail
408 
409  const int SEQUENCE_LOCK_TIME = 512; // Sequence locks pass 512 seconds later
410  for (int i = 0; i < CBlockIndex::nMedianTimeSpan; ++i)
411  m_node.chainman->ActiveChain().Tip()->GetAncestor(m_node.chainman->ActiveChain().Tip()->nHeight - i)->nTime += SEQUENCE_LOCK_TIME; // Trick the MedianTimePast
412  {
413  CBlockIndex* active_chain_tip = m_node.chainman->ActiveChain().Tip();
414  BOOST_CHECK(SequenceLocks(CTransaction(tx), flags, prevheights, CreateBlockIndex(active_chain_tip->nHeight + 1, active_chain_tip)));
415  }
416 
417  for (int i = 0; i < CBlockIndex::nMedianTimeSpan; ++i) {
418  CBlockIndex* ancestor{Assert(m_node.chainman->ActiveChain().Tip()->GetAncestor(m_node.chainman->ActiveChain().Tip()->nHeight - i))};
419  ancestor->nTime -= SEQUENCE_LOCK_TIME; // undo tricked MTP
420  }
421 
422  // absolute height locked
423  tx.vin[0].prevout.hash = txFirst[2]->GetHash();
424  tx.vin[0].nSequence = CTxIn::MAX_SEQUENCE_NONFINAL;
425  prevheights[0] = baseheight + 3;
426  tx.nLockTime = m_node.chainman->ActiveChain().Tip()->nHeight + 1;
427  hash = tx.GetHash();
428  m_node.mempool->addUnchecked(entry.Time(GetTime()).FromTx(tx));
429  BOOST_CHECK(!CheckFinalTxAtTip(*Assert(m_node.chainman->ActiveChain().Tip()), CTransaction{tx})); // Locktime fails
430  BOOST_CHECK(TestSequenceLocks(CTransaction{tx})); // Sequence locks pass
431  BOOST_CHECK(IsFinalTx(CTransaction(tx), m_node.chainman->ActiveChain().Tip()->nHeight + 2, m_node.chainman->ActiveChain().Tip()->GetMedianTimePast())); // Locktime passes on 2nd block
432 
433  // absolute time locked
434  tx.vin[0].prevout.hash = txFirst[3]->GetHash();
435  tx.nLockTime = m_node.chainman->ActiveChain().Tip()->GetMedianTimePast();
436  prevheights.resize(1);
437  prevheights[0] = baseheight + 4;
438  hash = tx.GetHash();
439  m_node.mempool->addUnchecked(entry.Time(GetTime()).FromTx(tx));
440  BOOST_CHECK(!CheckFinalTxAtTip(*Assert(m_node.chainman->ActiveChain().Tip()), CTransaction{tx})); // Locktime fails
441  BOOST_CHECK(TestSequenceLocks(CTransaction{tx})); // Sequence locks pass
442  BOOST_CHECK(IsFinalTx(CTransaction(tx), m_node.chainman->ActiveChain().Tip()->nHeight + 2, m_node.chainman->ActiveChain().Tip()->GetMedianTimePast() + 1)); // Locktime passes 1 second later
443 
444  // mempool-dependent transactions (not added)
445  tx.vin[0].prevout.hash = hash;
446  prevheights[0] = m_node.chainman->ActiveChain().Tip()->nHeight + 1;
447  tx.nLockTime = 0;
448  tx.vin[0].nSequence = 0;
449  BOOST_CHECK(CheckFinalTxAtTip(*Assert(m_node.chainman->ActiveChain().Tip()), CTransaction{tx})); // Locktime passes
450  BOOST_CHECK(TestSequenceLocks(CTransaction{tx})); // Sequence locks pass
451  tx.vin[0].nSequence = 1;
452  BOOST_CHECK(!TestSequenceLocks(CTransaction{tx})); // Sequence locks fail
453  tx.vin[0].nSequence = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG;
454  BOOST_CHECK(TestSequenceLocks(CTransaction{tx})); // Sequence locks pass
455  tx.vin[0].nSequence = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | 1;
456  BOOST_CHECK(!TestSequenceLocks(CTransaction{tx})); // Sequence locks fail
457 
458  BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey));
459 
460  // None of the of the absolute height/time locked tx should have made
461  // it into the template because we still check IsFinalTx in CreateNewBlock,
462  // but relative locked txs will if inconsistently added to mempool.
463  // For now these will still generate a valid template until BIP68 soft fork
464  BOOST_CHECK_EQUAL(pblocktemplate->block.vtx.size(), 3U);
465  // However if we advance height by 1 and time by SEQUENCE_LOCK_TIME, all of them should be mined
466  for (int i = 0; i < CBlockIndex::nMedianTimeSpan; ++i) {
467  CBlockIndex* ancestor{Assert(m_node.chainman->ActiveChain().Tip()->GetAncestor(m_node.chainman->ActiveChain().Tip()->nHeight - i))};
468  ancestor->nTime += SEQUENCE_LOCK_TIME; // Trick the MedianTimePast
469  }
470  m_node.chainman->ActiveChain().Tip()->nHeight++;
471  SetMockTime(m_node.chainman->ActiveChain().Tip()->GetMedianTimePast() + 1);
472 
473  BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey));
474  BOOST_CHECK_EQUAL(pblocktemplate->block.vtx.size(), 5U);
475 }
476 
477 void MinerTestingSetup::TestPrioritisedMining(const CChainParams& chainparams, const CScript& scriptPubKey, const std::vector<CTransactionRef>& txFirst)
478 {
480 
481  // Test that a tx below min fee but prioritised is included
483  tx.vin.resize(1);
484  tx.vin[0].prevout.hash = txFirst[0]->GetHash();
485  tx.vin[0].prevout.n = 0;
486  tx.vin[0].scriptSig = CScript() << OP_1;
487  tx.vout.resize(1);
488  tx.vout[0].nValue = 5000000000LL; // 0 fee
489  uint256 hashFreePrioritisedTx = tx.GetHash();
490  m_node.mempool->addUnchecked(entry.Fee(0).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
491  m_node.mempool->PrioritiseTransaction(hashFreePrioritisedTx, 5 * COIN);
492 
493  tx.vin[0].prevout.hash = txFirst[1]->GetHash();
494  tx.vin[0].prevout.n = 0;
495  tx.vout[0].nValue = 5000000000LL - 1000;
496  // This tx has a low fee: 1000 satoshis
497  uint256 hashParentTx = tx.GetHash(); // save this txid for later use
498  m_node.mempool->addUnchecked(entry.Fee(1000).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
499 
500  // This tx has a medium fee: 10000 satoshis
501  tx.vin[0].prevout.hash = txFirst[2]->GetHash();
502  tx.vout[0].nValue = 5000000000LL - 10000;
503  uint256 hashMediumFeeTx = tx.GetHash();
504  m_node.mempool->addUnchecked(entry.Fee(10000).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
505  m_node.mempool->PrioritiseTransaction(hashMediumFeeTx, -5 * COIN);
506 
507  // This tx also has a low fee, but is prioritised
508  tx.vin[0].prevout.hash = hashParentTx;
509  tx.vout[0].nValue = 5000000000LL - 1000 - 1000; // 1000 satoshi fee
510  uint256 hashPrioritsedChild = tx.GetHash();
511  m_node.mempool->addUnchecked(entry.Fee(1000).Time(GetTime()).SpendsCoinbase(false).FromTx(tx));
512  m_node.mempool->PrioritiseTransaction(hashPrioritsedChild, 2 * COIN);
513 
514  // Test that transaction selection properly updates ancestor fee calculations as prioritised
515  // parents get included in a block. Create a transaction with two prioritised ancestors, each
516  // included by itself: FreeParent <- FreeChild <- FreeGrandchild.
517  // When FreeParent is added, a modified entry will be created for FreeChild + FreeGrandchild
518  // FreeParent's prioritisation should not be included in that entry.
519  // When FreeChild is included, FreeChild's prioritisation should also not be included.
520  tx.vin[0].prevout.hash = txFirst[3]->GetHash();
521  tx.vout[0].nValue = 5000000000LL; // 0 fee
522  uint256 hashFreeParent = tx.GetHash();
523  m_node.mempool->addUnchecked(entry.Fee(0).SpendsCoinbase(true).FromTx(tx));
524  m_node.mempool->PrioritiseTransaction(hashFreeParent, 10 * COIN);
525 
526  tx.vin[0].prevout.hash = hashFreeParent;
527  tx.vout[0].nValue = 5000000000LL; // 0 fee
528  uint256 hashFreeChild = tx.GetHash();
529  m_node.mempool->addUnchecked(entry.Fee(0).SpendsCoinbase(false).FromTx(tx));
530  m_node.mempool->PrioritiseTransaction(hashFreeChild, 1 * COIN);
531 
532  tx.vin[0].prevout.hash = hashFreeChild;
533  tx.vout[0].nValue = 5000000000LL; // 0 fee
534  uint256 hashFreeGrandchild = tx.GetHash();
535  m_node.mempool->addUnchecked(entry.Fee(0).SpendsCoinbase(false).FromTx(tx));
536 
537  auto pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey);
538  BOOST_REQUIRE_EQUAL(pblocktemplate->block.vtx.size(), 6U);
539  BOOST_CHECK(pblocktemplate->block.vtx[1]->GetHash() == hashFreeParent);
540  BOOST_CHECK(pblocktemplate->block.vtx[2]->GetHash() == hashFreePrioritisedTx);
541  BOOST_CHECK(pblocktemplate->block.vtx[3]->GetHash() == hashParentTx);
542  BOOST_CHECK(pblocktemplate->block.vtx[4]->GetHash() == hashPrioritsedChild);
543  BOOST_CHECK(pblocktemplate->block.vtx[5]->GetHash() == hashFreeChild);
544  for (size_t i=0; i<pblocktemplate->block.vtx.size(); ++i) {
545  // The FreeParent and FreeChild's prioritisations should not impact the child.
546  BOOST_CHECK(pblocktemplate->block.vtx[i]->GetHash() != hashFreeGrandchild);
547  // De-prioritised transaction should not be included.
548  BOOST_CHECK(pblocktemplate->block.vtx[i]->GetHash() != hashMediumFeeTx);
549  }
550 }
551 
552 // NOTE: These tests rely on CreateNewBlock doing its own self-validation!
553 BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
554 {
555  // Note that by default, these tests run with size accounting enabled.
556  const auto chainParams = CreateChainParams(*m_node.args, CBaseChainParams::MAIN);
557  const CChainParams& chainparams = *chainParams;
558  CScript scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
559  std::unique_ptr<CBlockTemplate> pblocktemplate;
560 
561  fCheckpointsEnabled = false;
562 
563  // Simple block creation, nothing special yet:
564  BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey));
565 
566  // We can't make transactions until we have inputs
567  // Therefore, load 110 blocks :)
568  static_assert(std::size(BLOCKINFO) == 110, "Should have 110 blocks to import");
569  int baseheight = 0;
570  std::vector<CTransactionRef> txFirst;
571  for (const auto& bi : BLOCKINFO) {
572  CBlock *pblock = &pblocktemplate->block; // pointer for convenience
573  {
574  LOCK(cs_main);
575  pblock->nVersion = VERSIONBITS_TOP_BITS;
576  pblock->nTime = m_node.chainman->ActiveChain().Tip()->GetMedianTimePast()+1;
577  CMutableTransaction txCoinbase(*pblock->vtx[0]);
578  txCoinbase.nVersion = 1;
579  txCoinbase.vin[0].scriptSig = CScript{} << (m_node.chainman->ActiveChain().Height() + 1) << bi.extranonce;
580  txCoinbase.vout.resize(1); // Ignore the (optional) segwit commitment added by CreateNewBlock (as the hardcoded nonces don't account for this)
581  txCoinbase.vout[0].scriptPubKey = CScript();
582  pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase));
583  if (txFirst.size() == 0)
584  baseheight = m_node.chainman->ActiveChain().Height();
585  if (txFirst.size() < 4)
586  txFirst.push_back(pblock->vtx[0]);
587  pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
588  pblock->nNonce = bi.nonce;
589  }
590  std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(*pblock);
591  BOOST_CHECK(Assert(m_node.chainman)->ProcessNewBlock(shared_pblock, true, true, nullptr));
592  pblock->hashPrevBlock = pblock->GetHash();
593  }
594 
595  LOCK(cs_main);
596  LOCK(m_node.mempool->cs);
597 
598  TestBasicMining(chainparams, scriptPubKey, txFirst, baseheight);
599 
600  m_node.chainman->ActiveChain().Tip()->nHeight--;
601  SetMockTime(0);
602  m_node.mempool->clear();
603 
604  TestPackageSelection(chainparams, scriptPubKey, txFirst);
605 
606  m_node.chainman->ActiveChain().Tip()->nHeight--;
607  SetMockTime(0);
608  m_node.mempool->clear();
609 
610  TestPrioritisedMining(chainparams, scriptPubKey, txFirst);
611 
612  fCheckpointsEnabled = true;
613 }
614 
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
node::NodeContext m_node
Definition: bitcoin-gui.cpp:37
int flags
Definition: bitcoin-tx.cpp:525
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: validation.cpp:121
std::unique_ptr< const CChainParams > CreateChainParams(const ArgsManager &args, const std::string &chain)
Creates and returns a std::unique_ptr<CChainParams> of the chosen chain.
#define Assert(val)
Identity function.
Definition: check.h:74
static const std::string MAIN
Chain name strings.
uint32_t nNonce
Definition: block.h:30
uint32_t nTime
Definition: block.h:28
int32_t nVersion
Definition: block.h:25
uint256 hashPrevBlock
Definition: block.h:26
uint256 hashMerkleRoot
Definition: block.h:27
uint256 GetHash() const
Definition: block.cpp:11
Definition: block.h:69
std::vector< CTransactionRef > vtx
Definition: block.h:72
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:152
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:158
void BuildSkip()
Build the skiplist pointer for this entry.
Definition: chain.cpp:125
uint256 GetBlockHash() const
Definition: chain.h:264
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:164
static constexpr int nMedianTimeSpan
Definition: chain.h:294
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Definition: chain.h:155
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:70
CCoinsView that brings transactions from a mempool into view.
Definition: txmempool.h:908
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:33
CAmount GetFee(uint32_t num_bytes) const
Return the fee in satoshis for the given vsize in vbytes.
Definition: feerate.cpp:23
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:411
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:288
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:94
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:111
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:126
BOOST_CHECK_EXCEPTION predicates to check the specific validation error.
Definition: setup_common.h:242
Generate a new block, without valid proof-of-work.
Definition: miner.h:129
iterator begin()
Definition: prevector.h:292
iterator end()
Definition: prevector.h:294
256-bit opaque blob.
Definition: uint256.h:119
static constexpr unsigned int LOCKTIME_VERIFY_SEQUENCE
Flags for nSequence and nLockTime locks.
Definition: consensus.h:28
static const unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
Definition: consensus.h:15
BOOST_AUTO_TEST_SUITE_END()
unsigned int nHeight
bool spendsCoinbase
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:65
BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
static CFeeRate blockMinFeeRate
Definition: miner_tests.cpp:47
static CBlockIndex CreateBlockIndex(int nHeight, CBlockIndex *active_chain_tip) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: miner_tests.cpp:81
unsigned char extranonce
Definition: miner_tests.cpp:59
unsigned int nonce
Definition: miner_tests.cpp:60
constexpr static struct @15 BLOCKINFO[]
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:17
#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:25
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:415
@ OP_2
Definition: script.h:81
@ OP_CHECKMULTISIG
Definition: script.h:188
@ OP_CHECKSIG
Definition: script.h:186
@ OP_NOP
Definition: script.h:98
@ OP_1
Definition: script.h:79
@ OP_DROP
Definition: script.h:120
@ OP_0
Definition: script.h:72
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1109
static constexpr CAmount CENT
Definition: setup_common.h:78
static uint256 InsecureRand256()
Definition: setup_common.h:73
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:334
node::NodeContext m_node
Definition: setup_common.h:84
A mutable version of CTransaction.
Definition: transaction.h:373
uint256 GetHash() const
Compute the hash of this CMutableTransaction.
Definition: transaction.cpp:68
std::vector< CTxOut > vout
Definition: transaction.h:375
std::vector< CTxIn > vin
Definition: transaction.h:374
Definition: setup_common.h:207
TestMemPoolEntryHelper & SpendsCoinbase(bool _flag)
Definition: setup_common.h:227
CAmount nFee
Definition: setup_common.h:209
CTxMemPoolEntry FromTx(const CMutableTransaction &tx) const
unsigned int nHeight
Definition: setup_common.h:211
TestMemPoolEntryHelper & Time(int64_t _time)
Definition: setup_common.h:225
TestMemPoolEntryHelper & Fee(CAmount _fee)
Definition: setup_common.h:224
Testing setup that configures a complete environment.
Definition: setup_common.h:109
void TestPackageSelection(const CChainParams &chainparams, const CScript &scriptPubKey, const std::vector< CTransactionRef > &txFirst) EXCLUSIVE_LOCKS_REQUIRED(void TestBasicMining(const CChainParams &chainparams, const CScript &scriptPubKey, const std::vector< CTransactionRef > &txFirst, int baseheight) EXCLUSIVE_LOCKS_REQUIRED(void TestPrioritisedMining(const CChainParams &chainparams, const CScript &scriptPubKey, const std::vector< CTransactionRef > &txFirst) EXCLUSIVE_LOCKS_REQUIRED(bool TestSequenceLocks(const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(
Definition: miner_tests.cpp:36
BlockAssembler AssemblerForTest(const CChainParams &params)
Definition: miner_tests.cpp:49
std::unique_ptr< CTxMemPool > mempool
Definition: context.h:50
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:54
ArgsManager * args
Definition: context.h:56
#define LOCK(cs)
Definition: sync.h:261
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
int64_t GetTime()
Definition: time.cpp:117
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition: time.cpp:91
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:111
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
@ REPLACED
Removed for replacement.
std::vector< Byte > ParseHex(std::string_view str)
Parse the hex string into bytes (uint8_t or std::byte).
bool CheckFinalTxAtTip(const CBlockIndex &active_chain_tip, const CTransaction &tx)
Definition: validation.cpp:160
bool fCheckpointsEnabled
Definition: validation.cpp:128
bool CheckFinalTxAtTip(const CBlockIndex &active_chain_tip, const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(bool CheckSequenceLocksAtTip(CBlockIndex *tip, const CCoinsView &coins_view, const CTransaction &tx, LockPoints *lp=nullptr, bool useExistingLockPoints=false)
Check if transaction will be final in the next block to be created.
Definition: validation.h:283
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12
static const int32_t VERSIONBITS_TOP_BITS
What bits to set in version for versionbits blocks.
Definition: versionbits.h:16