38const Coin EMPTY_COIN{};
56 struct CacheCoinSnapshot {
61 bool operator==(
const CacheCoinSnapshot&)
const =
default;
64 std::vector<CacheCoinSnapshot> ComputeCacheCoinsSnapshot()
const
66 std::vector<CacheCoinSnapshot> snapshot;
67 snapshot.reserve(cacheCoins.size());
69 for (
const auto& [outpoint, entry] : cacheCoins) {
70 snapshot.emplace_back(outpoint, entry.IsDirty(), entry.IsFresh(), entry.coin);
73 std::ranges::sort(snapshot, std::less<>{}, &CacheCoinSnapshot::outpoint);
77 mutable std::vector<CacheCoinSnapshot> m_expected_snapshot{ComputeCacheCoinsSnapshot()};
83 assert(ComputeCacheCoinsSnapshot() == m_expected_snapshot);
85 m_expected_snapshot = ComputeCacheCoinsSnapshot();
93std::shared_ptr<ThreadPool> g_thread_pool{std::make_shared<ThreadPool>(
"view_fuzz")};
94Mutex g_thread_pool_mutex;
98 LOCK(g_thread_pool_mutex);
107 coinbase.
vin.emplace_back();
124 seed_cache.AddCoin(outpoint, std::move(*coin),
true);
126 tx.
vin.emplace_back(outpoint);
140 static const auto testing_setup = MakeNoLogFileContext<>();
147 const bool is_db{
db !=
nullptr};
148 bool good_data{
true};
149 auto* original_backend{backend_coins_view};
164 Coin coin{random_coin};
167 const bool possible_overwrite{coins_view_cache.PeekCoin(outpoint) || fuzzed_data_provider.ConsumeBool()};
168 coins_view_cache.
AddCoin(outpoint, std::move(coin), possible_overwrite);
174 if (overlay && !overlay->AllInputsConsumed())
return;
179 coins_view_cache.
Sync();
187 if (is_db && best_block.IsNull()) best_block =
uint256::ONE;
195 if (best_block.IsNull()) {
207 coins_view_cache.
Uncache(random_out_point);
212 if (use_original_backend && backend_coins_view != original_backend) {
220 coins_view_cache.
SetBackend(*backend_coins_view);
223 const std::optional<COutPoint> opt_out_point = ConsumeDeserializable<COutPoint>(
fuzzed_data_provider);
224 if (!opt_out_point) {
228 random_out_point = *opt_out_point;
236 random_coin = *opt_coin;
240 if (!opt_mutable_transaction) {
244 random_mutable_transaction = *opt_mutable_transaction;
248 sentinel.second.SelfRef(sentinel);
249 size_t dirty_count{0};
256 coins_cache_entry.
coin = random_coin;
263 coins_cache_entry.
coin = *opt_coin;
268 auto it{coins_map.emplace(random_out_point, std::move(coins_cache_entry)).first};
271 dirty_count += dirty;
277 if (is_db && best_block.IsNull()) best_block =
uint256::ONE;
278 coins_view_cache.
BatchWrite(cursor, best_block);
283 bool expected_code_path =
false;
285 (void)coins_view_cache.Cursor();
286 }
catch (
const std::logic_error&) {
287 expected_code_path =
true;
289 assert(expected_code_path);
290 (void)coins_view_cache.DynamicMemoryUsage();
291 (void)coins_view_cache.EstimateSize();
292 (void)coins_view_cache.GetBestBlock();
293 (void)coins_view_cache.GetCacheSize();
294 (void)coins_view_cache.GetHeadBlocks();
295 (void)coins_view_cache.HaveInputs(
CTransaction{random_mutable_transaction});
299 if (is_db && backend_coins_view == original_backend) {
300 assert(backend_coins_view->Cursor());
302 (void)backend_coins_view->EstimateSize();
303 (void)backend_coins_view->GetBestBlock();
304 (void)backend_coins_view->GetHeadBlocks();
311 const CTransaction transaction{random_mutable_transaction};
312 bool is_spent =
false;
313 for (
const CTxOut& tx_out : transaction.vout) {
314 if (Coin{tx_out, 0, transaction.IsCoinBase()}.IsSpent()) {
324 const bool check_for_overwrite{transaction.IsCoinBase() || [&] {
325 for (uint32_t i{0}; i < transaction.vout.size(); ++i) {
326 if (coins_view_cache.PeekCoin(
COutPoint{transaction.GetHash(), i}))
return true;
330 AddCoins(coins_view_cache, transaction, height, check_for_overwrite);
338 const CTransaction transaction{random_mutable_transaction};
354 const CTransaction transaction{random_mutable_transaction};
363 const CTransaction transaction{random_mutable_transaction};
370 if (!transaction.vin.empty() && (
flags & SCRIPT_VERIFY_WITNESS) != 0 && (
flags & SCRIPT_VERIFY_P2SH) == 0) {
383 const Coin& coin_using_access_coin = coins_view_cache.AccessCoin(random_out_point);
384 const bool exists_using_access_coin = !(coin_using_access_coin == EMPTY_COIN);
385 const bool exists_using_have_coin = coins_view_cache.HaveCoin(random_out_point);
386 const bool exists_using_have_coin_in_cache = coins_view_cache.HaveCoinInCache(random_out_point);
387 if (
auto coin{coins_view_cache.GetCoin(random_out_point)}) {
388 assert(*coin == coin_using_access_coin);
389 assert(exists_using_access_coin && exists_using_have_coin_in_cache && exists_using_have_coin);
391 assert(!exists_using_access_coin && !exists_using_have_coin_in_cache && !exists_using_have_coin);
394 std::optional<Coin> coin_in_backend;
395 bool exists_using_have_coin_in_backend;
398 coin_in_backend = backend_coins_view->PeekCoin(random_out_point);
399 exists_using_have_coin_in_backend = coin_in_backend.has_value();
401 exists_using_have_coin_in_backend = backend_coins_view->HaveCoin(random_out_point);
402 coin_in_backend = backend_coins_view->GetCoin(random_out_point);
404 if (!coin_using_access_coin.
IsSpent() && exists_using_have_coin_in_backend) {
405 assert(exists_using_have_coin);
407 if (coin_in_backend) {
408 assert(exists_using_have_coin_in_backend);
412 assert(!exists_using_have_coin_in_backend);
429 .cache_bytes = 1_MiB,
449 const auto reset_guard{coins_view_cache.StartFetching(block)};
460 .cache_bytes = 1_MiB,
469 const auto reset_guard{coins_view_cache.StartFetching(block)};
bool MoneyRange(const CAmount &nValue)
int64_t CAmount
Amount in satoshis (Can be negative)
static constexpr int32_t DEFAULT_PREVOUTFETCH_THREADS
std::vector< CTransactionRef > vtx
void SetBackend(CCoinsView &in_view)
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 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)
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
void BatchWrite(CoinsViewCacheCursor &cursor, const uint256 &block_hash) override
Do a bulk modification (multiple Coin changes + BestBlock change).
std::optional< Coin > PeekCoin(const COutPoint &outpoint) const override
Retrieve the Coin (unspent transaction output) for a given outpoint, without caching results.
void EmplaceCoinInternalDANGER(COutPoint &&outpoint, Coin &&coin)
Emplace a coin into cacheCoins without performing any checks, marking the emplaced coin as dirty.
CCoinsView backed by the coin database (chainstate/)
Pure abstract view on the open txout dataset.
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.
An output of a transaction.
CTxOut out
unspent transaction output
bool IsSpent() const
Either this coin never existed (see e.g.
bool fCoinBase
whether containing transaction was a coinbase
uint32_t nHeight
at which height this containing transaction was included in the active block chain
static CoinsViewEmpty & Get()
CCoinsViewCache subclass that asynchronously fetches most block input prevouts in parallel during Con...
T ConsumeIntegralInRange(T min, T max)
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)
Utility function to add all of a transaction's outputs to a cache.
std::pair< const COutPoint, CCoinsCacheEntry > CoinsCachePair
std::unordered_map< COutPoint, CCoinsCacheEntry, SaltedOutpointHasher, 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...
CCoinsMap::allocator_type::ResourceType CCoinsMapMemoryResource
void TestCoinsView(FuzzedDataProvider &fuzzed_data_provider, CCoinsViewCache &coins_view_cache, CCoinsView *backend_coins_view)
FUZZ_TARGET(coins_view,.init=initialize_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,...
static constexpr TransactionSerParams TX_WITH_WITNESS
static CTransactionRef MakeTransactionRef(Tx &&txIn)
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.
Cursor for iterating over the linked list of flagged entries in CCoinsViewCache.
User-controlled performance and debug options.
Application-specific storage settings.
fs::path path
Location in the filesystem where leveldb data will be stored.
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
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)
@ ZEROS
Seed with a compile time constant of zeros.
static void StartPoolIfNeeded()
#define EXCLUSIVE_LOCKS_REQUIRED(...)
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.
FuzzedDataProvider & fuzzed_data_provider