Bitcoin Core 32.99.0
P2P Digital Currency
utxo_snapshot.cpp
Go to the documentation of this file.
1// Copyright (c) 2021-present 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#include <chain.h>
6#include <chainparams.h>
7#include <coins.h>
10#include <kernel/coinstats.h>
12#include <node/blockstorage.h>
13#include <node/utxo_snapshot.h>
14#include <primitives/block.h>
16#include <serialize.h>
17#include <span.h>
18#include <streams.h>
19#include <sync.h>
21#include <test/fuzz/fuzz.h>
22#include <test/fuzz/util.h>
23#include <test/util/mining.h>
25#include <test/util/time.h>
26#include <uint256.h>
27#include <util/check.h>
28#include <util/fs.h>
29#include <util/result.h>
30#include <util/time.h>
31#include <validation.h>
32
33#include <cstdint>
34#include <functional>
35#include <ios>
36#include <memory>
37#include <optional>
38#include <vector>
39
41
42namespace {
43
44const std::vector<std::shared_ptr<CBlock>>* g_chain;
45TestingSetup* g_setup{nullptr};
46
48void sanity_check_snapshot()
49{
50 Assert(g_chain && g_setup == nullptr);
51
52 // Create a temporary chainstate manager to connect the chain to.
53 const auto tmp_setup{MakeNoLogFileContext<TestingSetup>(ChainType::REGTEST, TestOpts{.setup_net = false})};
54 const auto& node{tmp_setup->m_node};
55 for (auto& block: *g_chain) {
56 ProcessBlock(node, block);
57 }
58
59 // Connect the chain to the tmp chainman and sanity check the chainparams snapshot values.
61 auto& cs{node.chainman->ActiveChainstate()};
62 cs.ForceFlushStateToDisk(/*wipe_cache=*/false);
63 const auto stats{*Assert(kernel::ComputeUTXOStats(kernel::CoinStatsHashType::HASH_SERIALIZED, cs.CoinsDB(), node.chainman->m_blockman))};
64 const auto cp_au_data{*Assert(node.chainman->GetParams().AssumeutxoForHeight(2 * COINBASE_MATURITY))};
65 Assert(stats.nHeight == cp_au_data.height);
66 Assert(stats.nTransactions + 1 == cp_au_data.m_chain_tx_count); // +1 for the genesis tx.
67 Assert(stats.hashBlock == cp_au_data.blockhash);
68 Assert(AssumeutxoHash{stats.hashSerialized} == cp_au_data.hash_serialized);
69}
70
71template <bool INVALID>
72void initialize_chain()
73{
75 static const auto chain{CreateBlockChain(2 * COINBASE_MATURITY, *params)};
76 g_chain = &chain;
77 FakeNodeClock node_clock{chain.back()->Time()};
78
79 // Make sure we can generate a valid snapshot.
80 sanity_check_snapshot();
81
82 static const auto setup{
83 MakeNoLogFileContext<TestingSetup>(ChainType::REGTEST,
85 .setup_net = false,
86 .setup_validation_interface = false,
87 .min_validation_cache = true,
88 }),
89 };
90 if constexpr (INVALID) {
91 auto& chainman{*setup->m_node.chainman};
92 for (const auto& block : chain) {
94 bool processed{chainman.ProcessNewBlockHeaders({{*block}}, true, dummy)};
95 Assert(processed);
96 const auto* index{WITH_LOCK(::cs_main, return chainman.m_blockman.LookupBlockIndex(block->GetHash()))};
97 Assert(index);
98 }
99 }
100 g_setup = setup.get();
101}
102
103template <bool INVALID>
104void utxo_snapshot_fuzz(FuzzBufferType buffer)
105{
107 FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
108 FakeNodeClock node_clock{ConsumeTime(fuzzed_data_provider, /*min=*/1296688602)}; // regtest genesis block timestamp
109 auto& setup{*g_setup};
110 bool dirty_chainman{false}; // Reuse the global chainman, but reset it when it is dirty
111 auto& chainman{*setup.m_node.chainman};
112
113 const auto snapshot_path = gArgs.GetDataDirNet() / "fuzzed_snapshot.dat";
114
115 Assert(!chainman.ActiveChainstate().m_from_snapshot_blockhash);
116
117 {
118 AutoFile outfile{fsbridge::fopen(snapshot_path, "wb")};
119 // Metadata
121 std::vector<uint8_t> metadata{ConsumeRandomLengthByteVector(fuzzed_data_provider)};
122 outfile << std::span{metadata};
123 } else {
124 auto msg_start = chainman.GetParams().MessageStart();
125 int base_blockheight{fuzzed_data_provider.ConsumeIntegralInRange<int>(1, 2 * COINBASE_MATURITY)};
126 uint256 base_blockhash{g_chain->at(base_blockheight - 1)->GetHash()};
127 uint64_t m_coins_count{fuzzed_data_provider.ConsumeIntegralInRange<uint64_t>(1, 3 * COINBASE_MATURITY)};
128 SnapshotMetadata metadata{msg_start, base_blockhash, m_coins_count};
129 outfile << metadata;
130 }
131 // Coins
133 std::vector<uint8_t> file_data{ConsumeRandomLengthByteVector(fuzzed_data_provider)};
134 outfile << std::span{file_data};
135 } else {
136 int height{1};
137 for (const auto& block : *g_chain) {
138 auto coinbase{block->vtx.at(0)};
139 outfile << coinbase->GetHash();
140 WriteCompactSize(outfile, 1); // number of coins for the hash
141 WriteCompactSize(outfile, 0); // index of coin
142 outfile << Coin(coinbase->vout[0], height, /*fCoinBaseIn=*/true);
143 height++;
144 }
145 }
146 if constexpr (INVALID) {
147 // Append an invalid coin to ensure invalidity. This error will be
148 // detected late in PopulateAndValidateSnapshot, and allows the
149 // INVALID fuzz target to reach more potential code coverage.
150 const auto& coinbase{g_chain->back()->vtx.back()};
151 outfile << coinbase->GetHash();
152 WriteCompactSize(outfile, 1); // number of coins for the hash
153 WriteCompactSize(outfile, 999); // index of coin
154 outfile << Coin{coinbase->vout[0], /*nHeightIn=*/999, /*fCoinBaseIn=*/false};
155 }
156 assert(outfile.fclose() == 0);
157 }
158
159 const auto ActivateFuzzedSnapshot{[&] {
160 AutoFile infile{fsbridge::fopen(snapshot_path, "rb")};
161 auto msg_start = chainman.GetParams().MessageStart();
162 SnapshotMetadata metadata{msg_start};
163 try {
164 infile >> metadata;
165 } catch (const std::ios_base::failure&) {
166 return false;
167 }
168 return !!chainman.ActivateSnapshot(infile, metadata, /*in_memory=*/true);
169 }};
170
172 // Consume the bool, but skip the code for the INVALID fuzz target
173 if constexpr (!INVALID) {
174 for (const auto& block : *g_chain) {
176 bool processed{chainman.ProcessNewBlockHeaders({{*block}}, true, dummy)};
177 Assert(processed);
178 const auto* index{WITH_LOCK(::cs_main, return chainman.m_blockman.LookupBlockIndex(block->GetHash()))};
179 Assert(index);
180 }
181 dirty_chainman = true;
182 }
183 }
184
185 if (ActivateFuzzedSnapshot()) {
187 Assert(!chainman.ActiveChainstate().m_from_snapshot_blockhash->IsNull());
188 const auto& coinscache{chainman.ActiveChainstate().CoinsTip()};
189 for (const auto& block : *g_chain) {
190 Assert(coinscache.HaveCoin(COutPoint{block->vtx.at(0)->GetHash(), 0}));
191 const auto* index{chainman.m_blockman.LookupBlockIndex(block->GetHash())};
192 Assert(index);
193 Assert(index->nTx == 0);
194 if (index->nHeight == chainman.ActiveChainstate().SnapshotBase()->nHeight) {
195 auto params{chainman.GetParams().AssumeutxoForHeight(index->nHeight)};
196 Assert(params.has_value());
197 Assert(params.value().m_chain_tx_count == index->m_chain_tx_count);
198 } else {
199 Assert(index->m_chain_tx_count == 0);
200 }
201 }
202 Assert(g_chain->size() == coinscache.GetCacheSize());
203 dirty_chainman = true;
204 } else {
205 Assert(!chainman.ActiveChainstate().m_from_snapshot_blockhash);
206 }
207 // Snapshot should refuse to load a second time regardless of validity
208 Assert(!ActivateFuzzedSnapshot());
209 if constexpr (INVALID) {
210 // Activating the snapshot, or any other action that makes the chainman
211 // "dirty" can and must not happen for the INVALID fuzz target
212 Assert(!dirty_chainman);
213 }
214 if (dirty_chainman) {
215 setup.m_node.block_template_manager.reset();
216 setup.m_node.chainman.reset();
217 setup.m_make_chainman();
218 setup.LoadVerifyActivateChainstate();
219 setup.CreateBlockTemplateManager();
220 }
221}
222
223// There are two fuzz targets:
224//
225// The target 'utxo_snapshot', which allows valid snapshots, but is slow,
226// because it has to reset the chainstate manager on almost all fuzz inputs.
227// Otherwise, a dirty header tree or dirty chainstate could leak from one fuzz
228// input execution into the next, which makes execution non-deterministic.
229//
230// The target 'utxo_snapshot_invalid', which is fast and does not require any
231// expensive state to be reset.
232FUZZ_TARGET(utxo_snapshot /*valid*/, .init = initialize_chain<false>) { utxo_snapshot_fuzz<false>(buffer); }
233FUZZ_TARGET(utxo_snapshot_invalid, .init = initialize_chain<true>) { utxo_snapshot_fuzz<true>(buffer); }
234
235} // namespace
ArgsManager gArgs
Definition: args.cpp:38
static void pool cs
const TestingSetup * g_setup
std::unique_ptr< const CChainParams > CreateChainParams(const ArgsManager &args, const ChainType chain)
Creates and returns a std::unique_ptr<CChainParams> of the chosen chain.
#define Assert(val)
Identity function.
Definition: check.h:116
fs::path GetDataDirNet() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get data directory path with appended network identifier.
Definition: args.cpp:328
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:395
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:30
A UTXO entry.
Definition: coins.h:46
Helper to initialize the global NodeClock, let a duration elapse, and reset it after use in a test.
Definition: time.h:54
T ConsumeIntegralInRange(T min, T max)
Metadata describing a serialized version of a UTXO set from which an assumeutxo Chainstate can be con...
Definition: utxo_snapshot.h:38
256-bit opaque blob.
Definition: uint256.h:196
constexpr int COINBASE_MATURITY
Coinbase transaction outputs can only be spent after this number of new blocks (network rule)
Definition: consensus.h:19
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
#define FUZZ_TARGET(...)
Definition: fuzz.h:35
std::span< const uint8_t > FuzzBufferType
Definition: fuzz.h:25
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:23
Definition: basic.cpp:11
static std::optional< CCoinsStats > ComputeUTXOStats(T hash_obj, const CCoinsViewDB &view, node::BlockManager &blockman, const std::function< void()> &interruption_point)
Calculate statistics about the unspent transaction output set.
Definition: coinstats.cpp:112
const auto INVALID
A stack representing the lack of any (dis)satisfactions.
Definition: miniscript.h:353
Definition: messages.h:21
void WriteCompactSize(SizeComputer &os, uint64_t nSize)
Definition: serialize.h:1151
bool setup_net
Definition: setup_common.h:50
Testing setup that configures a complete environment.
Definition: setup_common.h:119
#define LOCK(cs)
Definition: sync.h:268
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:299
SeedRandomStateForTest(SeedRand::ZEROS)
NodeSeconds ConsumeTime(FuzzedDataProvider &fuzzed_data_provider, const std::optional< int64_t > &min, const std::optional< int64_t > &max) noexcept
Definition: util.cpp:34
std::vector< B > ConsumeRandomLengthByteVector(FuzzedDataProvider &fuzzed_data_provider, const std::optional< size_t > &max_length=std::nullopt) noexcept
Definition: util.h:63
COutPoint ProcessBlock(const NodeContext &node, const std::shared_ptr< CBlock > &block)
Returns the generated coin (or Null if the block was invalid).
Definition: mining.cpp:154
std::vector< std::shared_ptr< CBlock > > CreateBlockChain(size_t total_height, const CChainParams &params)
Create a blockchain, starting from genesis.
Definition: mining.cpp:44
@ ZEROS
Seed with a compile time constant of zeros.
static int setup(void)
Definition: tests.c:8289
assert(!tx.IsCoinBase())
FuzzedDataProvider & fuzzed_data_provider
Definition: fees.cpp:46