Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2015-present The Bitcoin Core developers2// Distributed under the MIT software license, see the accompanying3// file COPYING or http://www.opensource.org/licenses/mit-license.php.5#ifndef BITCOIN_TEST_UTIL_SETUP_COMMON_H6#define BITCOIN_TEST_UTIL_SETUP_COMMON_H8#include <common/args.h> // IWYU pragma: export9#include <consensus/amount.h>10#include <kernel/caches.h>11#include <key.h>12#include <node/caches.h>13#include <node/context.h> // IWYU pragma: export14#include <primitives/transaction.h>15#include <random.h>16#include <test/util/net.h>17#include <test/util/random.h>18#include <test/util/time.h>19#include <util/chaintype.h> // IWYU pragma: export20#include <util/fs.h>21#include <util/signalinterrupt.h>22#include <util/vector.h>24#include <cstddef>25#include <cstdint>26#include <functional>27#include <memory>28#include <optional>29#include <string>30#include <utility>31#include <vector>33class CFeeRate;35/** Retrieve the command line arguments. */36extern const std::function<std::vector<const char*>()> G_TEST_COMMAND_LINE_ARGUMENTS;38/** Retrieve the unit test name. */39extern const std::function<std::string()> G_TEST_GET_FULL_NAME;41inline constexpr CAmount CENT{1'000'000};43/** Register common test args. Shared across binaries that rely on the test framework. */44void SetupCommonTestArgs(ArgsManager& argsman);46struct TestOpts {47std::vector<const char*> extra_args{};48bool coins_db_in_memory{true};49bool block_tree_db_in_memory{true};50bool setup_net{true};51bool setup_validation_interface{true};52bool min_validation_cache{false}; // Equivalent of -maxsigcachebytes=053};55/** Basic testing setup.56* This just configures logging, data dir and chain parameters.57*/58struct BasicTestingSetup {59util::SignalInterrupt m_interrupt;60node::NodeContext m_node; // keep as first member to be destructed last62FastRandomContext m_rng;63/** Seed the global RNG state and m_rng for testing and log the seed value. This affects all randomness, except GetStrongRandBytes(). */64void SeedRandomForTest(SeedRand seed)65{66SeedRandomStateForTest(seed);67m_rng.Reseed(GetRandHash());68}70explicit BasicTestingSetup(ChainType chainType = ChainType::MAIN, TestOpts = {});71~BasicTestingSetup();73fs::path m_path_root;74fs::path m_path_lock;75bool m_has_custom_datadir{false};76/** @brief Test-specific arguments and settings.77*78* This member is intended to be the primary source of settings for code79* being tested by unit tests. It exists to make tests more self-contained80* and reduce reliance on global state.81*82* Usage guidelines:83* 1. Prefer using m_args where possible in test code.84* 2. If m_args is not accessible, use m_node.args as a fallback.85* 3. Avoid direct references to gArgs in test code.86*87* Note: Currently, m_node.args points to gArgs for backwards88* compatibility. In the future, it will point to m_args to further isolate89* test environments.90*91* @see https://github.com/bitcoin/bitcoin/issues/25055 for additional context.92*/93ArgsManager m_args;94};96/** Testing setup that performs all steps up until right before97* ChainstateManager gets initialized. Meant for testing ChainstateManager98* initialization behaviour.99*/100struct ChainTestingSetup : public BasicTestingSetup {101kernel::CacheSizes m_kernel_cache_sizes{node::CalculateCacheSizes(m_args).kernel};102bool m_coins_db_in_memory{true};103bool m_block_tree_db_in_memory{true};104std::function<void()> m_make_chainman{};106explicit ChainTestingSetup(ChainType chainType = ChainType::MAIN, TestOpts = {});107~ChainTestingSetup();109// Supplies a chainstate, if one is needed110void LoadVerifyActivateChainstate();111};113/** Testing setup that configures a complete environment.114*/115struct TestingSetup : public ChainTestingSetup {116explicit TestingSetup(117ChainType chainType = ChainType::MAIN,118TestOpts = {});119};121/** Identical to TestingSetup, but chain set to regtest */122struct RegTestingSetup : public TestingSetup {123RegTestingSetup()124: TestingSetup{ChainType::REGTEST} {}125};127/** Identical to TestingSetup, but chain set to testnet4 */128struct Testnet4Setup : public TestingSetup {129Testnet4Setup()130: TestingSetup{ChainType::TESTNET4} {}131};133class CBlock;134class CScript;136/**137* Testing fixture that pre-creates a 100-block REGTEST-mode block chain138*/139struct TestChain100Setup : public TestingSetup {140TestChain100Setup(141ChainType chain_type = ChainType::REGTEST,142TestOpts = {});144/**145* Create a new block with just given transactions, coinbase paying to146* scriptPubKey, and try to add it to the current chain.147*/148CBlock CreateAndProcessBlock(const std::vector<CMutableTransaction>& txns,149const CScript& scriptPubKey);151/**152* Create a new block with just given transactions, coinbase paying to153* scriptPubKey.154*/155CBlock CreateBlock(156const std::vector<CMutableTransaction>& txns,157const CScript& scriptPubKey);159//! Mine a series of new blocks on the active chain.160void mineBlocks(int num_blocks);162/**163* Create a transaction, optionally setting the fee based on the feerate.164* Note: The feerate may not be met exactly depending on whether the signatures can have different sizes.165*166* @param input_transactions The transactions to spend167* @param inputs Outpoints with which to construct transaction vin.168* @param input_height The height of the block that included the input transactions.169* @param input_signing_keys The keys to spend the input transactions.170* @param outputs Transaction vout.171* @param feerate The feerate the transaction should pay.172* @param fee_output The index of the output to take the fee from.173* @return The transaction and the fee it pays174*/175std::pair<CMutableTransaction, CAmount> CreateValidTransaction(const std::vector<CTransactionRef>& input_transactions,176const std::vector<COutPoint>& inputs,177int input_height,178const std::vector<CKey>& input_signing_keys,179const std::vector<CTxOut>& outputs,180const std::optional<CFeeRate>& feerate,181const std::optional<uint32_t>& fee_output);182/**183* Create a transaction and, optionally, submit to the mempool.184*185* @param input_transactions The transactions to spend186* @param inputs Outpoints with which to construct transaction vin.187* @param input_height The height of the block that included the input transaction(s).188* @param input_signing_keys The keys to spend inputs.189* @param outputs Transaction vout.190* @param submit Whether or not to submit to mempool191*/192CMutableTransaction CreateValidMempoolTransaction(const std::vector<CTransactionRef>& input_transactions,193const std::vector<COutPoint>& inputs,194int input_height,195const std::vector<CKey>& input_signing_keys,196const std::vector<CTxOut>& outputs,197bool submit = true);199/**200* Create a 1-in-1-out transaction and, optionally, submit to the mempool.201*202* @param input_transaction The transaction to spend203* @param input_vout The vout to spend from the input_transaction204* @param input_height The height of the block that included the input_transaction205* @param input_signing_key The key to spend the input_transaction206* @param output_destination Where to send the output207* @param output_amount How much to send208* @param submit Whether or not to submit to mempool209*/210CMutableTransaction CreateValidMempoolTransaction(CTransactionRef input_transaction,211uint32_t input_vout,212int input_height,213CKey input_signing_key,214CScript output_destination,215CAmount output_amount = CAmount(1 * COIN),216bool submit = true);218/** Create transactions spending from m_coinbase_txns. These transactions will only spend coins219* that exist in the current chain, but may be premature coinbase spends, have missing220* signatures, or violate some other consensus rules. They should only be used for testing221* mempool consistency. All transactions will have some random number of inputs and outputs222* (between 1 and 24). Transactions may or may not be dependent upon each other; if dependencies223* exit, every parent will always be somewhere in the list before the child so each transaction224* can be submitted in the same order they appear in the list.225* @param[in] submit When true, submit transactions to the mempool.226* When false, return them but don't submit them.227* @returns A vector of transactions that can be submitted to the mempool.228*/229std::vector<CTransactionRef> PopulateMempool(FastRandomContext& det_rand, size_t num_transactions, bool submit);231FakeNodeClock m_clock{std::chrono::seconds{1598887952}}; // 2020-08-31, arbitrary232std::vector<CTransactionRef> m_coinbase_txns; // For convenience, coinbase transactions233CKey coinbaseKey; // private/public key needed to spend coinbase transactions234};236/**237* Make a test setup that has disk access to the debug.log file disabled. Can238* be used in "hot loops", for example fuzzing or benchmarking.239*/240template <class T = const BasicTestingSetup>241std::unique_ptr<T> MakeNoLogFileContext(const ChainType chain_type = ChainType::REGTEST, TestOpts opts = {})242{243opts.extra_args = Cat(244{245"-nodebuglogfile",246"-nodebug",247},248opts.extra_args);250return std::make_unique<T>(chain_type, opts);
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.