mirror of
https://github.com/bitcoin/bitcoin.git
synced 2026-04-12 16:47:58 +02:00
coins: introduce CCoinsViewCache::ResetGuard
CCoinsViewCache::CreateResetGuard returns a guard that calls Reset on the cache when the guard goes out of scope. This RAII pattern ensures the cache is always properly reset when it leaves current scope. Co-authored-by: l0rinc <pap.lorinc@gmail.com> Co-authored-by: sedited <seb.kung@gmail.com>
This commit is contained in:
@@ -1120,4 +1120,47 @@ BOOST_AUTO_TEST_CASE(ccoins_emplace_duplicate_keeps_usage_balanced)
|
||||
BOOST_CHECK(cache.AccessCoin(outpoint) == coin1);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(ccoins_reset_guard)
|
||||
{
|
||||
CCoinsViewTest root{m_rng};
|
||||
CCoinsViewCache root_cache{&root};
|
||||
uint256 base_best_block{m_rng.rand256()};
|
||||
root_cache.SetBestBlock(base_best_block);
|
||||
root_cache.Flush();
|
||||
|
||||
CCoinsViewCache cache{&root};
|
||||
|
||||
const COutPoint outpoint{Txid::FromUint256(m_rng.rand256()), m_rng.rand32()};
|
||||
|
||||
const Coin coin{CTxOut{m_rng.randrange(10), CScript{} << m_rng.randbytes(CScriptBase::STATIC_SIZE + 1)}, 1, false};
|
||||
cache.EmplaceCoinInternalDANGER(COutPoint{outpoint}, Coin{coin});
|
||||
|
||||
uint256 cache_best_block{m_rng.rand256()};
|
||||
cache.SetBestBlock(cache_best_block);
|
||||
|
||||
{
|
||||
const auto reset_guard{cache.CreateResetGuard()};
|
||||
BOOST_CHECK(cache.AccessCoin(outpoint) == coin);
|
||||
BOOST_CHECK(!cache.AccessCoin(outpoint).IsSpent());
|
||||
BOOST_CHECK_EQUAL(cache.GetCacheSize(), 1);
|
||||
BOOST_CHECK_EQUAL(cache.GetBestBlock(), cache_best_block);
|
||||
BOOST_CHECK(!root_cache.HaveCoinInCache(outpoint));
|
||||
}
|
||||
|
||||
BOOST_CHECK(cache.AccessCoin(outpoint).IsSpent());
|
||||
BOOST_CHECK_EQUAL(cache.GetCacheSize(), 0);
|
||||
BOOST_CHECK_EQUAL(cache.GetBestBlock(), base_best_block);
|
||||
BOOST_CHECK(!root_cache.HaveCoinInCache(outpoint));
|
||||
|
||||
// Using a reset guard again is idempotent
|
||||
{
|
||||
const auto reset_guard{cache.CreateResetGuard()};
|
||||
}
|
||||
|
||||
BOOST_CHECK(cache.AccessCoin(outpoint).IsSpent());
|
||||
BOOST_CHECK_EQUAL(cache.GetCacheSize(), 0);
|
||||
BOOST_CHECK_EQUAL(cache.GetBestBlock(), base_best_block);
|
||||
BOOST_CHECK(!root_cache.HaveCoinInCache(outpoint));
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_SUITE_END()
|
||||
|
||||
Reference in New Issue
Block a user