49 struct CacheCoinSnapshot {
54 bool operator==(
const CacheCoinSnapshot&)
const =
default;
57 std::vector<CacheCoinSnapshot> ComputeCacheCoinsSnapshot()
const
59 std::vector<CacheCoinSnapshot> snapshot;
60 snapshot.reserve(cacheCoins.size());
62 for (
const auto& [outpoint, entry] : cacheCoins) {
63 snapshot.emplace_back(outpoint, entry.IsDirty(), entry.IsFresh(), entry.coin);
66 std::ranges::sort(snapshot, std::less<>{}, &CacheCoinSnapshot::outpoint);
70 mutable std::vector<CacheCoinSnapshot> m_expected_snapshot{ComputeCacheCoinsSnapshot()};
73 void BatchWrite(CoinsViewCacheCursor& cursor,
const uint256& block_hash)
override
76 assert(ComputeCacheCoinsSnapshot() == m_expected_snapshot);
78 m_expected_snapshot = ComputeCacheCoinsSnapshot();
86std::shared_ptr<ThreadPool> g_thread_pool{std::make_shared<ThreadPool>(
"view_fuzz")};
98 coinbase.
vin.emplace_back();
99 block.
vtx.push_back(MakeTransactionRef(coinbase));
115 seed_cache.
AddCoin(outpoint, std::move(*coin),
true);
117 tx.
vin.emplace_back(outpoint);
120 block.
vtx.push_back(MakeTransactionRef(tx));
138 const bool is_db{
db !=
nullptr};
139 bool good_data{
true};
140 auto* original_backend{backend_coins_view};
148 fuzzed_data_provider,
154 Coin coin{random_coin};
157 const bool possible_overwrite{coins_view_cache.
PeekCoin(outpoint) || fuzzed_data_provider.
ConsumeBool()};
158 coins_view_cache.
AddCoin(outpoint, std::move(coin), possible_overwrite);
164 if (overlay && !overlay->AllInputsConsumed())
return;
169 coins_view_cache.
Sync();
185 if (best_block.
IsNull()) {
194 (void)coins_view_cache.
SpendCoin(random_out_point, fuzzed_data_provider.
ConsumeBool() ? &move_to :
nullptr);
197 coins_view_cache.
Uncache(random_out_point);
201 const bool use_original_backend{fuzzed_data_provider.
ConsumeBool()};
202 if (use_original_backend && backend_coins_view != original_backend) {
210 coins_view_cache.
SetBackend(*backend_coins_view);
214 if (!opt_out_point) {
218 random_out_point = *opt_out_point;
226 random_coin = *opt_coin;
230 if (!opt_mutable_transaction) {
234 random_mutable_transaction = *opt_mutable_transaction;
238 sentinel.second.SelfRef(sentinel);
239 size_t dirty_count{0};
245 coins_cache_entry.
coin = random_coin;
252 coins_cache_entry.
coin = *opt_coin;
255 bool fresh{!coins_view_cache.
PeekCoin(random_out_point) && fuzzed_data_provider.
ConsumeBool()};
256 bool dirty{fresh || fuzzed_data_provider.
ConsumeBool()};
257 auto it{coins_map.emplace(random_out_point, std::move(coins_cache_entry)).first};
260 dirty_count += dirty;
267 coins_view_cache.
BatchWrite(cursor, best_block);
281 if (is_db && backend_coins_view == original_backend) {
291 fuzzed_data_provider,
293 const CTransaction transaction{random_mutable_transaction};
294 bool is_spent =
false;
295 for (
const CTxOut& tx_out : transaction.
vout) {
305 const int height{int(fuzzed_data_provider.
ConsumeIntegral<uint32_t>() >> 1)};
306 const bool check_for_overwrite{transaction.
IsCoinBase() || [&] {
307 for (uint32_t i{0}; i < transaction.
vout.size(); ++i) {
312 AddCoins(coins_view_cache, transaction, height, check_for_overwrite);
320 const CTransaction transaction{random_mutable_transaction};
336 const CTransaction transaction{random_mutable_transaction};
345 const CTransaction transaction{random_mutable_transaction};
365 const Coin& coin_using_access_coin = coins_view_cache.
AccessCoin(random_out_point);
366 const bool exists_using_access_coin = !coin_using_access_coin.
IsSpent();
367 const bool exists_using_have_coin = coins_view_cache.
HaveCoin(random_out_point);
368 const bool exists_using_have_coin_in_cache = coins_view_cache.
HaveCoinInCache(random_out_point);
369 if (
auto coin{coins_view_cache.
GetCoin(random_out_point)}) {
370 assert(*coin == coin_using_access_coin);
371 assert(exists_using_access_coin && exists_using_have_coin_in_cache && exists_using_have_coin);
373 assert(!exists_using_access_coin && !exists_using_have_coin_in_cache && !exists_using_have_coin);
376 std::optional<Coin> coin_in_backend;
377 bool exists_using_have_coin_in_backend;
380 coin_in_backend = backend_coins_view->
PeekCoin(random_out_point);
381 exists_using_have_coin_in_backend = coin_in_backend.has_value();
383 exists_using_have_coin_in_backend = backend_coins_view->
HaveCoin(random_out_point);
384 coin_in_backend = backend_coins_view->
GetCoin(random_out_point);
386 if (!coin_using_access_coin.
IsSpent() && exists_using_have_coin_in_backend) {
387 assert(exists_using_have_coin);
389 if (coin_in_backend) {
390 assert(exists_using_have_coin_in_backend);
394 assert(!exists_using_have_coin_in_backend);
411 .cache_bytes = 1_MiB,
416 TestCoinsView(fuzzed_data_provider, coins_view_cache, &backend_coins_view);
430 CBlock block{BuildRandomBlock(fuzzed_data_provider, backend_cache)};
431 const auto reset_guard{coins_view_cache.
StartFetching(block)};
432 TestCoinsView(fuzzed_data_provider, coins_view_cache, &backend_cache);
442 .cache_bytes = 1_MiB,
447 TestCoinsView(fuzzed_data_provider, backend_cache, &backend_base_coins_view);
449 CBlock block{BuildRandomBlock(fuzzed_data_provider, backend_base_coins_view)};
451 const auto reset_guard{coins_view_cache.
StartFetching(block)};
452 TestCoinsView(fuzzed_data_provider, coins_view_cache, &backend_cache);
454 TestCoinsView(fuzzed_data_provider, backend_cache, &backend_base_coins_view);
bool MoneyRange(const CAmount &nValue)
int64_t CAmount
Amount in satoshis (Can be negative).
constexpr int32_t DEFAULT_PREVOUTFETCH_THREADS
std::vector< CTransactionRef > vtx
size_t EstimateSize() const override
Estimate database size.
void SetBackend(CCoinsView &in_view)
std::vector< uint256 > GetHeadBlocks() const override
CCoinsView that adds a memory cache for transactions to another CCoinsView.
void Sync()
Push the modifications applied to this cache to its base while retaining the contents of this cache (...
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
ResetGuard CreateResetGuard() noexcept
Create a scoped guard that will call Reset() on this cache when it goes out of scope.
void Uncache(const COutPoint &outpoint)
Removes the UTXO with the given outpoint from the cache, if it is not modified.
void EmplaceCoinInternalDANGER(const COutPoint &outpoint, Coin &&coin)
Emplace a coin into cacheCoins without performing any checks, marking the emplaced coin as dirty.
bool HaveInputs(const CTransaction &tx) const
Check whether all prevouts of the transaction are present in the UTXO set represented by this view.
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool possible_overwrite)
Add a coin.
CCoinsViewCache(CCoinsView *in_base, bool deterministic=false)
virtual void Flush(bool reallocate_cache=true)
Push the modifications applied to this cache to its base and wipe local state.
void SetBestBlock(const uint256 &block_hash)
unsigned int GetCacheSize() const
Size of the cache (in number of transaction outputs).
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
bool HaveCoinInCache(const COutPoint &outpoint) const
Check if we have the given utxo already loaded in this cache.
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes).
void BatchWrite(CoinsViewCacheCursor &cursor, const uint256 &block_hash) override
std::optional< Coin > PeekCoin(const COutPoint &outpoint) const override
bool HaveCoin(const COutPoint &outpoint) const override
std::optional< Coin > GetCoin(const COutPoint &outpoint) const override
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
CCoinsView backed by the coin database (chainstate/).
Pure abstract view on the open txout dataset.
virtual size_t EstimateSize() const =0
Estimate database size.
virtual std::vector< uint256 > GetHeadBlocks() const =0
virtual std::optional< Coin > PeekCoin(const COutPoint &outpoint) const =0
virtual std::optional< Coin > GetCoin(const COutPoint &outpoint) const =0
virtual bool HaveCoin(const COutPoint &outpoint) const =0
virtual uint256 GetBestBlock() const =0
Retrieve the block hash whose state this CCoinsView currently represents.
An outpoint - a combination of a transaction hash and an index n into its vout.
The basic transaction that is broadcasted on the network and contained in blocks.
const std::vector< CTxOut > vout
const std::vector< CTxIn > vin
An output of a transaction.
bool IsSpent() const
Either this coin never existed (see e.g.
static CoinsViewEmpty & Get()
CCoinsViewCache subclass that asynchronously fetches most block input prevouts in parallel during Con...
ResetGuard StartFetching(const CBlock &block LIFETIMEBOUND) noexcept
Start fetching inputs from block.
T ConsumeIntegralInRange(T min, T max)
SipHash-1-3-UJ based hasher for the coins cache and related coins containers.
constexpr bool IsNull() const
static constexpr script_verify_flags from_int(value_type f)
static transaction_identifier FromUint256(const uint256 &id)
void AddCoins(CCoinsViewCache &cache, const CTransaction &tx, int nHeight, bool check_for_overwrite)
std::unordered_map< COutPoint, CCoinsCacheEntry, SaltedCoinsCacheHasher, std::equal_to< COutPoint >, PoolAllocator< CoinsCachePair, sizeof(CoinsCachePair)+sizeof(void *) *4 > > CCoinsMap
PoolAllocator's MAX_BLOCK_SIZE_BYTES parameter here uses sizeof the data, and adds the size of 4 poin...
std::pair< const COutPoint, CCoinsCacheEntry > CoinsCachePair
CCoinsMap::allocator_type::ResourceType CCoinsMapMemoryResource
void TestCoinsView(FuzzedDataProvider &fuzzed_data_provider, CCoinsViewCache &coins_view_cache, CCoinsView *backend_coins_view)
void initialize_coins_view()
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
#define LIMITED_WHILE(condition, limit)
Can be used to limit a theoretically unbounded loop.
bool CheckTxInputs(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &inputs, int nSpendHeight, CAmount &txfee)
Check whether all inputs of this transaction are valid (no double spends and amounts) This does not m...
bool operator==(const CNetAddr &a, const CNetAddr &b)
TxValidationState ValidateInputsStandardness(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check transaction inputs.
bool IsWitnessStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check if the transaction is over standard P2WSH resources limit: 3600bytes witnessScript size,...
constexpr TransactionSerParams TX_WITH_WITNESS
std::unique_ptr< T > MakeNoLogFileContext(const ChainType chain_type=ChainType::REGTEST, TestOpts opts={})
Make a test setup that has disk access to the debug.log file disabled.
A Coin in one level of the coins database caching hierarchy.
static void SetFresh(CoinsCachePair &pair, CoinsCachePair &sentinel) noexcept
static void SetDirty(CoinsCachePair &pair, CoinsCachePair &sentinel) noexcept
A mutable version of CTransaction.
Txid GetHash() const
Compute the hash of this CMutableTransaction.
CoinsViewCacheCursor(size_t &dirty_count LIFETIMEBOUND, CoinsCachePair &sentinel LIFETIMEBOUND, CCoinsMap &map LIFETIMEBOUND, bool will_erase) noexcept
User-controlled performance and debug options.
Application-specific storage settings.
#define WITH_LOCK(cs, code)
SeedRandomStateForTest(SeedRand::ZEROS)
bool ContainsSpentInput(const CTransaction &tx, const CCoinsViewCache &inputs) noexcept
uint256 ConsumeUInt256(FuzzedDataProvider &fuzzed_data_provider) noexcept
size_t CallOneOf(FuzzedDataProvider &fuzzed_data_provider, Callables... callables)
std::optional< T > ConsumeDeserializable(FuzzedDataProvider &fuzzed_data_provider, const P ¶ms, const std::optional< size_t > &max_length=std::nullopt) noexcept
@ ZEROS
Seed with a compile time constant of zeros.
transaction_identifier< false > Txid
Txid commits to all transaction fields except the witness.
bool CheckTransaction(const CTransaction &tx, TxValidationState &state)
int64_t GetTransactionSigOpCost(const CTransaction &tx, const CCoinsViewCache &inputs, script_verify_flags flags)
Compute total signature operation cost of a transaction.
unsigned int GetP2SHSigOpCount(const CTransaction &tx, const CCoinsViewCache &inputs)
Count ECDSA signature operations in pay-to-script-hash inputs.