You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

validation_block_tests.cpp 6.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. // Copyright (c) 2018 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. #include <boost/test/unit_test.hpp>
  5. #include <chainparams.h>
  6. #include <consensus/merkle.h>
  7. #include <consensus/validation.h>
  8. #include <miner.h>
  9. #include <pow.h>
  10. #include <random.h>
  11. #include <test/test_bitcoin.h>
  12. #include <validation.h>
  13. #include <validationinterface.h>
  14. struct RegtestingSetup : public TestingSetup {
  15. RegtestingSetup() : TestingSetup(CBaseChainParams::REGTEST) {}
  16. };
  17. BOOST_FIXTURE_TEST_SUITE(validation_block_tests, RegtestingSetup)
  18. struct TestSubscriber : public CValidationInterface {
  19. uint256 m_expected_tip;
  20. TestSubscriber(uint256 tip) : m_expected_tip(tip) {}
  21. void UpdatedBlockTip(const CBlockIndex* pindexNew, const CBlockIndex* pindexFork, bool fInitialDownload)
  22. {
  23. BOOST_CHECK_EQUAL(m_expected_tip, pindexNew->GetBlockHash());
  24. }
  25. void BlockConnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex, const std::vector<CTransactionRef>& txnConflicted)
  26. {
  27. BOOST_CHECK_EQUAL(m_expected_tip, block->hashPrevBlock);
  28. BOOST_CHECK_EQUAL(m_expected_tip, pindex->pprev->GetBlockHash());
  29. m_expected_tip = block->GetHash();
  30. }
  31. void BlockDisconnected(const std::shared_ptr<const CBlock>& block)
  32. {
  33. BOOST_CHECK_EQUAL(m_expected_tip, block->GetHash());
  34. m_expected_tip = block->hashPrevBlock;
  35. }
  36. };
  37. std::shared_ptr<CBlock> Block(const uint256& prev_hash)
  38. {
  39. static int i = 0;
  40. static uint64_t time = Params().GenesisBlock().nTime;
  41. CScript pubKey;
  42. pubKey << i++ << OP_TRUE;
  43. auto ptemplate = BlockAssembler(Params()).CreateNewBlock(pubKey, false);
  44. auto pblock = std::make_shared<CBlock>(ptemplate->block);
  45. pblock->hashPrevBlock = prev_hash;
  46. pblock->nTime = ++time;
  47. CMutableTransaction txCoinbase(*pblock->vtx[0]);
  48. txCoinbase.vout.resize(1);
  49. txCoinbase.vin[0].scriptWitness.SetNull();
  50. pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase));
  51. return pblock;
  52. }
  53. std::shared_ptr<CBlock> FinalizeBlock(std::shared_ptr<CBlock> pblock)
  54. {
  55. pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
  56. while (!CheckProofOfWork(pblock->GetHash(), pblock->nBits, Params().GetConsensus())) {
  57. ++(pblock->nNonce);
  58. }
  59. return pblock;
  60. }
  61. // construct a valid block
  62. const std::shared_ptr<const CBlock> GoodBlock(const uint256& prev_hash)
  63. {
  64. return FinalizeBlock(Block(prev_hash));
  65. }
  66. // construct an invalid block (but with a valid header)
  67. const std::shared_ptr<const CBlock> BadBlock(const uint256& prev_hash)
  68. {
  69. auto pblock = Block(prev_hash);
  70. CMutableTransaction coinbase_spend;
  71. coinbase_spend.vin.push_back(CTxIn(COutPoint(pblock->vtx[0]->GetHash(), 0), CScript(), 0));
  72. coinbase_spend.vout.push_back(pblock->vtx[0]->vout[0]);
  73. CTransactionRef tx = MakeTransactionRef(coinbase_spend);
  74. pblock->vtx.push_back(tx);
  75. auto ret = FinalizeBlock(pblock);
  76. return ret;
  77. }
  78. void BuildChain(const uint256& root, int height, const unsigned int invalid_rate, const unsigned int branch_rate, const unsigned int max_size, std::vector<std::shared_ptr<const CBlock>>& blocks)
  79. {
  80. if (height <= 0 || blocks.size() >= max_size) return;
  81. bool gen_invalid = GetRand(100) < invalid_rate;
  82. bool gen_fork = GetRand(100) < branch_rate;
  83. const std::shared_ptr<const CBlock> pblock = gen_invalid ? BadBlock(root) : GoodBlock(root);
  84. blocks.push_back(pblock);
  85. if (!gen_invalid) {
  86. BuildChain(pblock->GetHash(), height - 1, invalid_rate, branch_rate, max_size, blocks);
  87. }
  88. if (gen_fork) {
  89. blocks.push_back(GoodBlock(root));
  90. BuildChain(blocks.back()->GetHash(), height - 1, invalid_rate, branch_rate, max_size, blocks);
  91. }
  92. }
  93. BOOST_AUTO_TEST_CASE(processnewblock_signals_ordering)
  94. {
  95. // build a large-ish chain that's likely to have some forks
  96. std::vector<std::shared_ptr<const CBlock>> blocks;
  97. while (blocks.size() < 50) {
  98. blocks.clear();
  99. BuildChain(Params().GenesisBlock().GetHash(), 100, 15, 10, 500, blocks);
  100. }
  101. bool ignored;
  102. CValidationState state;
  103. std::vector<CBlockHeader> headers;
  104. std::transform(blocks.begin(), blocks.end(), std::back_inserter(headers), [](std::shared_ptr<const CBlock> b) { return b->GetBlockHeader(); });
  105. // Process all the headers so we understand the toplogy of the chain
  106. BOOST_CHECK(ProcessNewBlockHeaders(headers, state, Params()));
  107. // Connect the genesis block and drain any outstanding events
  108. ProcessNewBlock(Params(), std::make_shared<CBlock>(Params().GenesisBlock()), true, &ignored);
  109. SyncWithValidationInterfaceQueue();
  110. // subscribe to events (this subscriber will validate event ordering)
  111. const CBlockIndex* initial_tip = nullptr;
  112. {
  113. LOCK(cs_main);
  114. initial_tip = chainActive.Tip();
  115. }
  116. TestSubscriber sub(initial_tip->GetBlockHash());
  117. RegisterValidationInterface(&sub);
  118. // create a bunch of threads that repeatedly process a block generated above at random
  119. // this will create parallelism and randomness inside validation - the ValidationInterface
  120. // will subscribe to events generated during block validation and assert on ordering invariance
  121. boost::thread_group threads;
  122. for (int i = 0; i < 10; i++) {
  123. threads.create_thread([&blocks]() {
  124. bool ignored;
  125. for (int i = 0; i < 1000; i++) {
  126. auto block = blocks[GetRand(blocks.size() - 1)];
  127. ProcessNewBlock(Params(), block, true, &ignored);
  128. }
  129. // to make sure that eventually we process the full chain - do it here
  130. for (auto block : blocks) {
  131. if (block->vtx.size() == 1) {
  132. bool processed = ProcessNewBlock(Params(), block, true, &ignored);
  133. assert(processed);
  134. }
  135. }
  136. });
  137. }
  138. threads.join_all();
  139. while (GetMainSignals().CallbacksPending() > 0) {
  140. MilliSleep(100);
  141. }
  142. UnregisterValidationInterface(&sub);
  143. BOOST_CHECK_EQUAL(sub.m_expected_tip, chainActive.Tip()->GetBlockHash());
  144. }
  145. BOOST_AUTO_TEST_SUITE_END()