5#include <chainparams.h>
29#include <boost/test/unit_test.hpp>
71 const uint256 snapshot_blockhash = active_tip->GetBlockHash();
74 1 << 23,
true,
false);
77 c2.InitCoinsCache(1 << 23);
78 c2.CoinsTip().SetBestBlock(active_tip->GetBlockHash());
118 size_t max_cache = 10000;
122 std::vector<Chainstate*> chainstates;
127 chainstates.push_back(&c1);
130 c1.InitCoinsCache(1 << 23);
131 manager.MaybeRebalanceCaches();
141 chainstates.push_back(&c2);
143 1 << 23,
true,
false);
156 c2.InitCoinsCache(1 << 23);
157 manager.MaybeRebalanceCaches();
162 BOOST_CHECK_CLOSE(
double(c2.m_coinstip_cache_size_bytes), max_cache * 0.95, 1);
163 BOOST_CHECK_CLOSE(
double(c2.m_coinsdb_cache_size_bytes), max_cache * 0.95, 1);
176 .coins_db_in_memory =
false,
177 .block_tree_db_in_memory =
false,
194 size_t initial_total_coins{100};
201 size_t total_coins{0};
221 constexpr int snapshot_height = 110;
224 initial_total_coins += 10;
297 int chains_tested{0};
299 for (
const auto& chainstate : chainman.m_chainstates) {
300 BOOST_TEST_MESSAGE(
"Checking coins in " << chainstate->ToString());
306 size_t total_coins{0};
323 constexpr size_t new_coins{100};
324 mineBlocks(new_coins);
328 size_t coins_in_active{0};
329 size_t coins_in_background{0};
330 size_t coins_missing_from_background{0};
332 for (
const auto& chainstate : chainman.m_chainstates) {
333 BOOST_TEST_MESSAGE(
"Checking coins in " << chainstate->ToString());
340 (is_background ? coins_in_background : coins_in_active)++;
341 }
else if (is_background) {
342 coins_missing_from_background++;
358 loaded_snapshot_blockhash);
359 return std::make_tuple(&validation_chainstate, &snapshot_chainstate);
370 BOOST_TEST_MESSAGE(
"Simulating node restart");
373 for (
const auto&
cs : chainman.m_chainstates) {
374 if (
cs->CanFlushToDisk())
cs->ForceFlushStateToDisk();
381 chainman.ResetChainstates();
390 const BlockManager::Options blockman_opts{
391 .chainparams = chainman_opts.chainparams,
392 .blocks_dir = m_args.GetBlocksDirPath(),
393 .notifications = chainman_opts.notifications,
396 .cache_bytes = m_kernel_cache_sizes.block_tree_db,
397 .memory_only = m_block_tree_db_in_memory,
412 this->SetupSnapshot();
433 const int expected_assumed_valid{20};
434 const int last_assumed_valid_idx{111};
435 const int assumed_valid_start_idx = last_assumed_valid_idx - expected_assumed_valid;
446 auto reload_all_block_indexes = [&]() {
452 for (
const auto&
cs : chainman.m_chainstates) {
453 cs->ClearBlockIndexCandidates();
461 reload_all_block_indexes();
470 if (i < last_assumed_valid_idx && i >= assumed_valid_start_idx) {
473 index->m_chain_tx_count = 0;
479 if (i == (assumed_valid_start_idx - 1)) {
480 validated_tip = index;
483 if (i == last_assumed_valid_idx - 1) {
484 assumed_base = index;
495 cs2.m_chain.SetTip(*assumed_base);
505 reload_all_block_indexes();
553 BOOST_CHECK_EQUAL(cs2.setBlockIndexCandidates.size(), num_indexes - last_assumed_valid_idx + 1);
563 this->SetupSnapshot();
593 BOOST_TEST_MESSAGE(
"Performing Load/Verify/Activate of chainstate");
596 this->LoadVerifyActivateChainstate();
617 "Ensure we can mine blocks on top of the initialized snapshot chainstate");
634 this->SetupSnapshot();
653 res =
WITH_LOCK(
::cs_main,
return chainman.MaybeValidateSnapshot(validated_cs, active_cs));
666 res =
WITH_LOCK(
::cs_main,
return chainman.MaybeValidateSnapshot(validated_cs, active_cs));
670 fs::path snapshot_invalid_dir =
gArgs.
GetDataDirNet() /
"chainstate_snapshot_INVALID";
680 BOOST_TEST_MESSAGE(
"Performing Load/Verify/Activate of chainstate");
684 this->LoadVerifyActivateChainstate();
704 "Ensure we can mine blocks on top of the \"new\" IBD chainstate");
714 auto chainstates = this->SetupSnapshot();
715 Chainstate& validation_chainstate = *std::get<0>(chainstates);
716 Chainstate& unvalidated_cs = *std::get<1>(chainstates);
724 return validation_chainstate.
CoinsTip());
737 res =
WITH_LOCK(
::cs_main,
return chainman.MaybeValidateSnapshot(validation_chainstate, unvalidated_cs));
745 BOOST_CHECK(!chainman.m_chainstates[0]->SnapshotBase());
747 BOOST_CHECK(chainman.m_chainstates[1]->SnapshotBase());
750 fs::path snapshot_invalid_dir =
gArgs.
GetDataDirNet() /
"chainstate_snapshot_INVALID";
758 BOOST_TEST_MESSAGE(
"Performing Load/Verify/Activate of chainstate");
762 this->LoadVerifyActivateChainstate();
775 "Ensure we can mine blocks on top of the \"new\" IBD chainstate");
784template <
typename Options>
786 const std::vector<const char*>&
args)
788 const auto argv{
Cat({
"ignore"},
args)};
801 auto get_opts = [&](
const std::vector<const char*>&
args) {
806 .notifications = notifications};
810 auto get_valid_opts = [&](
const std::vector<const char*>&
args) {
811 const auto result{get_opts(
args)};
817 BOOST_CHECK(!get_valid_opts({}).assumed_valid_block);
823 std::string assume_valid{
"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"};
827 BOOST_CHECK(!get_opts({
"-assumevalid=01234567890123456789012345678901234567890123456789012345678901234"}));
830 BOOST_CHECK(!get_valid_opts({}).minimum_chain_work);
835 std::string minimum_chainwork{
"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"};
839 BOOST_CHECK(!get_opts({
"-minimumchainwork=01234567890123456789012345678901234567890123456789012345678901234"}));
arith_uint256 UintToArith256(const uint256 &a)
@ BLOCK_VALID_TREE
All parent headers found, difficulty matches, timestamp >= median previous.
const CChainParams & Params()
Return the currently selected parameters.
#define Assert(val)
Identity function.
bool ParseParameters(int argc, const char *const argv[], std::string &error)
fs::path GetDataDirNet() const
Get data directory path with appended network identifier.
Non-refcounted RAII wrapper for FILE*.
The block chain is a tree shaped structure starting with the genesis block at the root,...
uint64_t m_chain_tx_count
(memory only) Number of transactions in the chain up to and including this block.
uint256 GetBlockHash() const
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
void SetTip(CBlockIndex &block)
Set/initialize a chain with a given tip.
int Height() const
Return the maximal height in the chain.
std::optional< AssumeutxoData > AssumeutxoForHeight(int height) const
CCoinsView that adds a memory cache for transactions to another CCoinsView.
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool possible_overwrite)
Add a coin.
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transaction outputs)
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
An outpoint - a combination of a transaction hash and an index n into its vout.
Chainstate stores and provides an API to update our local knowledge of the current best chain.
CChain m_chain
The current chain of blockheaders we consult and build on.
size_t m_coinstip_cache_size_bytes
The cache size of the in-memory coins view.
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
size_t m_coinsdb_cache_size_bytes
The cache size of the on-disk coins view.
const std::optional< uint256 > m_from_snapshot_blockhash
The blockhash which is the base of the snapshot this chainstate was created from.
bool DisconnectTip(BlockValidationState &state, DisconnectedBlockTransactions *disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Disconnect m_chain's tip.
std::set< CBlockIndex *, node::CBlockIndexWorkComparator > setBlockIndexCandidates
The set of all CBlockIndex entries that have as much work as our current tip or more,...
CoinsCacheSizeState GetCoinsCacheSizeState() EXCLUSIVE_LOCKS_REQUIRED(CoinsCacheSizeState GetCoinsCacheSizeState(size_t max_coins_cache_size_bytes, size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(std::string ToString() EXCLUSIVE_LOCKS_REQUIRED(RecursiveMutex * MempoolMutex() const LOCK_RETURNED(m_mempool -> cs)
Dictates whether we need to flush the cache to disk or not.
Interface for managing multiple Chainstate objects, where each chainstate is associated with chainsta...
Chainstate * HistoricalChainstate() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Return historical chainstate targeting a specific block, if any.
size_t m_total_coinstip_cache
The total number of bytes available for us to use across all in-memory coins caches.
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Chainstate & ActiveChainstate() const
Alternatives to CurrentChainstate() used by older code to query latest chainstate information without...
SnapshotCompletionResult MaybeValidateSnapshot(Chainstate &validated_cs, Chainstate &unvalidated_cs) EXCLUSIVE_LOCKS_REQUIRED(Chainstate & CurrentChainstate() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Try to validate an assumeutxo snapshot by using a validated historical chainstate targeted at the sna...
size_t m_total_coinsdb_cache
The total number of bytes available for us to use across all leveldb coins databases.
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the block tree and coins database from disk, initializing state if we're running with -reindex.
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
void ResetBlockSequenceCounters() EXCLUSIVE_LOCKS_REQUIRED(
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
CTxOut out
unspent transaction output
uint32_t nHeight
at which height this containing transaction was included in the active block chain
DisconnectedBlockTransactions.
256-bit unsigned big integer.
A base class defining functions for notifying about certain kernel events.
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
void assign(size_type n, const T &val)
static transaction_identifier FromUint256(const uint256 &id)
static const uint256 ZERO
static std::optional< uint256 > FromHex(std::string_view str)
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
BOOST_FIXTURE_TEST_SUITE(cuckoocache_tests, BasicTestingSetup)
Test Suite for CuckooCache.
BOOST_AUTO_TEST_SUITE_END()
static const unsigned int MAX_DISCONNECTED_TX_POOL_BYTES
Maximum bytes for transactions to store for processing during reorg.
static bool exists(const path &p)
util::Result< void > ApplyArgsManOptions(const ArgsManager &args, BlockManager::Options &opts)
std::optional< fs::path > FindAssumeutxoChainstateDir(const fs::path &data_dir)
Return a path to the snapshot-based chainstate dir, if one exists.
std::optional< uint256 > ReadSnapshotBaseBlockhash(fs::path chaindir)
bilingual_str ErrorString(const Result< T > &result)
#define BOOST_CHECK_EQUAL(v1, v2)
#define BOOST_CHECK(expr)
std::shared_ptr< const CTransaction > CTransactionRef
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
Application-specific storage settings.
fs::path path
Location in the filesystem where leveldb data will be stored.
std::tuple< Chainstate *, Chainstate * > SetupSnapshot()
ChainstateManager & SimulateNodeRestart()
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
Testing setup that configures a complete environment.
An options struct for ChainstateManager, more ergonomically referred to as ChainstateManager::Options...
const CChainParams & chainparams
std::unique_ptr< ValidationSignals > validation_signals
Issues calls about blocks and transactions.
std::unique_ptr< ChainstateManager > chainman
std::unique_ptr< node::Warnings > warnings
Manages all the node warnings.
std::function< bool()> shutdown_request
Function to request a shutdown.
std::unique_ptr< KernelNotifications > notifications
Issues blocking calls about sync status, errors and warnings.
util::SignalInterrupt * shutdown_signal
Interrupt object used to track whether node shutdown was requested.
std::atomic< int > exit_status
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
static bool CreateAndActivateUTXOSnapshot(TestingSetup *fixture, F malleation=NoMalleation, bool reset_chainstate=false, bool in_memory_chainstate=false)
Create and activate a UTXO snapshot, optionally providing a function to malleate the snapshot.
#define ASSERT_DEBUG_LOG(message)
consteval auto _(util::TranslatedLiteral str)
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
@ VALIDATED
Every block in the chain has been validated.
@ UNVALIDATED
Blocks after an assumeutxo snapshot have been validated but the snapshot itself has not been validate...
@ INVALID
The assumeutxo snapshot failed validation.
BOOST_FIXTURE_TEST_CASE(chainstatemanager, TestChain100Setup)
Basic tests for ChainstateManager.
util::Result< Options > SetOptsFromArgs(ArgsManager &args_man, Options opts, const std::vector< const char * > &args)
Helper function to parse args into args_man and return the result of applying them to opts.
V Cat(V v1, V &&v2)
Concatenate two vectors, moving elements.