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) 2011-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#include <test/util/setup_common.h>7#include <addrman.h>8#include <banman.h>9#include <chain.h>10#include <chainparams.h>11#include <coins.h>12#include <common/system.h>13#include <consensus/amount.h>14#include <consensus/consensus.h>15#include <consensus/validation.h>16#include <crypto/hex_base.h>17#include <dbwrapper.h>18#include <init.h>19#include <interfaces/chain.h>20#include <interfaces/mining.h>21#include <kernel/caches.h>22#include <kernel/context.h>23#include <key.h>24#include <logging.h>25#include <net.h>26#include <net_processing.h>27#include <netbase.h>28#include <netgroup.h>29#include <node/blockstorage.h>30#include <node/chainstate.h>31#include <node/context.h>32#include <node/kernel_notifications.h>33#include <node/miner.h>34#include <node/mining_args.h>35#include <node/mining_types.h>36#include <node/peerman_args.h>37#include <node/warnings.h>38#include <noui.h>39#include <policy/feerate.h>40#include <policy/policy.h>41#include <pow.h>42#include <primitives/block.h>43#include <primitives/transaction.h>44#include <random.h>45#include <rpc/register.h>46#include <rpc/server.h>47#include <scheduler.h>48#include <script/interpreter.h>49#include <script/script.h>50#include <script/sign.h>51#include <script/signingprovider.h>52#include <serialize.h>53#include <span.h>54#include <streams.h>55#include <sync.h>56#include <test/util/coverage.h>57#include <test/util/net.h>58#include <test/util/random.h>59#include <test/util/txmempool.h>60#include <tinyformat.h>61#include <txmempool.h>62#include <uint256.h>63#include <util/chaintype.h>64#include <util/check.h>65#include <util/fs.h>66#include <util/fs_helpers.h>67#include <util/rbf.h>68#include <util/result.h>69#include <util/signalinterrupt.h>70#include <util/strencodings.h>71#include <util/task_runner.h>72#include <util/thread.h>73#include <util/threadnames.h>74#include <util/time.h>75#include <util/translation.h>76#include <util/vector.h>77#include <validation.h>78#include <validationinterface.h>80#include <algorithm>81#include <array>82#include <atomic>83#include <cstdlib>84#include <deque>85#include <functional>86#include <future>87#include <iostream>88#include <iterator>89#include <map>90#include <numeric>91#include <span>92#include <stdexcept>93#include <string_view>94#include <thread>95#include <tuple>96#include <utility>98using namespace util::hex_literals;99using node::ApplyArgsManOptions;100using node::BlockManager;101using node::KernelNotifications;102using node::LoadChainstate;103using node::RegenerateCommitments;104using node::VerifyLoadedChainstate;106const TranslateFn G_TRANSLATION_FUN{nullptr};108constexpr inline auto TEST_DIR_PATH_ELEMENT{"test_common bitcoin"}; // Includes a space to catch possible path escape issues.109/** Random context to get unique temp data dirs. Separate from m_rng, which can be seeded from a const env var */110static FastRandomContext g_rng_temp_path;111static const bool g_rng_temp_path_init{[] {112// Must be initialized before any SeedRandomForTest113Assert(!g_used_g_prng);114(void)g_rng_temp_path.rand64();115g_used_g_prng = false;116ResetCoverageCounters(); // The seed strengthen in SeedStartup is not deterministic, so exclude it from coverage counts117return true;118}()};120struct NetworkSetup121{122NetworkSetup()123{124Assert(SetupNetworking());125}126};127static NetworkSetup g_networksetup_instance;129void SetupCommonTestArgs(ArgsManager& argsman)130{131argsman.AddArg("-testdatadir", strprintf("Custom data directory (default: %s<random_string>)", fs::PathToString(fs::temp_directory_path() / TEST_DIR_PATH_ELEMENT / "")),132ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);133}135/** Test setup failure */136static void ExitFailure(std::string_view str_err)137{138std::cerr << str_err << std::endl;139exit(EXIT_FAILURE);140}142BasicTestingSetup::BasicTestingSetup(const ChainType chainType, TestOpts opts)143: m_args{}144{145if (!EnableFuzzDeterminism()) {146SeedRandomForTest(SeedRand::FIXED_SEED);147}149// Reset globals150fDiscover = true;151fListen = true;152SetRPCWarmupStarting();153g_reachable_nets.Reset();154ClearLocal();156m_node.shutdown_signal = &m_interrupt;157m_node.shutdown_request = [this]{ return m_interrupt(); };158m_node.args = &gArgs;159std::vector<const char*> arguments = Cat(160{161"dummy",162"-printtoconsole=0",163"-logsourcelocations",164"-logtimemicros",165"-logthreadnames",166"-loglevel=trace",167"-debug",168"-debugexclude=leveldb",169},170opts.extra_args);171if (G_TEST_COMMAND_LINE_ARGUMENTS) {172arguments = Cat(arguments, G_TEST_COMMAND_LINE_ARGUMENTS());173}174util::ThreadRename("test");175gArgs.ClearPathCache();176{177SetupServerArgs(*m_node.args);178SetupCommonTestArgs(*m_node.args);179std::string error;180if (!m_node.args->ParseParameters(arguments.size(), arguments.data(), error)) {181m_node.args->ClearArgs();182throw std::runtime_error{error};183}184}186const std::string test_name{G_TEST_GET_FULL_NAME ? G_TEST_GET_FULL_NAME() : ""};187if (!m_node.args->IsArgSet("-testdatadir")) {188// To avoid colliding with a leftover prior datadir, and to allow189// tests, such as the fuzz tests to run in several processes at the190// same time, add a random element to the path. Keep it small enough to191// avoid a MAX_PATH violation on Windows.192//193// When fuzzing with AFL++, use the shared memory ID for a deterministic194// path. This allows for cleanup of leftover directories from timed-out195// or crashed iterations, preventing accumulation of stale datadirs.196if (const char* shm_id = std::getenv("__AFL_SHM_ID"); shm_id && *shm_id) {197m_path_root = fs::temp_directory_path() / TEST_DIR_PATH_ELEMENT / test_name / shm_id;198fs::remove_all(m_path_root);199} else {200const auto rand{HexStr(g_rng_temp_path.randbytes(10))};201m_path_root = fs::temp_directory_path() / TEST_DIR_PATH_ELEMENT / test_name / rand;202}203TryCreateDirectories(m_path_root);204} else {205// Custom data directory206m_has_custom_datadir = true;207fs::path root_dir{m_node.args->GetPathArg("-testdatadir")};208if (root_dir.empty()) ExitFailure("-testdatadir argument is empty, please specify a path");210root_dir = fs::absolute(root_dir);211m_path_lock = root_dir / TEST_DIR_PATH_ELEMENT / fs::PathFromString(test_name);212m_path_root = m_path_lock / "datadir";214// Try to obtain the lock; if unsuccessful don't disturb the existing test.215TryCreateDirectories(m_path_lock);216if (util::LockDirectory(m_path_lock, ".lock", /*probe_only=*/false) != util::LockResult::Success) {217ExitFailure("Cannot obtain a lock on test data lock directory " + fs::PathToString(m_path_lock) + '\n' + "The test executable is probably already running.");218}220// Always start with a fresh data directory; this doesn't delete the .lock file located one level above.221fs::remove_all(m_path_root);222if (!TryCreateDirectories(m_path_root)) ExitFailure("Cannot create test data directory");224// Print the test directory name if custom.225std::cout << "Test directory (will not be deleted): " << m_path_root << std::endl;226}227m_args.ForceSetArg("-datadir", fs::PathToString(m_path_root));228gArgs.ForceSetArg("-datadir", fs::PathToString(m_path_root));230// Avoid non-loopback network traffic during tests.231gArgs.ForceSetArg("-dnsseed", "0"); // DNS queries are usually forwarded to upstream DNS servers.232gArgs.ForceSetArg("-natpmp", "0"); // NATPMP sends packets to the router.234SelectParams(chainType);235InitLogging(*m_node.args);236AppInitParameterInteraction(*m_node.args);237LogInstance().StartLogging();238m_node.warnings = std::make_unique<node::Warnings>();239m_node.kernel = std::make_unique<kernel::Context>();240m_node.ecc_context = std::make_unique<ECC_Context>();241SetupEnvironment();243m_node.chain = interfaces::MakeChain(m_node);244static bool noui_connected = false;245if (!noui_connected) {246noui_connect();247noui_connected = true;248}249}
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.