CoinsViewOverlay

CCoinsViewCache subclass that asynchronously fetches most block input prevouts in parallel during ConnectBlock without mutating the base cache.

Synopsis

Declared in <coins.h>

class CoinsViewOverlay
    : public CCoinsViewCache

Description

Only used in ConnectBlock to pass as an ephemeral view that can be reset if the block is invalid. It provides the same interface as CCoinsViewCache. It adds an additional StartFetching method to provide the block.

When a block is passed to StartFetching, the inputs of the block are flattened into a vector of InputToFetch objects. StartFetching then submits worker tasks to a ThreadPool and keeps the returned futures alive until fetching is stopped.

ProcessInput() atomically fetches and increments m_input_head, so each thread can only access a single element of the m_inputs vector at a time. Workers race to claim inputs, so they may fetch elements in any order. If the fetched index is greater than or equal to the size of m_inputs, no more inputs can be fetched and false is returned.

The worker claims the InputToFetch at this index, fetches the coin from the base cache and moves it into the InputToFetch object. The ready flag is then set with a release memory order. This allows the ready flag to be used as a memory fence, guaranteeing the coin being written to the object will have happened before another thread tests the flag with an acquire memory order. This assumes all base->PeekCoin() paths are safe for concurrent readers and do not mutate lower cache layers.

When a coin is requested from the cache on the main thread and is not already in cacheCoins map, FetchCoinFromBase checks whether the next unconsumed entry in m_inputs has the requested outpoint. On a match, m_input_tail is advanced and the entry's ready flag is waited on with an acquire memory order until a worker has finished fetching it. The coin is then moved out and returned. Since the main thread is the only consumer of validation results, it blocks on the specific input it needs rather than racing workers for other inputs.

StopFetching() is called in Flush() and in Reset() (the per-block teardown) so workers stop before the block they reference goes away. It stops fetching by moving m_input_head to the end of m_inputs (so workers quickly exit), then waits for all futures to complete and clears the per-block state (m_inputs and the head/tail counters).

Workers advance m_input_head to fetch inputs. Main thread advances m_input_tail to consume.

Before workers start:

m_input_head m_input_tail │ ▼ ┌─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┐ m_inputs: │ waiting │ waiting │ waiting │ waiting │ waiting │ waiting │ waiting │ waiting │ waiting │ │ │ │ │ │ │ │ │ │ │ └─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┘

After workers start:

Worker 2 Worker 0 Worker 3 Worker 1 m_input_head │ │ │ │ │ ▼ ▼ ▼ ▼ ▼ ┌─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┐ m_inputs: │ ready │ ready │fetching │ ready │fetching │fetching │fetching │ waiting │ waiting │ │consumed │ ✓ │ ● │ ✓ │ ● │ ● │ ● │ │ │ └─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┘ ▲ │ m_input_tail

Base Classes

NameDescription
CCoinsViewCacheCCoinsView that adds a memory cache for transactions to another CCoinsView

Types

NameDescription
ResetGuard Scope guard that calls Reset() on its cache when it goes out of scope.

Member Functions

NameDescription
CoinsViewOverlay [constructor]Construct an overlay that fetches block input prevouts in parallel.
~CoinsViewOverlay [destructor] [virtual]Stop fetching before the overlay is destroyed.
AccessCoin Return a reference to Coin in the cache, or coinEmpty if not found. This is more efficient than GetCoin.
AddCoin Add a coin. Set possible_overwrite to true if an unspent version may already exist in the cache.
AllInputsConsumed Verify that all parallel fetched input prevouts have been consumed.
BatchWrite [virtual]Write flagged coins from a cursor into this cache and update the best block.
CreateResetGuard Create a scoped guard that will call Reset() on this cache when it goes out of scope.
DynamicMemoryUsage Calculate the size of the cache (in bytes)
EmplaceCoinInternalDANGER Emplace a coin into cacheCoins without performing any checks, marking the emplaced coin as dirty.
EstimateSize [virtual]Forward the size estimate to the backing view.
Flush [virtual]Warn if prefetched inputs went unconsumed, stop fetching, then flush to the base cache.
GetBestBlock [virtual]Retrieve the best block hash this cache represents.
GetCacheSize Size of the cache (in number of transaction outputs)
GetCoin [virtual]Retrieve a coin, populating this cache on a hit.
GetDirtyCount Number of dirty cache entries (transaction outputs)
GetHeadBlocks [virtual]Forward the head-blocks query to the backing view.
HaveCoin [virtual]Check whether an outpoint is unspent, possibly populating this cache.
HaveCoinInCache Check if we have the given utxo already loaded in this cache. The semantics are the same as HaveCoin(), but no calls to the backing CCoinsView are made.
HaveInputs Check whether all prevouts of the transaction are present in the UTXO set represented by this view
PeekCoin [virtual]Retrieve a coin without populating this cache.
SanityCheck Run an internal sanity check on the cache data structure. */
SetBackend Replace the backing view.
SetBestBlock Set the best block hash this cache represents.
SpendCoin Spend a coin. Pass moveto in order to get the deleted data. If no unspent output exists for the passed outpoint, this call has no effect.
StartFetching Start fetching inputs from block.
Sync Push the modifications applied to this cache to its base while retaining the contents of this cache (except for spent coins, which we erase). Failure to call this method or Flush() before destruction will cause the changes to be forgotten.
Uncache Removes the UTXO with the given outpoint from the cache, if it is not modified.

Protected Member Functions

NameDescription
FetchCoinFromBase [virtual]Fetch the coin from base. Used for cache misses in FetchCoin.
Reset [virtual]Stop any in-progress fetching, then discard this overlay's modifications.

Protected Data Members

NameDescription
base The underlying view that all calls are forwarded to.
cacheCoins The map of cached coins, keyed by outpoint.
cachedCoinsUsage Cached dynamic memory usage for the inner Coin objects.
m_block_hash Make mutable so that we can "fill the cache" even from Get-methods declared as "const".
m_cache_coins_memory_resource Memory resource that backs the pool allocator used by cacheCoins.
m_dirty_count Running count of dirty Coin cache entries.
m_sentinel The starting sentinel of the flagged entry circular doubly linked list.

Non-Member Functions

NameDescription
AccessByTxidUtility function to find any unspent output with a given txid. This function can be quite expensive because in the event of a transaction which is not found in the cache, it can cause up to MAX_OUTPUTS_PER_BLOCK lookups to database, so it should be used with care.
AddCoinsUtility function to add all of a transaction's outputs to a cache. When check is false, this assumes that overwrites are only possible for coinbase transactions. When check is true, the underlying view may be queried to determine whether an addition is an overwrite.