diff options
Diffstat (limited to 'src/test/util')
-rw-r--r-- | src/test/util/CMakeLists.txt | 29 | ||||
-rw-r--r-- | src/test/util/cluster_linearize.h | 44 | ||||
-rw-r--r-- | src/test/util/coins.cpp | 6 | ||||
-rw-r--r-- | src/test/util/coins.h | 3 | ||||
-rw-r--r-- | src/test/util/json.cpp | 8 | ||||
-rw-r--r-- | src/test/util/json.h | 8 | ||||
-rw-r--r-- | src/test/util/random.cpp | 24 | ||||
-rw-r--r-- | src/test/util/random.h | 56 | ||||
-rw-r--r-- | src/test/util/setup_common.cpp | 105 | ||||
-rw-r--r-- | src/test/util/setup_common.h | 44 | ||||
-rw-r--r-- | src/test/util/transaction_utils.cpp | 21 | ||||
-rw-r--r-- | src/test/util/transaction_utils.h | 4 |
12 files changed, 203 insertions, 149 deletions
diff --git a/src/test/util/CMakeLists.txt b/src/test/util/CMakeLists.txt new file mode 100644 index 0000000000..5d88d1da3e --- /dev/null +++ b/src/test/util/CMakeLists.txt @@ -0,0 +1,29 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +add_library(test_util STATIC EXCLUDE_FROM_ALL + blockfilter.cpp + coins.cpp + index.cpp + json.cpp + logging.cpp + mining.cpp + net.cpp + random.cpp + script.cpp + setup_common.cpp + str.cpp + transaction_utils.cpp + txmempool.cpp + validation.cpp + $<$<BOOL:${ENABLE_WALLET}>:${PROJECT_SOURCE_DIR}/src/wallet/test/util.cpp> +) + +target_link_libraries(test_util + PRIVATE + core_interface + Boost::headers + PUBLIC + univalue +) diff --git a/src/test/util/cluster_linearize.h b/src/test/util/cluster_linearize.h index 508a08133c..b86ebcd78b 100644 --- a/src/test/util/cluster_linearize.h +++ b/src/test/util/cluster_linearize.h @@ -102,7 +102,7 @@ bool IsAcyclic(const DepGraph<SetType>& depgraph) noexcept struct DepGraphFormatter { /** Convert x>=0 to 2x (even), x<0 to -2x-1 (odd). */ - static uint64_t SignedToUnsigned(int64_t x) noexcept + [[maybe_unused]] static uint64_t SignedToUnsigned(int64_t x) noexcept { if (x < 0) { return 2 * uint64_t(-(x + 1)) + 1; @@ -112,7 +112,7 @@ struct DepGraphFormatter } /** Convert even x to x/2 (>=0), odd x to -(x/2)-1 (<0). */ - static int64_t UnsignedToSigned(uint64_t x) noexcept + [[maybe_unused]] static int64_t UnsignedToSigned(uint64_t x) noexcept { if (x & 1) { return -int64_t(x / 2) - 1; @@ -155,7 +155,7 @@ struct DepGraphFormatter // Ignore transactions which are already known to be ancestors. if (depgraph.Descendants(dep_idx).Overlaps(written_parents)) continue; if (depgraph.Ancestors(idx)[dep_idx]) { - // When an actual parent is encounted, encode how many non-parents were skipped + // When an actual parent is encountered, encode how many non-parents were skipped // before it. s << VARINT(diff); diff = 0; @@ -186,7 +186,7 @@ struct DepGraphFormatter /** The dependency graph which we deserialize into first, with transactions in * topological serialization order, not original cluster order. */ DepGraph<SetType> topo_depgraph; - /** Mapping from cluster order to serialization order, used later to reconstruct the + /** Mapping from serialization order to cluster order, used later to reconstruct the * cluster order. */ std::vector<ClusterIndex> reordering; @@ -205,9 +205,9 @@ struct DepGraphFormatter coded_fee &= 0xFFFFFFFFFFFFF; // Enough for fee between -21M...21M BTC. static_assert(0xFFFFFFFFFFFFF > uint64_t{2} * 21000000 * 100000000); auto fee = UnsignedToSigned(coded_fee); - // Extend topo_depgraph with the new transaction (at the end). + // Extend topo_depgraph with the new transaction (preliminarily at the end). auto topo_idx = topo_depgraph.AddTransaction({fee, size}); - reordering.push_back(topo_idx); + reordering.push_back(reordering.size()); // Read dependency information. uint64_t diff = 0; //!< How many potential parents we have to skip. s >> VARINT(diff); @@ -226,31 +226,23 @@ struct DepGraphFormatter --diff; } } - // If we reach this point, we can interpret the remaining skip value as how far from the - // end of reordering topo_idx should be placed (wrapping around), so move it to its - // correct location. The preliminary reordering.push_back(topo_idx) above was to make - // sure that if a deserialization exception occurs, topo_idx still appears somewhere. + // If we reach this point, we can interpret the remaining skip value as how far + // from the end of reordering the new transaction should be placed (wrapping + // around), so remove the preliminary position it was put in above (which was to + // make sure that if a deserialization exception occurs, the new transaction still + // has some entry in reordering). reordering.pop_back(); - reordering.insert(reordering.end() - (diff % (reordering.size() + 1)), topo_idx); + ClusterIndex insert_distance = diff % (reordering.size() + 1); + // And then update reordering to reflect this new transaction's insertion. + for (auto& pos : reordering) { + pos += (pos >= reordering.size() - insert_distance); + } + reordering.push_back(reordering.size() - insert_distance); } } catch (const std::ios_base::failure&) {} // Construct the original cluster order depgraph. - depgraph = {}; - // Add transactions to depgraph in the original cluster order. - for (auto topo_idx : reordering) { - depgraph.AddTransaction(topo_depgraph.FeeRate(topo_idx)); - } - // Translate dependencies from topological to cluster order. - for (ClusterIndex idx = 0; idx < reordering.size(); ++idx) { - ClusterIndex topo_idx = reordering[idx]; - for (ClusterIndex dep_idx = 0; dep_idx < reordering.size(); ++dep_idx) { - ClusterIndex dep_topo_idx = reordering[dep_idx]; - if (topo_depgraph.Ancestors(topo_idx)[dep_topo_idx]) { - depgraph.AddDependency(dep_idx, idx); - } - } - } + depgraph = DepGraph(topo_depgraph, reordering); } }; diff --git a/src/test/util/coins.cpp b/src/test/util/coins.cpp index 742dbc04d1..7e10c7c58d 100644 --- a/src/test/util/coins.cpp +++ b/src/test/util/coins.cpp @@ -13,12 +13,12 @@ #include <stdint.h> #include <utility> -COutPoint AddTestCoin(CCoinsViewCache& coins_view) +COutPoint AddTestCoin(FastRandomContext& rng, CCoinsViewCache& coins_view) { Coin new_coin; - COutPoint outpoint{Txid::FromUint256(InsecureRand256()), /*nIn=*/0}; + COutPoint outpoint{Txid::FromUint256(rng.rand256()), /*nIn=*/0}; new_coin.nHeight = 1; - new_coin.out.nValue = InsecureRandMoneyAmount(); + new_coin.out.nValue = RandMoney(rng); new_coin.out.scriptPubKey.assign(uint32_t{56}, 1); coins_view.AddCoin(outpoint, std::move(new_coin), /*possible_overwrite=*/false); diff --git a/src/test/util/coins.h b/src/test/util/coins.h index 5e6f4293ae..89a9e7b329 100644 --- a/src/test/util/coins.h +++ b/src/test/util/coins.h @@ -8,12 +8,13 @@ #include <primitives/transaction.h> class CCoinsViewCache; +class FastRandomContext; /** * Create a Coin with DynamicMemoryUsage of 80 bytes and add it to the given view. * @param[in,out] coins_view The coins view cache to add the new coin to. * @returns the COutPoint of the created coin. */ -COutPoint AddTestCoin(CCoinsViewCache& coins_view); +COutPoint AddTestCoin(FastRandomContext& rng, CCoinsViewCache& coins_view); #endif // BITCOIN_TEST_UTIL_COINS_H diff --git a/src/test/util/json.cpp b/src/test/util/json.cpp index ad3c346c84..46a4a9f9a1 100644 --- a/src/test/util/json.cpp +++ b/src/test/util/json.cpp @@ -1,15 +1,15 @@ -// Copyright (c) 2023 The Bitcoin Core developers +// Copyright (c) 2023-present 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 <test/util/json.h> -#include <string> +#include <univalue.h> #include <util/check.h> -#include <univalue.h> +#include <string_view> -UniValue read_json(const std::string& jsondata) +UniValue read_json(std::string_view jsondata) { UniValue v; Assert(v.read(jsondata) && v.isArray()); diff --git a/src/test/util/json.h b/src/test/util/json.h index 5b1026762e..f6f4e6ab71 100644 --- a/src/test/util/json.h +++ b/src/test/util/json.h @@ -1,14 +1,14 @@ -// Copyright (c) 2023 The Bitcoin Core developers +// Copyright (c) 2023-present The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_TEST_UTIL_JSON_H #define BITCOIN_TEST_UTIL_JSON_H -#include <string> - #include <univalue.h> -UniValue read_json(const std::string& jsondata); +#include <string_view> + +UniValue read_json(std::string_view jsondata); #endif // BITCOIN_TEST_UTIL_JSON_H diff --git a/src/test/util/random.cpp b/src/test/util/random.cpp index 47d03055e2..32d785e45d 100644 --- a/src/test/util/random.cpp +++ b/src/test/util/random.cpp @@ -7,17 +7,16 @@ #include <logging.h> #include <random.h> #include <uint256.h> +#include <util/check.h> #include <cstdlib> -#include <string> - -FastRandomContext g_insecure_rand_ctx; +#include <iostream> extern void MakeRandDeterministicDANGEROUS(const uint256& seed) noexcept; -void SeedRandomForTest(SeedRand seedtype) +void SeedRandomStateForTest(SeedRand seedtype) { - static const std::string RANDOM_CTX_SEED{"RANDOM_CTX_SEED"}; + constexpr auto RANDOM_CTX_SEED{"RANDOM_CTX_SEED"}; // Do this once, on the first call, regardless of seedtype, because once // MakeRandDeterministicDANGEROUS is called, the output of GetRandHash is @@ -25,14 +24,19 @@ void SeedRandomForTest(SeedRand seedtype) // process. static const uint256 ctx_seed = []() { // If RANDOM_CTX_SEED is set, use that as seed. - const char* num = std::getenv(RANDOM_CTX_SEED.c_str()); - if (num) return uint256S(num); + if (const char* num{std::getenv(RANDOM_CTX_SEED)}) { + if (auto num_parsed{uint256::FromUserHex(num)}) { + return *num_parsed; + } else { + std::cerr << RANDOM_CTX_SEED << " must consist of up to " << uint256::size() * 2 << " hex digits (\"0x\" prefix allowed), it was set to: '" << num << "'.\n"; + std::abort(); + } + } // Otherwise use a (truly) random value. return GetRandHash(); }(); - const uint256& seed{seedtype == SeedRand::SEED ? ctx_seed : uint256::ZERO}; - LogPrintf("%s: Setting random seed for current tests to %s=%s\n", __func__, RANDOM_CTX_SEED, seed.GetHex()); + const uint256& seed{seedtype == SeedRand::FIXED_SEED ? ctx_seed : uint256::ZERO}; + LogInfo("Setting random seed for current tests to %s=%s\n", RANDOM_CTX_SEED, seed.GetHex()); MakeRandDeterministicDANGEROUS(seed); - g_insecure_rand_ctx.Reseed(GetRandHash()); } diff --git a/src/test/util/random.h b/src/test/util/random.h index 09a475f8b3..441150e666 100644 --- a/src/test/util/random.h +++ b/src/test/util/random.h @@ -1,4 +1,4 @@ -// Copyright (c) 2023 The Bitcoin Core developers +// Copyright (c) 2023-present The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. @@ -11,50 +11,26 @@ #include <cstdint> -/** - * This global and the helpers that use it are not thread-safe. - * - * If thread-safety is needed, a per-thread instance could be - * used in the multi-threaded test. - */ -extern FastRandomContext g_insecure_rand_ctx; - enum class SeedRand { - ZEROS, //!< Seed with a compile time constant of zeros - SEED, //!< Use (and report) random seed from environment, or a (truly) random one. + /** + * Seed with a compile time constant of zeros. + */ + ZEROS, + /** + * Seed with a fixed value that never changes over the lifetime of this + * process. The seed is read from the RANDOM_CTX_SEED environment variable + * if set, otherwise generated randomly once, saved, and reused. + */ + FIXED_SEED, }; -/** Seed the RNG for testing. This affects all randomness, except GetStrongRandBytes(). */ -void SeedRandomForTest(SeedRand seed = SeedRand::SEED); - -static inline uint32_t InsecureRand32() -{ - return g_insecure_rand_ctx.rand32(); -} - -static inline uint256 InsecureRand256() -{ - return g_insecure_rand_ctx.rand256(); -} - -static inline uint64_t InsecureRandBits(int bits) -{ - return g_insecure_rand_ctx.randbits(bits); -} - -static inline uint64_t InsecureRandRange(uint64_t range) -{ - return g_insecure_rand_ctx.randrange(range); -} - -static inline bool InsecureRandBool() -{ - return g_insecure_rand_ctx.randbool(); -} +/** Seed the global RNG state for testing and log the seed value. This affects all randomness, except GetStrongRandBytes(). */ +void SeedRandomStateForTest(SeedRand seed); -static inline CAmount InsecureRandMoneyAmount() +template <RandomNumberGenerator Rng> +inline CAmount RandMoney(Rng&& rng) { - return static_cast<CAmount>(InsecureRandRange(MAX_MONEY + 1)); + return CAmount{rng.randrange(MAX_MONEY + 1)}; } #endif // BITCOIN_TEST_UTIL_RANDOM_H diff --git a/src/test/util/setup_common.cpp b/src/test/util/setup_common.cpp index 3f48ea4375..fa89ceb332 100644 --- a/src/test/util/setup_common.cpp +++ b/src/test/util/setup_common.cpp @@ -1,9 +1,7 @@ -// Copyright (c) 2011-2022 The Bitcoin Core developers +// Copyright (c) 2011-present 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 <config/bitcoin-config.h> // IWYU pragma: keep - #include <test/util/setup_common.h> #include <addrman.h> @@ -31,7 +29,6 @@ #include <node/warnings.h> #include <noui.h> #include <policy/fees.h> -#include <policy/fees_args.h> #include <pow.h> #include <random.h> #include <rpc/blockchain.h> @@ -64,6 +61,7 @@ #include <functional> #include <stdexcept> +using namespace util::hex_literals; using kernel::BlockTreeDB; using node::ApplyArgsManOptions; using node::BlockAssembler; @@ -76,26 +74,9 @@ using node::VerifyLoadedChainstate; const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr; -/** Random context to get unique temp data dirs. Separate from g_insecure_rand_ctx, which can be seeded from a const env var */ -static FastRandomContext g_insecure_rand_ctx_temp_path; - -std::ostream& operator<<(std::ostream& os, const arith_uint256& num) -{ - os << num.ToString(); - return os; -} - -std::ostream& operator<<(std::ostream& os, const uint160& num) -{ - os << num.ToString(); - return os; -} - -std::ostream& operator<<(std::ostream& os, const uint256& num) -{ - os << num.ToString(); - return os; -} +constexpr inline auto TEST_DIR_PATH_ELEMENT{"test_common bitcoin"}; // Includes a space to catch possible path escape issues. +/** Random context to get unique temp data dirs. Separate from m_rng, which can be seeded from a const env var */ +static FastRandomContext g_rng_temp_path; struct NetworkSetup { @@ -109,7 +90,7 @@ static NetworkSetup g_networksetup_instance; /** Register test-only arguments */ static void SetupUnitTestArgs(ArgsManager& argsman) { - argsman.AddArg("-testdatadir", strprintf("Custom data directory (default: %s<random_string>)", fs::PathToString(fs::temp_directory_path() / "test_common_" PACKAGE_NAME / "")), + argsman.AddArg("-testdatadir", strprintf("Custom data directory (default: %s<random_string>)", fs::PathToString(fs::temp_directory_path() / TEST_DIR_PATH_ELEMENT / "")), ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); } @@ -155,12 +136,12 @@ BasicTestingSetup::BasicTestingSetup(const ChainType chainType, TestOpts opts) // Use randomly chosen seed for deterministic PRNG, so that (by default) test // data directories use a random name that doesn't overlap with other tests. - SeedRandomForTest(SeedRand::SEED); + SeedRandomForTest(SeedRand::FIXED_SEED); if (!m_node.args->IsArgSet("-testdatadir")) { // By default, the data directory has a random name - const auto rand_str{g_insecure_rand_ctx_temp_path.rand256().ToString()}; - m_path_root = fs::temp_directory_path() / "test_common_" PACKAGE_NAME / rand_str; + const auto rand_str{g_rng_temp_path.rand256().ToString()}; + m_path_root = fs::temp_directory_path() / TEST_DIR_PATH_ELEMENT / rand_str; TryCreateDirectories(m_path_root); } else { // Custom data directory @@ -170,7 +151,7 @@ BasicTestingSetup::BasicTestingSetup(const ChainType chainType, TestOpts opts) root_dir = fs::absolute(root_dir); const std::string test_path{G_TEST_GET_FULL_NAME ? G_TEST_GET_FULL_NAME() : ""}; - m_path_lock = root_dir / "test_common_" PACKAGE_NAME / fs::PathFromString(test_path); + m_path_lock = root_dir / TEST_DIR_PATH_ELEMENT / fs::PathFromString(test_path); m_path_root = m_path_lock / "datadir"; // Try to obtain the lock; if unsuccessful don't disturb the existing test. @@ -236,7 +217,6 @@ ChainTestingSetup::ChainTestingSetup(const ChainType chainType, TestOpts opts) m_node.validation_signals = std::make_unique<ValidationSignals>(std::make_unique<SerialTaskRunner>(*m_node.scheduler)); } - m_node.fee_estimator = std::make_unique<CBlockPolicyEstimator>(FeeestPath(*m_node.args), DEFAULT_ACCEPT_STALE_FEE_ESTIMATES); bilingual_str error{}; m_node.mempool = std::make_unique<CTxMemPool>(MemPoolOptionsForTest(m_node), error); Assert(error.empty()); @@ -246,24 +226,34 @@ ChainTestingSetup::ChainTestingSetup(const ChainType chainType, TestOpts opts) m_node.notifications = std::make_unique<KernelNotifications>(*Assert(m_node.shutdown), m_node.exit_status, *Assert(m_node.warnings)); - const ChainstateManager::Options chainman_opts{ - .chainparams = chainparams, - .datadir = m_args.GetDataDirNet(), - .check_block_index = 1, - .notifications = *m_node.notifications, - .signals = m_node.validation_signals.get(), - .worker_threads_num = 2, - }; - const BlockManager::Options blockman_opts{ - .chainparams = chainman_opts.chainparams, - .blocks_dir = m_args.GetBlocksDirPath(), - .notifications = chainman_opts.notifications, + m_make_chainman = [this, &chainparams, opts] { + Assert(!m_node.chainman); + ChainstateManager::Options chainman_opts{ + .chainparams = chainparams, + .datadir = m_args.GetDataDirNet(), + .check_block_index = 1, + .notifications = *m_node.notifications, + .signals = m_node.validation_signals.get(), + .worker_threads_num = 2, + }; + if (opts.min_validation_cache) { + chainman_opts.script_execution_cache_bytes = 0; + chainman_opts.signature_cache_bytes = 0; + } + const BlockManager::Options blockman_opts{ + .chainparams = chainman_opts.chainparams, + .blocks_dir = m_args.GetBlocksDirPath(), + .notifications = chainman_opts.notifications, + }; + m_node.chainman = std::make_unique<ChainstateManager>(*Assert(m_node.shutdown), chainman_opts, blockman_opts); + LOCK(m_node.chainman->GetMutex()); + m_node.chainman->m_blockman.m_block_tree_db = std::make_unique<BlockTreeDB>(DBParams{ + .path = m_args.GetDataDirNet() / "blocks" / "index", + .cache_bytes = static_cast<size_t>(m_cache_sizes.block_tree_db), + .memory_only = true, + }); }; - m_node.chainman = std::make_unique<ChainstateManager>(*Assert(m_node.shutdown), chainman_opts, blockman_opts); - m_node.chainman->m_blockman.m_block_tree_db = std::make_unique<BlockTreeDB>(DBParams{ - .path = m_args.GetDataDirNet() / "blocks" / "index", - .cache_bytes = static_cast<size_t>(m_cache_sizes.block_tree_db), - .memory_only = true}); + m_make_chainman(); } ChainTestingSetup::~ChainTestingSetup() @@ -276,7 +266,7 @@ ChainTestingSetup::~ChainTestingSetup() m_node.netgroupman.reset(); m_node.args = nullptr; m_node.mempool.reset(); - m_node.fee_estimator.reset(); + Assert(!m_node.fee_estimator); // Each test must create a local object, if they wish to use the fee_estimator m_node.chainman.reset(); m_node.validation_signals.reset(); m_node.scheduler.reset(); @@ -572,7 +562,7 @@ void TestChain100Setup::MockMempoolMinFee(const CFeeRate& target_feerate) // Manually create an invalid transaction. Manually set the fee in the CTxMemPoolEntry to // achieve the exact target feerate. CMutableTransaction mtx = CMutableTransaction(); - mtx.vin.emplace_back(COutPoint{Txid::FromUint256(g_insecure_rand_ctx.rand256()), 0}); + mtx.vin.emplace_back(COutPoint{Txid::FromUint256(m_rng.rand256()), 0}); mtx.vout.emplace_back(1 * COIN, GetScriptForDestination(WitnessV0ScriptHash(CScript() << OP_TRUE))); const auto tx{MakeTransactionRef(mtx)}; LockPoints lp; @@ -593,8 +583,23 @@ CBlock getBlock13b8a() { CBlock block; DataStream stream{ - ParseHex("0100000090f0a9f110702f808219ebea1173056042a714bad51b916cb6800000000000005275289558f51c9966699404ae2294730c3c9f9bda53523ce50e9b95e558da2fdb261b4d4c86041b1ab1bf930901000000010000000000000000000000000000000000000000000000000000000000000000ffffffff07044c86041b0146ffffffff0100f2052a01000000434104e18f7afbe4721580e81e8414fc8c24d7cfacf254bb5c7b949450c3e997c2dc1242487a8169507b631eb3771f2b425483fb13102c4eb5d858eef260fe70fbfae0ac00000000010000000196608ccbafa16abada902780da4dc35dafd7af05fa0da08cf833575f8cf9e836000000004a493046022100dab24889213caf43ae6adc41cf1c9396c08240c199f5225acf45416330fd7dbd022100fe37900e0644bf574493a07fc5edba06dbc07c311b947520c2d514bc5725dcb401ffffffff0100f2052a010000001976a914f15d1921f52e4007b146dfa60f369ed2fc393ce288ac000000000100000001fb766c1288458c2bafcfec81e48b24d98ec706de6b8af7c4e3c29419bfacb56d000000008c493046022100f268ba165ce0ad2e6d93f089cfcd3785de5c963bb5ea6b8c1b23f1ce3e517b9f022100da7c0f21adc6c401887f2bfd1922f11d76159cbc597fbd756a23dcbb00f4d7290141042b4e8625a96127826915a5b109852636ad0da753c9e1d5606a50480cd0c40f1f8b8d898235e571fe9357d9ec842bc4bba1827daaf4de06d71844d0057707966affffffff0280969800000000001976a9146963907531db72d0ed1a0cfb471ccb63923446f388ac80d6e34c000000001976a914f0688ba1c0d1ce182c7af6741e02658c7d4dfcd388ac000000000100000002c40297f730dd7b5a99567eb8d27b78758f607507c52292d02d4031895b52f2ff010000008b483045022100f7edfd4b0aac404e5bab4fd3889e0c6c41aa8d0e6fa122316f68eddd0a65013902205b09cc8b2d56e1cd1f7f2fafd60a129ed94504c4ac7bdc67b56fe67512658b3e014104732012cb962afa90d31b25d8fb0e32c94e513ab7a17805c14ca4c3423e18b4fb5d0e676841733cb83abaf975845c9f6f2a8097b7d04f4908b18368d6fc2d68ecffffffffca5065ff9617cbcba45eb23726df6498a9b9cafed4f54cbab9d227b0035ddefb000000008a473044022068010362a13c7f9919fa832b2dee4e788f61f6f5d344a7c2a0da6ae740605658022006d1af525b9a14a35c003b78b72bd59738cd676f845d1ff3fc25049e01003614014104732012cb962afa90d31b25d8fb0e32c94e513ab7a17805c14ca4c3423e18b4fb5d0e676841733cb83abaf975845c9f6f2a8097b7d04f4908b18368d6fc2d68ecffffffff01001ec4110200000043410469ab4181eceb28985b9b4e895c13fa5e68d85761b7eee311db5addef76fa8621865134a221bd01f28ec9999ee3e021e60766e9d1f3458c115fb28650605f11c9ac000000000100000001cdaf2f758e91c514655e2dc50633d1e4c84989f8aa90a0dbc883f0d23ed5c2fa010000008b48304502207ab51be6f12a1962ba0aaaf24a20e0b69b27a94fac5adf45aa7d2d18ffd9236102210086ae728b370e5329eead9accd880d0cb070aea0c96255fae6c4f1ddcce1fd56e014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff02404b4c00000000001976a9142b6ba7c9d796b75eef7942fc9288edd37c32f5c388ac002d3101000000001976a9141befba0cdc1ad56529371864d9f6cb042faa06b588ac000000000100000001b4a47603e71b61bc3326efd90111bf02d2f549b067f4c4a8fa183b57a0f800cb010000008a4730440220177c37f9a505c3f1a1f0ce2da777c339bd8339ffa02c7cb41f0a5804f473c9230220585b25a2ee80eb59292e52b987dad92acb0c64eced92ed9ee105ad153cdb12d001410443bd44f683467e549dae7d20d1d79cbdb6df985c6e9c029c8d0c6cb46cc1a4d3cf7923c5021b27f7a0b562ada113bc85d5fda5a1b41e87fe6e8802817cf69996ffffffff0280651406000000001976a9145505614859643ab7b547cd7f1f5e7e2a12322d3788ac00aa0271000000001976a914ea4720a7a52fc166c55ff2298e07baf70ae67e1b88ac00000000010000000586c62cd602d219bb60edb14a3e204de0705176f9022fe49a538054fb14abb49e010000008c493046022100f2bc2aba2534becbdf062eb993853a42bbbc282083d0daf9b4b585bd401aa8c9022100b1d7fd7ee0b95600db8535bbf331b19eed8d961f7a8e54159c53675d5f69df8c014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff03ad0e58ccdac3df9dc28a218bcf6f1997b0a93306faaa4b3a28ae83447b2179010000008b483045022100be12b2937179da88599e27bb31c3525097a07cdb52422d165b3ca2f2020ffcf702200971b51f853a53d644ebae9ec8f3512e442b1bcb6c315a5b491d119d10624c83014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff2acfcab629bbc8685792603762c921580030ba144af553d271716a95089e107b010000008b483045022100fa579a840ac258871365dd48cd7552f96c8eea69bd00d84f05b283a0dab311e102207e3c0ee9234814cfbb1b659b83671618f45abc1326b9edcc77d552a4f2a805c0014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffffdcdc6023bbc9944a658ddc588e61eacb737ddf0a3cd24f113b5a8634c517fcd2000000008b4830450221008d6df731df5d32267954bd7d2dda2302b74c6c2a6aa5c0ca64ecbabc1af03c75022010e55c571d65da7701ae2da1956c442df81bbf076cdbac25133f99d98a9ed34c014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffffe15557cd5ce258f479dfd6dc6514edf6d7ed5b21fcfa4a038fd69f06b83ac76e010000008b483045022023b3e0ab071eb11de2eb1cc3a67261b866f86bf6867d4558165f7c8c8aca2d86022100dc6e1f53a91de3efe8f63512850811f26284b62f850c70ca73ed5de8771fb451014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff01404b4c00000000001976a9142b6ba7c9d796b75eef7942fc9288edd37c32f5c388ac00000000010000000166d7577163c932b4f9690ca6a80b6e4eb001f0a2fa9023df5595602aae96ed8d000000008a4730440220262b42546302dfb654a229cefc86432b89628ff259dc87edd1154535b16a67e102207b4634c020a97c3e7bbd0d4d19da6aa2269ad9dded4026e896b213d73ca4b63f014104979b82d02226b3a4597523845754d44f13639e3bf2df5e82c6aab2bdc79687368b01b1ab8b19875ae3c90d661a3d0a33161dab29934edeb36aa01976be3baf8affffffff02404b4c00000000001976a9144854e695a02af0aeacb823ccbc272134561e0a1688ac40420f00000000001976a914abee93376d6b37b5c2940655a6fcaf1c8e74237988ac0000000001000000014e3f8ef2e91349a9059cb4f01e54ab2597c1387161d3da89919f7ea6acdbb371010000008c49304602210081f3183471a5ca22307c0800226f3ef9c353069e0773ac76bb580654d56aa523022100d4c56465bdc069060846f4fbf2f6b20520b2a80b08b168b31e66ddb9c694e240014104976c79848e18251612f8940875b2b08d06e6dc73b9840e8860c066b7e87432c477e9a59a453e71e6d76d5fe34058b800a098fc1740ce3012e8fc8a00c96af966ffffffff02c0e1e400000000001976a9144134e75a6fcb6042034aab5e18570cf1f844f54788ac404b4c00000000001976a9142b6ba7c9d796b75eef7942fc9288edd37c32f5c388ac00000000"), + "0100000090f0a9f110702f808219ebea1173056042a714bad51b916cb6800000000000005275289558f51c9966699404ae2294730c3c9f9bda53523ce50e9b95e558da2fdb261b4d4c86041b1ab1bf930901000000010000000000000000000000000000000000000000000000000000000000000000ffffffff07044c86041b0146ffffffff0100f2052a01000000434104e18f7afbe4721580e81e8414fc8c24d7cfacf254bb5c7b949450c3e997c2dc1242487a8169507b631eb3771f2b425483fb13102c4eb5d858eef260fe70fbfae0ac00000000010000000196608ccbafa16abada902780da4dc35dafd7af05fa0da08cf833575f8cf9e836000000004a493046022100dab24889213caf43ae6adc41cf1c9396c08240c199f5225acf45416330fd7dbd022100fe37900e0644bf574493a07fc5edba06dbc07c311b947520c2d514bc5725dcb401ffffffff0100f2052a010000001976a914f15d1921f52e4007b146dfa60f369ed2fc393ce288ac000000000100000001fb766c1288458c2bafcfec81e48b24d98ec706de6b8af7c4e3c29419bfacb56d000000008c493046022100f268ba165ce0ad2e6d93f089cfcd3785de5c963bb5ea6b8c1b23f1ce3e517b9f022100da7c0f21adc6c401887f2bfd1922f11d76159cbc597fbd756a23dcbb00f4d7290141042b4e8625a96127826915a5b109852636ad0da753c9e1d5606a50480cd0c40f1f8b8d898235e571fe9357d9ec842bc4bba1827daaf4de06d71844d0057707966affffffff0280969800000000001976a9146963907531db72d0ed1a0cfb471ccb63923446f388ac80d6e34c000000001976a914f0688ba1c0d1ce182c7af6741e02658c7d4dfcd388ac000000000100000002c40297f730dd7b5a99567eb8d27b78758f607507c52292d02d4031895b52f2ff010000008b483045022100f7edfd4b0aac404e5bab4fd3889e0c6c41aa8d0e6fa122316f68eddd0a65013902205b09cc8b2d56e1cd1f7f2fafd60a129ed94504c4ac7bdc67b56fe67512658b3e014104732012cb962afa90d31b25d8fb0e32c94e513ab7a17805c14ca4c3423e18b4fb5d0e676841733cb83abaf975845c9f6f2a8097b7d04f4908b18368d6fc2d68ecffffffffca5065ff9617cbcba45eb23726df6498a9b9cafed4f54cbab9d227b0035ddefb000000008a473044022068010362a13c7f9919fa832b2dee4e788f61f6f5d344a7c2a0da6ae740605658022006d1af525b9a14a35c003b78b72bd59738cd676f845d1ff3fc25049e01003614014104732012cb962afa90d31b25d8fb0e32c94e513ab7a17805c14ca4c3423e18b4fb5d0e676841733cb83abaf975845c9f6f2a8097b7d04f4908b18368d6fc2d68ecffffffff01001ec4110200000043410469ab4181eceb28985b9b4e895c13fa5e68d85761b7eee311db5addef76fa8621865134a221bd01f28ec9999ee3e021e60766e9d1f3458c115fb28650605f11c9ac000000000100000001cdaf2f758e91c514655e2dc50633d1e4c84989f8aa90a0dbc883f0d23ed5c2fa010000008b48304502207ab51be6f12a1962ba0aaaf24a20e0b69b27a94fac5adf45aa7d2d18ffd9236102210086ae728b370e5329eead9accd880d0cb070aea0c96255fae6c4f1ddcce1fd56e014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff02404b4c00000000001976a9142b6ba7c9d796b75eef7942fc9288edd37c32f5c388ac002d3101000000001976a9141befba0cdc1ad56529371864d9f6cb042faa06b588ac000000000100000001b4a47603e71b61bc3326efd90111bf02d2f549b067f4c4a8fa183b57a0f800cb010000008a4730440220177c37f9a505c3f1a1f0ce2da777c339bd8339ffa02c7cb41f0a5804f473c9230220585b25a2ee80eb59292e52b987dad92acb0c64eced92ed9ee105ad153cdb12d001410443bd44f683467e549dae7d20d1d79cbdb6df985c6e9c029c8d0c6cb46cc1a4d3cf7923c5021b27f7a0b562ada113bc85d5fda5a1b41e87fe6e8802817cf69996ffffffff0280651406000000001976a9145505614859643ab7b547cd7f1f5e7e2a12322d3788ac00aa0271000000001976a914ea4720a7a52fc166c55ff2298e07baf70ae67e1b88ac00000000010000000586c62cd602d219bb60edb14a3e204de0705176f9022fe49a538054fb14abb49e010000008c493046022100f2bc2aba2534becbdf062eb993853a42bbbc282083d0daf9b4b585bd401aa8c9022100b1d7fd7ee0b95600db8535bbf331b19eed8d961f7a8e54159c53675d5f69df8c014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff03ad0e58ccdac3df9dc28a218bcf6f1997b0a93306faaa4b3a28ae83447b2179010000008b483045022100be12b2937179da88599e27bb31c3525097a07cdb52422d165b3ca2f2020ffcf702200971b51f853a53d644ebae9ec8f3512e442b1bcb6c315a5b491d119d10624c83014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff2acfcab629bbc8685792603762c921580030ba144af553d271716a95089e107b010000008b483045022100fa579a840ac258871365dd48cd7552f96c8eea69bd00d84f05b283a0dab311e102207e3c0ee9234814cfbb1b659b83671618f45abc1326b9edcc77d552a4f2a805c0014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffffdcdc6023bbc9944a658ddc588e61eacb737ddf0a3cd24f113b5a8634c517fcd2000000008b4830450221008d6df731df5d32267954bd7d2dda2302b74c6c2a6aa5c0ca64ecbabc1af03c75022010e55c571d65da7701ae2da1956c442df81bbf076cdbac25133f99d98a9ed34c014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffffe15557cd5ce258f479dfd6dc6514edf6d7ed5b21fcfa4a038fd69f06b83ac76e010000008b483045022023b3e0ab071eb11de2eb1cc3a67261b866f86bf6867d4558165f7c8c8aca2d86022100dc6e1f53a91de3efe8f63512850811f26284b62f850c70ca73ed5de8771fb451014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff01404b4c00000000001976a9142b6ba7c9d796b75eef7942fc9288edd37c32f5c388ac00000000010000000166d7577163c932b4f9690ca6a80b6e4eb001f0a2fa9023df5595602aae96ed8d000000008a4730440220262b42546302dfb654a229cefc86432b89628ff259dc87edd1154535b16a67e102207b4634c020a97c3e7bbd0d4d19da6aa2269ad9dded4026e896b213d73ca4b63f014104979b82d02226b3a4597523845754d44f13639e3bf2df5e82c6aab2bdc79687368b01b1ab8b19875ae3c90d661a3d0a33161dab29934edeb36aa01976be3baf8affffffff02404b4c00000000001976a9144854e695a02af0aeacb823ccbc272134561e0a1688ac40420f00000000001976a914abee93376d6b37b5c2940655a6fcaf1c8e74237988ac0000000001000000014e3f8ef2e91349a9059cb4f01e54ab2597c1387161d3da89919f7ea6acdbb371010000008c49304602210081f3183471a5ca22307c0800226f3ef9c353069e0773ac76bb580654d56aa523022100d4c56465bdc069060846f4fbf2f6b20520b2a80b08b168b31e66ddb9c694e240014104976c79848e18251612f8940875b2b08d06e6dc73b9840e8860c066b7e87432c477e9a59a453e71e6d76d5fe34058b800a098fc1740ce3012e8fc8a00c96af966ffffffff02c0e1e400000000001976a9144134e75a6fcb6042034aab5e18570cf1f844f54788ac404b4c00000000001976a9142b6ba7c9d796b75eef7942fc9288edd37c32f5c388ac00000000"_hex, }; stream >> TX_WITH_WITNESS(block); return block; } + +std::ostream& operator<<(std::ostream& os, const arith_uint256& num) +{ + return os << num.ToString(); +} + +std::ostream& operator<<(std::ostream& os, const uint160& num) +{ + return os << num.ToString(); +} + +std::ostream& operator<<(std::ostream& os, const uint256& num) +{ + return os << num.ToString(); +} diff --git a/src/test/util/setup_common.h b/src/test/util/setup_common.h index 9515f0255e..30d4280fa5 100644 --- a/src/test/util/setup_common.h +++ b/src/test/util/setup_common.h @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2022 The Bitcoin Core developers +// Copyright (c) 2015-present The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. @@ -10,9 +10,12 @@ #include <key.h> #include <node/caches.h> #include <node/context.h> // IWYU pragma: export +#include <optional> +#include <ostream> #include <primitives/transaction.h> #include <pubkey.h> #include <stdexcept> +#include <test/util/random.h> #include <util/chaintype.h> // IWYU pragma: export #include <util/check.h> #include <util/fs.h> @@ -28,6 +31,8 @@ class arith_uint256; class CFeeRate; class Chainstate; class FastRandomContext; +class uint160; +class uint256; /** This is connected to the logger. Can be used to redirect logs to any other log */ extern const std::function<void(const std::string&)> G_TEST_LOG_FUN; @@ -38,15 +43,6 @@ extern const std::function<std::vector<const char*>()> G_TEST_COMMAND_LINE_ARGUM /** Retrieve the unit test name. */ extern const std::function<std::string()> G_TEST_GET_FULL_NAME; -// Enable BOOST_CHECK_EQUAL for enum class types -namespace std { -template <typename T> -std::ostream& operator<<(typename std::enable_if<std::is_enum<T>::value, std::ostream>::type& stream, const T& e) -{ - return stream << static_cast<typename std::underlying_type<T>::type>(e); -} -} // namespace std - static constexpr CAmount CENT{1000000}; struct TestOpts { @@ -55,6 +51,7 @@ struct TestOpts { bool block_tree_db_in_memory{true}; bool setup_net{true}; bool setup_validation_interface{true}; + bool min_validation_cache{false}; // Equivalent of -maxsigcachebytes=0 }; /** Basic testing setup. @@ -64,6 +61,14 @@ struct BasicTestingSetup { util::SignalInterrupt m_interrupt; node::NodeContext m_node; // keep as first member to be destructed last + FastRandomContext m_rng; + /** Seed the global RNG state and m_rng for testing and log the seed value. This affects all randomness, except GetStrongRandBytes(). */ + void SeedRandomForTest(SeedRand seed) + { + SeedRandomStateForTest(seed); + m_rng.Reseed(GetRandHash()); + } + explicit BasicTestingSetup(const ChainType chainType = ChainType::MAIN, TestOpts = {}); ~BasicTestingSetup(); @@ -81,6 +86,7 @@ struct ChainTestingSetup : public BasicTestingSetup { node::CacheSizes m_cache_sizes{}; bool m_coins_db_in_memory{true}; bool m_block_tree_db_in_memory{true}; + std::function<void()> m_make_chainman{}; explicit ChainTestingSetup(const ChainType chainType = ChainType::MAIN, TestOpts = {}); ~ChainTestingSetup(); @@ -239,10 +245,26 @@ std::unique_ptr<T> MakeNoLogFileContext(const ChainType chain_type = ChainType:: CBlock getBlock13b8a(); -// Make types usable in BOOST_CHECK_* +// Make types usable in BOOST_CHECK_* @{ +namespace std { +template <typename T> requires std::is_enum_v<T> +inline std::ostream& operator<<(std::ostream& os, const T& e) +{ + return os << static_cast<std::underlying_type_t<T>>(e); +} + +template <typename T> +inline std::ostream& operator<<(std::ostream& os, const std::optional<T>& v) +{ + return v ? os << *v + : os << "std::nullopt"; +} +} // namespace std + std::ostream& operator<<(std::ostream& os, const arith_uint256& num); std::ostream& operator<<(std::ostream& os, const uint160& num); std::ostream& operator<<(std::ostream& os, const uint256& num); +// @} /** * BOOST_CHECK_EXCEPTION predicates to check the specific validation error. diff --git a/src/test/util/transaction_utils.cpp b/src/test/util/transaction_utils.cpp index 300caa577c..5727da4444 100644 --- a/src/test/util/transaction_utils.cpp +++ b/src/test/util/transaction_utils.cpp @@ -3,6 +3,7 @@ // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <coins.h> +#include <consensus/validation.h> #include <script/signingprovider.h> #include <test/util/transaction_utils.h> @@ -69,3 +70,23 @@ std::vector<CMutableTransaction> SetupDummyInputs(FillableSigningProvider& keyst return dummyTransactions; } + +void BulkTransaction(CMutableTransaction& tx, int32_t target_weight) +{ + tx.vout.emplace_back(0, CScript() << OP_RETURN); + auto unpadded_weight{GetTransactionWeight(CTransaction(tx))}; + assert(target_weight >= unpadded_weight); + + // determine number of needed padding bytes by converting weight difference to vbytes + auto dummy_vbytes = (target_weight - unpadded_weight + (WITNESS_SCALE_FACTOR - 1)) / WITNESS_SCALE_FACTOR; + // compensate for the increase of the compact-size encoded script length + // (note that the length encoding of the unpadded output script needs one byte) + dummy_vbytes -= GetSizeOfCompactSize(dummy_vbytes) - 1; + + // pad transaction by repeatedly appending a dummy opcode to the output script + tx.vout[0].scriptPubKey.insert(tx.vout[0].scriptPubKey.end(), dummy_vbytes, OP_1); + + // actual weight should be at most 3 higher than target weight + assert(GetTransactionWeight(CTransaction(tx)) >= target_weight); + assert(GetTransactionWeight(CTransaction(tx)) <= target_weight + 3); +} diff --git a/src/test/util/transaction_utils.h b/src/test/util/transaction_utils.h index 6f2faeec6c..80f2d1acbf 100644 --- a/src/test/util/transaction_utils.h +++ b/src/test/util/transaction_utils.h @@ -26,4 +26,8 @@ CMutableTransaction BuildSpendingTransaction(const CScript& scriptSig, const CSc // the second nValues[2] and nValues[3] outputs paid to a TxoutType::PUBKEYHASH. std::vector<CMutableTransaction> SetupDummyInputs(FillableSigningProvider& keystoreRet, CCoinsViewCache& coinsRet, const std::array<CAmount,4>& nValues); +// bulk transaction to reach a certain target weight, +// by appending a single output with padded output script +void BulkTransaction(CMutableTransaction& tx, int32_t target_weight); + #endif // BITCOIN_TEST_UTIL_TRANSACTION_UTILS_H |