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