Line data Source code
1 : // Copyright (c) 2021 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 : // 5 : #ifndef BITCOIN_TEST_UTIL_CHAINSTATE_H 6 : #define BITCOIN_TEST_UTIL_CHAINSTATE_H 7 : 8 : #include <clientversion.h> 9 : #include <fs.h> 10 : #include <logging.h> 11 : #include <node/context.h> 12 : #include <node/utxo_snapshot.h> 13 : #include <rpc/blockchain.h> 14 : #include <validation.h> 15 : 16 : #include <univalue.h> 17 : 18 4 : const auto NoMalleation = [](AutoFile& file, node::SnapshotMetadata& meta){}; 19 : 20 : /** 21 : * Create and activate a UTXO snapshot, optionally providing a function to 22 : * malleate the snapshot. 23 : */ 24 : template<typename F = decltype(NoMalleation)> 25 : static bool 26 9 : CreateAndActivateUTXOSnapshot(node::NodeContext& node, const fs::path root, F malleation = NoMalleation) 27 : { 28 : // Write out a snapshot to the test's tempdir. 29 : // 30 : int height; 31 18 : WITH_LOCK(::cs_main, height = node.chainman->ActiveHeight()); 32 9 : fs::path snapshot_path = root / fs::u8path(tfm::format("test_snapshot.%d.dat", height)); 33 9 : FILE* outfile{fsbridge::fopen(snapshot_path, "wb")}; 34 9 : AutoFile auto_outfile{outfile}; 35 : 36 9 : UniValue result = CreateUTXOSnapshot( 37 9 : node, node.chainman->ActiveChainstate(), auto_outfile, snapshot_path, snapshot_path); 38 9 : LogPrintf( 39 : "Wrote UTXO snapshot to %s: %s", fs::PathToString(snapshot_path.make_preferred()), result.write()); 40 : 41 : // Read the written snapshot in and then activate it. 42 : // 43 9 : FILE* infile{fsbridge::fopen(snapshot_path, "rb")}; 44 9 : AutoFile auto_infile{infile}; 45 9 : node::SnapshotMetadata metadata; 46 9 : auto_infile >> metadata; 47 : 48 9 : malleation(auto_infile, metadata); 49 : 50 9 : return node.chainman->ActivateSnapshot(auto_infile, metadata, /*in_memory=*/true); 51 9 : } 52 : 53 : 54 : #endif // BITCOIN_TEST_UTIL_CHAINSTATE_H