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