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.

test_bitcoin.cpp 5.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. // Copyright (c) 2011-2016 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 "test_bitcoin.h"
  5. #include "chainparams.h"
  6. #include "consensus/consensus.h"
  7. #include "consensus/validation.h"
  8. #include "crypto/sha256.h"
  9. #include "fs.h"
  10. #include "key.h"
  11. #include "validation.h"
  12. #include "miner.h"
  13. #include "net_processing.h"
  14. #include "pubkey.h"
  15. #include "random.h"
  16. #include "txdb.h"
  17. #include "txmempool.h"
  18. #include "ui_interface.h"
  19. #include "rpc/server.h"
  20. #include "rpc/register.h"
  21. #include "script/sigcache.h"
  22. #include <memory>
  23. void CConnmanTest::AddNode(CNode& node)
  24. {
  25. LOCK(g_connman->cs_vNodes);
  26. g_connman->vNodes.push_back(&node);
  27. }
  28. void CConnmanTest::ClearNodes()
  29. {
  30. LOCK(g_connman->cs_vNodes);
  31. g_connman->vNodes.clear();
  32. }
  33. uint256 insecure_rand_seed = GetRandHash();
  34. FastRandomContext insecure_rand_ctx(insecure_rand_seed);
  35. extern bool fPrintToConsole;
  36. extern void noui_connect();
  37. BasicTestingSetup::BasicTestingSetup(const std::string& chainName)
  38. {
  39. SHA256AutoDetect();
  40. RandomInit();
  41. ECC_Start();
  42. SetupEnvironment();
  43. SetupNetworking();
  44. InitSignatureCache();
  45. InitScriptExecutionCache();
  46. fPrintToDebugLog = false; // don't want to write to debug.log file
  47. fCheckBlockIndex = true;
  48. SelectParams(chainName);
  49. noui_connect();
  50. }
  51. BasicTestingSetup::~BasicTestingSetup()
  52. {
  53. ECC_Stop();
  54. }
  55. TestingSetup::TestingSetup(const std::string& chainName) : BasicTestingSetup(chainName)
  56. {
  57. const CChainParams& chainparams = Params();
  58. // Ideally we'd move all the RPC tests to the functional testing framework
  59. // instead of unit tests, but for now we need these here.
  60. RegisterAllCoreRPCCommands(tableRPC);
  61. ClearDatadirCache();
  62. pathTemp = fs::temp_directory_path() / strprintf("test_bitcoin_%lu_%i", (unsigned long)GetTime(), (int)(InsecureRandRange(100000)));
  63. fs::create_directories(pathTemp);
  64. gArgs.ForceSetArg("-datadir", pathTemp.string());
  65. // Note that because we don't bother running a scheduler thread here,
  66. // callbacks via CValidationInterface are unreliable, but that's OK,
  67. // our unit tests aren't testing multiple parts of the code at once.
  68. GetMainSignals().RegisterBackgroundSignalScheduler(scheduler);
  69. mempool.setSanityCheck(1.0);
  70. pblocktree = new CBlockTreeDB(1 << 20, true);
  71. pcoinsdbview = new CCoinsViewDB(1 << 23, true);
  72. pcoinsTip = new CCoinsViewCache(pcoinsdbview);
  73. if (!LoadGenesisBlock(chainparams)) {
  74. throw std::runtime_error("LoadGenesisBlock failed.");
  75. }
  76. {
  77. CValidationState state;
  78. if (!ActivateBestChain(state, chainparams)) {
  79. throw std::runtime_error("ActivateBestChain failed.");
  80. }
  81. }
  82. nScriptCheckThreads = 3;
  83. for (int i=0; i < nScriptCheckThreads-1; i++)
  84. threadGroup.create_thread(&ThreadScriptCheck);
  85. g_connman = std::unique_ptr<CConnman>(new CConnman(0x1337, 0x1337)); // Deterministic randomness for tests.
  86. connman = g_connman.get();
  87. peerLogic.reset(new PeerLogicValidation(connman, scheduler));
  88. }
  89. TestingSetup::~TestingSetup()
  90. {
  91. threadGroup.interrupt_all();
  92. threadGroup.join_all();
  93. GetMainSignals().FlushBackgroundCallbacks();
  94. GetMainSignals().UnregisterBackgroundSignalScheduler();
  95. g_connman.reset();
  96. peerLogic.reset();
  97. UnloadBlockIndex();
  98. delete pcoinsTip;
  99. delete pcoinsdbview;
  100. delete pblocktree;
  101. fs::remove_all(pathTemp);
  102. }
  103. TestChain100Setup::TestChain100Setup() : TestingSetup(CBaseChainParams::REGTEST)
  104. {
  105. // Generate a 100-block chain:
  106. coinbaseKey.MakeNewKey(true);
  107. CScript scriptPubKey = CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG;
  108. for (int i = 0; i < COINBASE_MATURITY; i++)
  109. {
  110. std::vector<CMutableTransaction> noTxns;
  111. CBlock b = CreateAndProcessBlock(noTxns, scriptPubKey);
  112. coinbaseTxns.push_back(*b.vtx[0]);
  113. }
  114. }
  115. //
  116. // Create a new block with just given transactions, coinbase paying to
  117. // scriptPubKey, and try to add it to the current chain.
  118. //
  119. CBlock
  120. TestChain100Setup::CreateAndProcessBlock(const std::vector<CMutableTransaction>& txns, const CScript& scriptPubKey)
  121. {
  122. const CChainParams& chainparams = Params();
  123. std::unique_ptr<CBlockTemplate> pblocktemplate = BlockAssembler(chainparams).CreateNewBlock(scriptPubKey);
  124. CBlock& block = pblocktemplate->block;
  125. // Replace mempool-selected txns with just coinbase plus passed-in txns:
  126. block.vtx.resize(1);
  127. for (const CMutableTransaction& tx : txns)
  128. block.vtx.push_back(MakeTransactionRef(tx));
  129. // IncrementExtraNonce creates a valid coinbase and merkleRoot
  130. unsigned int extraNonce = 0;
  131. IncrementExtraNonce(&block, chainActive.Tip(), extraNonce);
  132. while (!CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus())) ++block.nNonce;
  133. std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(block);
  134. ProcessNewBlock(chainparams, shared_pblock, true, nullptr);
  135. CBlock result = block;
  136. return result;
  137. }
  138. TestChain100Setup::~TestChain100Setup()
  139. {
  140. }
  141. CTxMemPoolEntry TestMemPoolEntryHelper::FromTx(const CMutableTransaction &tx) {
  142. CTransaction txn(tx);
  143. return FromTx(txn);
  144. }
  145. CTxMemPoolEntry TestMemPoolEntryHelper::FromTx(const CTransaction &txn) {
  146. return CTxMemPoolEntry(MakeTransactionRef(txn), nFee, nTime, nHeight,
  147. spendsCoinbase, sigOpCost, lp);
  148. }