text: // Copyright (c) 2011-2015 The Bitcoin Core developers
  // Distributed under the MIT software license, see the accompanying
  // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  
  #include "chainparams.h"
  #include "coins.h"
  #include "consensus/consensus.h"
  #include "consensus/merkle.h"
  #include "consensus/validation.h"
  #include "validation.h"
  #include "masternode-payments.h"
  #include "miner.h"
  #include "policy/policy.h"
  #include "pubkey.h"
  #include "script/standard.h"
  #include "txmempool.h"
  #include "uint256.h"
  #include "util.h"
  #include "utilstrencodings.h"
  #include "primitives/transaction.h"
  
  #include "test/test_dash.h"
  
  #include <memory>
  
  #include <boost/test/unit_test.hpp>
  
  struct TestnetTestingSetup : public TestingSetup {
      TestnetTestingSetup() : TestingSetup(CBaseChainParams::TESTNET) {}
  };
  
  BOOST_FIXTURE_TEST_SUITE(miner_tests, TestnetTestingSetup)
  
  static CFeeRate blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE);
  
  static BlockAssembler AssemblerForTest(const CChainParams& params) {
      BlockAssembler::Options options;
  
      options.nBlockMaxSize = DEFAULT_BLOCK_MAX_SIZE;
      options.blockMinFeeRate = blockMinFeeRate;
      return BlockAssembler(params, options);
  }
  
  static
  struct {
      unsigned char extranonce;
      unsigned int nonce;
  } blockinfo[] = {
      {0, 3113015}, {0, 1478645}, {0, 220976}, {0, 53647},
      {0, 37438}, {0, 198150}, {0, 265631}, {0, 665437},
      {0, 487214}, {0, 566668}, {0, 1251390}, {0, 869149},
      {0, 586950}, {0, 613416}, {0, 574852}, {0, 2131081},
      {0, 170690}, {0, 131486}, {0, 945521}, {0, 156712},
      {0, 206393}, {0, 1213868}, {0, 1775777}, {0, 394320},
      {0, 307180}, {0, 147314}, {0, 298006}, {0, 826319},
      {0, 844227}, {0, 1258740}, {0, 961643}, {0, 836456},
      {0, 981673}, {0, 207111}, {0, 3285577}, {0, 290627},
      {0, 1738441}, {0, 1803414}, {0, 308350}, {0, 529914},
      {0, 1139987}, {0, 808458}, {0, 51258}, {0, 18081},
      {0, 573762}, {0, 121594}, {0, 219977}, {0, 165086},
      {0, 1955973}, {0, 101046}, {0, 213078}, {0, 368692},
      {0, 39664}, {0, 418533}, {0, 1240932}, {0, 43546},
      {0, 1757805}, {0, 5196480}, {0, 869104}, {0, 21187},
      {0, 143248}, {0, 1010207}, {0, 571234}, {0, 135657},
      {0, 178847}, {0, 2672521}, {0, 2562455}, {0, 528638},
      {0, 329565}, {0, 6735106}, {0, 96868}, {0, 1392531},
      {0, 419597}, {0, 298323}, {0, 2128349}, {0, 510573},
      {0, 1046865}, {0, 395480}, {0, 516678}, {0, 137590},
      {0, 1443787}, {0, 295227}, {0, 546322}, {0, 41818},
      {0, 131228}, {0, 983725}, {0, 1261167}, {0, 465381},
      {0, 115620}, {0, 92259}, {0, 206585}, {0, 212395},
      {0, 281019}, {0, 977482}, {0, 962756}, {0, 203730},
      {0, 2051092}, {0, 1656616}, {0, 264930}, {0, 975867}
  };
  CBlockIndex CreateBlockIndex(int nHeight)
  {
      CBlockIndex index;
      index.nHeight = nHeight;
      index.pprev = chainActive.Tip();
      return index;
  }
  
  bool TestSequenceLocks(const CTransaction &tx, int flags)
  {
      LOCK(mempool.cs);
      return CheckSequenceLocks(tx, flags);
  }
  
  // Test suite for ancestor feerate transaction selection.
  // Implemented as an additional function, rather than a separate test case,
  // to allow reusing the blockchain created in CreateNewBlock_validity.
  void TestPackageSelection(const CChainParams& chainparams, CScript scriptPubKey, std::vector<CTransactionRef>& txFirst)
  {
      // Disable free transactions, otherwise TX selection is non-deterministic
      SoftSetArg("-blockprioritysize", "0");
  
      // Test the ancestor feerate transaction selection.
      TestMemPoolEntryHelper entry;
  
      // Test that a medium fee transaction will be selected after a higher fee
      // rate package with a low fee rate parent.
      CMutableTransaction tx;
      tx.vin.resize(1);
      tx.vin[0].scriptSig = CScript() << OP_1;
      tx.vin[0].prevout.hash = txFirst[0]->GetHash();
      tx.vin[0].prevout.n = 0;
      tx.vout.resize(1);
      tx.vout[0].nValue = 5000000000LL - 1000;
      // This tx has a low fee: 1000 satoshis
      uint256 hashParentTx = tx.GetHash(); // save this txid for later use
      mempool.addUnchecked(hashParentTx, entry.Fee(1000).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
  
      // This tx has a medium fee: 10000 satoshis
      tx.vin[0].prevout.hash = txFirst[1]->GetHash();
      tx.vout[0].nValue = 5000000000LL - 10000;
      uint256 hashMediumFeeTx = tx.GetHash();
      mempool.addUnchecked(hashMediumFeeTx, entry.Fee(10000).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
  
      // This tx has a high fee, but depends on the first transaction
      tx.vin[0].prevout.hash = hashParentTx;
      tx.vout[0].nValue = 5000000000LL - 1000 - 50000; // 50k satoshi fee
      uint256 hashHighFeeTx = tx.GetHash();
      mempool.addUnchecked(hashHighFeeTx, entry.Fee(50000).Time(GetTime()).SpendsCoinbase(false).FromTx(tx));
  
      std::unique_ptr<CBlockTemplate> pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey);
      BOOST_CHECK(pblocktemplate->block.vtx[1]->GetHash() == hashParentTx);
      BOOST_CHECK(pblocktemplate->block.vtx[2]->GetHash() == hashHighFeeTx);
      BOOST_CHECK(pblocktemplate->block.vtx[3]->GetHash() == hashMediumFeeTx);
  
      // Test that a package below the block min tx fee doesn't get included
      tx.vin[0].prevout.hash = hashHighFeeTx;
      tx.vout[0].nValue = 5000000000LL - 1000 - 50000; // 0 fee
      uint256 hashFreeTx = tx.GetHash();
      mempool.addUnchecked(hashFreeTx, entry.Fee(0).FromTx(tx));
      size_t freeTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
  
      // Calculate a fee on child transaction that will put the package just
      // below the block min tx fee (assuming 1 child tx of the same size).
      CAmount feeToUse = blockMinFeeRate.GetFee(2*freeTxSize) - 1;
  
      tx.vin[0].prevout.hash = hashFreeTx;
      tx.vout[0].nValue = 5000000000LL - 1000 - 50000 - feeToUse;
      uint256 hashLowFeeTx = tx.GetHash();
      mempool.addUnchecked(hashLowFeeTx, entry.Fee(feeToUse).FromTx(tx));
      pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey);
      // Verify that the free tx and the low fee tx didn't get selected
      for (size_t i=0; i<pblocktemplate->block.vtx.size(); ++i) {
          BOOST_CHECK(pblocktemplate->block.vtx[i]->GetHash() != hashFreeTx);
          BOOST_CHECK(pblocktemplate->block.vtx[i]->GetHash() != hashLowFeeTx);
      }
  
      // Test that packages above the min relay fee do get included, even if one
      // of the transactions is below the min relay fee
      // Remove the low fee transaction and replace with a higher fee transaction
      mempool.removeRecursive(tx);
      tx.vout[0].nValue -= 2; // Now we should be just over the min relay fee
      hashLowFeeTx = tx.GetHash();
      mempool.addUnchecked(hashLowFeeTx, entry.Fee(feeToUse+2).FromTx(tx));
      pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey);
      BOOST_CHECK(pblocktemplate->block.vtx[4]->GetHash() == hashFreeTx);
      BOOST_CHECK(pblocktemplate->block.vtx[5]->GetHash() == hashLowFeeTx);
  
      // Test that transaction selection properly updates ancestor fee
      // calculations as ancestor transactions get included in a block.
      // Add a 0-fee transaction that has 2 outputs.
      tx.vin[0].prevout.hash = txFirst[2]->GetHash();
      tx.vout.resize(2);
      tx.vout[0].nValue = 5000000000LL - 100000000;
      tx.vout[1].nValue = 100000000; // 1BTC output
      uint256 hashFreeTx2 = tx.GetHash();
      mempool.addUnchecked(hashFreeTx2, entry.Fee(0).SpendsCoinbase(true).FromTx(tx));
  
      // This tx can't be mined by itself
      tx.vin[0].prevout.hash = hashFreeTx2;
      tx.vout.resize(1);
      feeToUse = blockMinFeeRate.GetFee(freeTxSize);
      tx.vout[0].nValue = 5000000000LL - 100000000 - feeToUse;
      uint256 hashLowFeeTx2 = tx.GetHash();
      mempool.addUnchecked(hashLowFeeTx2, entry.Fee(feeToUse).SpendsCoinbase(false).FromTx(tx));
      pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey);
  
      // Verify that this tx isn't selected.
      for (size_t i=0; i<pblocktemplate->block.vtx.size(); ++i) {
          BOOST_CHECK(pblocktemplate->block.vtx[i]->GetHash() != hashFreeTx2);
          BOOST_CHECK(pblocktemplate->block.vtx[i]->GetHash() != hashLowFeeTx2);
      }
  
      // This tx will be mineable, and should cause hashLowFeeTx2 to be selected
      // as well.
      tx.vin[0].prevout.n = 1;
      tx.vout[0].nValue = 100000000 - 10000; // 10k satoshi fee
      mempool.addUnchecked(tx.GetHash(), entry.Fee(10000).FromTx(tx));
      pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey);
      BOOST_CHECK(pblocktemplate->block.vtx[8]->GetHash() == hashLowFeeTx2);
  }
  
  // NOTE: These tests rely on CreateNewBlock doing its own self-validation!
  BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
  {
      const CChainParams& chainparams = Params(CBaseChainParams::TESTNET);
      CScript scriptPubKey = CScript() << ParseHex("045e8f2ce0dbe0455e33fa7cc7b1048b6977a0f81828991fc3a088cd4386b25531bcfae0351359b2fbe51aa71c819d0b05ee3c1ac72fdb4bb26b842e6bf6e6449f") << OP_CHECKSIG;
      std::unique_ptr<CBlockTemplate> pblocktemplate;
      CMutableTransaction tx,tx2;
      CScript script;
      uint256 hash;
      TestMemPoolEntryHelper entry;
      entry.nFee = 11;
      entry.nHeight = 11;
  
      fCheckpointsEnabled = false;
  
      // We can't make transactions until we have inputs
      // Therefore, load 100 blocks :)
      int baseheight = 0;
      std::vector<CTransactionRef> txFirst;
  
      auto createAndProcessEmptyBlock = [&]() {
          int i = chainActive.Height();
          std::unique_ptr<CBlockTemplate> blocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey); // pointer for convenience
          CBlock *pblock = &blocktemplate->block;
          {
              if (txFirst.size() == 0)
                  baseheight = chainActive.Height();
              if (txFirst.size() < 4)
                  txFirst.push_back(pblock->vtx[0]);
              pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
              pblock->nNonce = blockinfo[i].nonce;
  
              // This will usually succeed in the first round as we take the nonce from blockinfo
              // It's however usefull when adding new blocks with unknown nonces (you should add the found block to blockinfo)
              while (!CheckProofOfWork(pblock->GetHash(), pblock->nBits, chainparams.GetConsensus())) {
                  pblock->nNonce++;
              }
              std::cout << "Block found " << i << ": " << pblock->nNonce << "\n";
          }
          std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(*pblock);
          BOOST_CHECK(ProcessNewBlock(chainparams, shared_pblock, true, NULL));
      };
  
      for (unsigned int i = 0; i < sizeof(blockinfo)/sizeof(*blockinfo) - 1; ++i)
      {
          createAndProcessEmptyBlock();
      }
  
      {
      LOCK(cs_main);
  
      // Just to make sure we can still make simple blocks
      BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey));
  
      const CAmount BLOCKSUBSIDY = 50*COIN;
      const CAmount LOWFEE = CENT;
      const CAmount HIGHFEE = COIN;
      const CAmount HIGHERFEE = 4*COIN;
  
      // block sigops > limit: 1000 CHECKMULTISIG + 1
      tx.vin.resize(1);
      // NOTE: OP_NOP is used to force 20 SigOps for the CHECKMULTISIG
      tx.vin[0].scriptSig = CScript() << OP_0 << OP_0 << OP_0 << OP_NOP << OP_CHECKMULTISIG << OP_1;
      tx.vin[0].prevout.hash = txFirst[0]->GetHash();
      tx.vin[0].prevout.n = 0;
      tx.vout.resize(1);
      tx.vout[0].nValue = BLOCKSUBSIDY;
      for (unsigned int i = 0; i < 1001; ++i)
      {
          tx.vout[0].nValue -= LOWFEE;
          hash = tx.GetHash();
          bool spendsCoinbase = (i == 0) ? true : false; // only first tx spends coinbase
          // If we don't set the # of sig ops in the CTxMemPoolEntry, template creation fails
          mempool.addUnchecked(hash, entry.Fee(LOWFEE).Time(GetTime()).SpendsCoinbase(spendsCoinbase).FromTx(tx));
          tx.vin[0].prevout.hash = hash;
      }
      BOOST_CHECK_THROW(AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey), std::runtime_error);
      mempool.clear();
  
      tx.vin[0].prevout.hash = txFirst[0]->GetHash();
      tx.vout[0].nValue = BLOCKSUBSIDY;
      for (unsigned int i = 0; i < 1001; ++i)
      {
          tx.vout[0].nValue -= LOWFEE;
          hash = tx.GetHash();
          bool spendsCoinbase = (i == 0) ? true : false; // only first tx spends coinbase
          // If we do set the # of sig ops in the CTxMemPoolEntry, template creation passes
          mempool.addUnchecked(hash, entry.Fee(LOWFEE).Time(GetTime()).SpendsCoinbase(spendsCoinbase).SigOps(20).FromTx(tx));
          tx.vin[0].prevout.hash = hash;
      }
      BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey));
      mempool.clear();
  
      // block size > limit
      tx.vin[0].scriptSig = CScript();
      // 18 * (520char + DROP) + OP_1 = 9433 bytes
      std::vector<unsigned char> vchData(520);
      for (unsigned int i = 0; i < 18; ++i)
          tx.vin[0].scriptSig << vchData << OP_DROP;
      tx.vin[0].scriptSig << OP_1;
      tx.vin[0].prevout.hash = txFirst[0]->GetHash();
      tx.vout[0].nValue = BLOCKSUBSIDY;
      for (unsigned int i = 0; i < 128; ++i)
      {
          tx.vout[0].nValue -= LOWFEE;
          hash = tx.GetHash();
          bool spendsCoinbase = (i == 0) ? true : false; // only first tx spends coinbase
          mempool.addUnchecked(hash, entry.Fee(LOWFEE).Time(GetTime()).SpendsCoinbase(spendsCoinbase).FromTx(tx));
          tx.vin[0].prevout.hash = hash;
      }
      BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey));
      mempool.clear();
  
      // orphan in mempool, template creation fails
      hash = tx.GetHash();
      mempool.addUnchecked(hash, entry.Fee(LOWFEE).Time(GetTime()).FromTx(tx));
      BOOST_CHECK_THROW(AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey), std::runtime_error);
      mempool.clear();
  
      // child with higher feerate than parent
      tx.vin[0].scriptSig = CScript() << OP_1;
      tx.vin[0].prevout.hash = txFirst[1]->GetHash();
      tx.vout[0].nValue = BLOCKSUBSIDY-HIGHFEE;
      hash = tx.GetHash();
      mempool.addUnchecked(hash, entry.Fee(HIGHFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
      tx.vin[0].prevout.hash = hash;
      tx.vin.resize(2);
      tx.vin[1].scriptSig = CScript() << OP_1;
      tx.vin[1].prevout.hash = txFirst[0]->GetHash();
      tx.vin[1].prevout.n = 0;
      tx.vout[0].nValue = tx.vout[0].nValue+BLOCKSUBSIDY-HIGHERFEE; //First txn output + fresh coinbase - new txn fee
      hash = tx.GetHash();
      mempool.addUnchecked(hash, entry.Fee(HIGHERFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
      BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey));
      mempool.clear();
  
      // coinbase in mempool, template creation fails
      tx.vin.resize(1);
      tx.vin[0].prevout.SetNull();
      tx.vin[0].scriptSig = CScript() << OP_0 << OP_1;
      tx.vout[0].nValue = 0;
      hash = tx.GetHash();
      // give it a fee so it'll get mined
      mempool.addUnchecked(hash, entry.Fee(LOWFEE).Time(GetTime()).SpendsCoinbase(false).FromTx(tx));
      BOOST_CHECK_THROW(AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey), std::runtime_error);
      mempool.clear();
  
      // invalid (pre-p2sh) txn in mempool, template creation fails
      tx.vin[0].prevout.hash = txFirst[0]->GetHash();
      tx.vin[0].prevout.n = 0;
      tx.vin[0].scriptSig = CScript() << OP_1;
      tx.vout[0].nValue = BLOCKSUBSIDY-LOWFEE;
      script = CScript() << OP_0;
      tx.vout[0].scriptPubKey = GetScriptForDestination(CScriptID(script));
      hash = tx.GetHash();
      mempool.addUnchecked(hash, entry.Fee(LOWFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
      tx.vin[0].prevout.hash = hash;
      tx.vin[0].scriptSig = CScript() << std::vector<unsigned char>(script.begin(), script.end());
      tx.vout[0].nValue -= LOWFEE;
      hash = tx.GetHash();
      mempool.addUnchecked(hash, entry.Fee(LOWFEE).Time(GetTime()).SpendsCoinbase(false).FromTx(tx));
      BOOST_CHECK_THROW(AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey), std::runtime_error);
      mempool.clear();
  
      // double spend txn pair in mempool, template creation fails
      tx.vin[0].prevout.hash = txFirst[0]->GetHash();
      tx.vin[0].scriptSig = CScript() << OP_1;
      tx.vout[0].nValue = BLOCKSUBSIDY-HIGHFEE;
      tx.vout[0].scriptPubKey = CScript() << OP_1;
      hash = tx.GetHash();
      mempool.addUnchecked(hash, entry.Fee(HIGHFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
      tx.vout[0].scriptPubKey = CScript() << OP_2;
      hash = tx.GetHash();
      mempool.addUnchecked(hash, entry.Fee(HIGHFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
      BOOST_CHECK_THROW(AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey), std::runtime_error);
      mempool.clear();
  
      // subsidy changing
      // int nHeight = chainActive.Height();
      // // Create an actual 209999-long block chain (without valid blocks).
      // while (chainActive.Tip()->nHeight < 209999) {
      //     CBlockIndex* prev = chainActive.Tip();
      //     CBlockIndex* next = new CBlockIndex();
      //     next->phashBlock = new uint256(GetRandHash());
      //     pcoinsTip->SetBestBlock(next->GetBlockHash());
      //     next->pprev = prev;
      //     next->nHeight = prev->nHeight + 1;
      //     next->BuildSkip();
      //     chainActive.SetTip(next);
      // }
      //BOOST_CHECK(pblocktemplate = BlockAssembler(chainparams).CreateNewBlock(scriptPubKey));
      // // Extend to a 210000-long block chain.
      // while (chainActive.Tip()->nHeight < 210000) {
      //     CBlockIndex* prev = chainActive.Tip();
      //     CBlockIndex* next = new CBlockIndex();
      //     next->phashBlock = new uint256(GetRandHash());
      //     pcoinsTip->SetBestBlock(next->GetBlockHash());
      //     next->pprev = prev;
      //     next->nHeight = prev->nHeight + 1;
      //     next->BuildSkip();
      //     chainActive.SetTip(next);
      // }
      //BOOST_CHECK(pblocktemplate = BlockAssembler(chainparams).CreateNewBlock(scriptPubKey));
      // // Delete the dummy blocks again.
      // while (chainActive.Tip()->nHeight > nHeight) {
      //     CBlockIndex* del = chainActive.Tip();
      //     chainActive.SetTip(del->pprev);
      //     pcoinsTip->SetBestBlock(del->pprev->GetBlockHash());
      //     delete del->phashBlock;
      //     delete del;
      // }
  
      // non-final txs in mempool
      SetMockTime(chainActive.Tip()->GetMedianTimePast()+1);
      int flags = LOCKTIME_VERIFY_SEQUENCE|LOCKTIME_MEDIAN_TIME_PAST;
      // height map
      std::vector<int> prevheights;
  
      // relative height locked
      tx.nVersion = 2;
      tx.vin.resize(1);
      prevheights.resize(1);
      tx.vin[0].prevout.hash = txFirst[0]->GetHash(); // only 1 transaction
      tx.vin[0].prevout.n = 0;
      tx.vin[0].scriptSig = CScript() << OP_1;
      tx.vin[0].nSequence = chainActive.Tip()->nHeight + 1; // txFirst[0] is the 2nd block
      prevheights[0] = baseheight + 1;
      tx.vout.resize(1);
      tx.vout[0].nValue = BLOCKSUBSIDY-HIGHFEE;
      tx.vout[0].scriptPubKey = CScript() << OP_1;
      tx.nLockTime = 0;
      hash = tx.GetHash();
      mempool.addUnchecked(hash, entry.Fee(HIGHFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
      BOOST_CHECK(CheckFinalTx(tx, flags)); // Locktime passes
      BOOST_CHECK(!TestSequenceLocks(tx, flags)); // Sequence locks fail
      BOOST_CHECK(SequenceLocks(tx, flags, &prevheights, CreateBlockIndex(chainActive.Tip()->nHeight + 2))); // Sequence locks pass on 2nd block
  
      // relative time locked
      tx.vin[0].prevout.hash = txFirst[1]->GetHash();
      tx.vin[0].nSequence = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | (((chainActive.Tip()->GetMedianTimePast()+1-chainActive[1]->GetMedianTimePast()) >> CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) + 1); // txFirst[1] is the 3rd block
      prevheights[0] = baseheight + 2;
      hash = tx.GetHash();
      mempool.addUnchecked(hash, entry.Time(GetTime()).FromTx(tx));
      BOOST_CHECK(CheckFinalTx(tx, flags)); // Locktime passes
      BOOST_CHECK(!TestSequenceLocks(tx, flags)); // Sequence locks fail
  
      for (int i = 0; i < CBlockIndex::nMedianTimeSpan; i++)
          chainActive.Tip()->GetAncestor(chainActive.Tip()->nHeight - i)->nTime += 512; //Trick the MedianTimePast
      BOOST_CHECK(SequenceLocks(tx, flags, &prevheights, CreateBlockIndex(chainActive.Tip()->nHeight + 1))); // Sequence locks pass 512 seconds later
      for (int i = 0; i < CBlockIndex::nMedianTimeSpan; i++)
          chainActive.Tip()->GetAncestor(chainActive.Tip()->nHeight - i)->nTime -= 512; //undo tricked MTP
  
      // absolute height locked
      tx.vin[0].prevout.hash = txFirst[2]->GetHash();
      tx.vin[0].nSequence = CTxIn::SEQUENCE_FINAL - 1;
      prevheights[0] = baseheight + 3;
      tx.nLockTime = chainActive.Tip()->nHeight + 1;
      hash = tx.GetHash();
      mempool.addUnchecked(hash, entry.Time(GetTime()).FromTx(tx));
      BOOST_CHECK(!CheckFinalTx(tx, flags)); // Locktime fails
      BOOST_CHECK(TestSequenceLocks(tx, flags)); // Sequence locks pass
      BOOST_CHECK(IsFinalTx(tx, chainActive.Tip()->nHeight + 2, chainActive.Tip()->GetMedianTimePast())); // Locktime passes on 2nd block
  
      // absolute time locked
      tx.vin[0].prevout.hash = txFirst[3]->GetHash();
      tx.nLockTime = chainActive.Tip()->GetMedianTimePast();
      prevheights.resize(1);
      prevheights[0] = baseheight + 4;
      hash = tx.GetHash();
      mempool.addUnchecked(hash, entry.Time(GetTime()).FromTx(tx));
      BOOST_CHECK(!CheckFinalTx(tx, flags)); // Locktime fails
      BOOST_CHECK(TestSequenceLocks(tx, flags)); // Sequence locks pass
      BOOST_CHECK(IsFinalTx(tx, chainActive.Tip()->nHeight + 2, chainActive.Tip()->GetMedianTimePast() + 1)); // Locktime passes 1 second later
  
      // mempool-dependent transactions (not added)
      tx.vin[0].prevout.hash = hash;
      prevheights[0] = chainActive.Tip()->nHeight + 1;
      tx.nLockTime = 0;
      tx.vin[0].nSequence = 0;
      BOOST_CHECK(CheckFinalTx(tx, flags)); // Locktime passes
      BOOST_CHECK(TestSequenceLocks(tx, flags)); // Sequence locks pass
      tx.vin[0].nSequence = 1;
      BOOST_CHECK(!TestSequenceLocks(tx, flags)); // Sequence locks fail
      tx.vin[0].nSequence = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG;
      BOOST_CHECK(TestSequenceLocks(tx, flags)); // Sequence locks pass
      tx.vin[0].nSequence = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | 1;
      BOOST_CHECK(!TestSequenceLocks(tx, flags)); // Sequence locks fail
  
      BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey));
  
      // None of the of the absolute height/time locked tx should have made
      // it into the template because we still check IsFinalTx in CreateNewBlock,
      // but relative locked txs will if inconsistently added to mempool.
      // For now these will still generate a valid template until BIP68 soft fork
      BOOST_CHECK_EQUAL(pblocktemplate->block.vtx.size(), 3);
      // However if we advance height by 1 and time by 512, all of them should be mined
      for (int i = 0; i < CBlockIndex::nMedianTimeSpan; i++)
          chainActive.Tip()->GetAncestor(chainActive.Tip()->nHeight - i)->nTime += 512; //Trick the MedianTimePast
  
      } // unlock cs_main while calling createAndProcessEmptyBlock
  
      // Mine an empty block
      createAndProcessEmptyBlock();
  
      LOCK(cs_main);
  
      SetMockTime(chainActive.Tip()->GetMedianTimePast() + 1);
  
      BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey));
      BOOST_CHECK_EQUAL(pblocktemplate->block.vtx.size(), 5);
  
      CValidationState state;
      InvalidateBlock(state, chainparams, chainActive.Tip());
  
      SetMockTime(0);
      mempool.clear();
  
      TestPackageSelection(chainparams, scriptPubKey, txFirst);
  
      fCheckpointsEnabled = true;
  }
  
  BOOST_AUTO_TEST_SUITE_END()
  