Bitcoin Core 32.99.0
P2P Digital Currency
validation.cpp
Go to the documentation of this file.
1// Copyright (c) 2020-present The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
6
7#include <coins.h>
9#include <index/base.h>
11#include <interfaces/chain.h>
13#include <node/blockstorage.h>
14#include <node/context.h>
15#include <node/mining_types.h>
16#include <test/util/mining.h>
17#include <test/util/script.h>
19#include <test/util/time.h>
20#include <test/util/txmempool.h>
21#include <txmempool.h>
22#include <util/byte_units.h>
23#include <util/check.h>
24#include <util/time.h>
25#include <validation.h>
26#include <validationinterface.h>
27
28#include <memory>
29#include <utility>
30#include <vector>
31
33
35{
36 m_dirty_blockindex.clear();
37 m_dirty_fileinfo.clear();
38 m_blockfile_info.resize(1);
39}
40
42{
43 struct TestChainstate : public Chainstate {
44 void ResetNextWrite() { m_next_write = NodeClock::time_point::max() - 1s; }
45 };
47 for (const auto& cs : m_chainstates) {
48 static_cast<TestChainstate&>(*cs).ResetNextWrite();
49 }
50}
51
53{
54 m_cached_is_ibd = true;
56}
57
59{
61 m_cached_is_ibd = false;
63}
64
66 const ChainstateRole& role,
68 const std::shared_ptr<const CBlock>& block,
69 const CBlockIndex* pindex)
70{
71 obj.BlockConnected(role, block, pindex);
72}
74{
75 struct TestChainstate : public Chainstate {
76 void CallInvalidBlockFound(CBlockIndex* pindex, const BlockValidationState& state) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
77 {
78 InvalidBlockFound(pindex, state);
79 }
80 };
81
82 static_cast<TestChainstate*>(&ActiveChainstate())->CallInvalidBlockFound(pindex, state);
83}
84
86{
87 struct TestChainstate : public Chainstate {
88 void CallInvalidChainFound(CBlockIndex* pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
89 {
90 InvalidChainFound(pindexNew);
91 }
92 };
93
94 static_cast<TestChainstate*>(&ActiveChainstate())->CallInvalidChainFound(pindexNew);
95}
96
98{
99 struct TestChainstate : public Chainstate {
100 CBlockIndex* CallFindMostWorkChain() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
101 {
102 return FindMostWorkChain();
103 }
104 };
105
106 return static_cast<TestChainstate*>(&ActiveChainstate())->CallFindMostWorkChain();
107}
108
110{
111 m_best_invalid = nullptr;
112}
113
114std::vector<std::pair<COutPoint, CAmount>> ResetChainmanAndMempool(TestingSetup& setup, FakeNodeClock& node_clock, const ResetOptions& opts)
115{
116 node_clock.set(setup.m_node.chainman->GetParams().GenesisBlock().Time());
117
119
120 bilingual_str error{};
121 setup.m_node.block_template_manager.reset();
122 setup.m_node.mempool.reset();
123 setup.m_node.mempool = std::make_unique<CTxMemPool>(MemPoolOptionsForTest(setup.m_node), error);
124 Assert(error.empty());
125
126 setup.m_node.chainman.reset();
127 setup.m_make_chainman();
128 setup.LoadVerifyActivateChainstate();
129 setup.CreateBlockTemplateManager();
130
133
134 std::vector<std::pair<COutPoint, CAmount>> mature_coinbase;
135 for (int i = 0; i < 2 * COINBASE_MATURITY; ++i) {
136 COutPoint prevout{MineBlock(setup.m_node, options)};
137 if (i < COINBASE_MATURITY) {
138 LOCK(cs_main);
139 CAmount subsidy{setup.m_node.chainman->ActiveChainstate().CoinsTip().GetCoin(prevout)->out.nValue};
140 mature_coinbase.emplace_back(prevout, subsidy);
141 }
142 }
143
144 if (opts.init_block_filter_basic) {
145 Assert(InitBlockFilterIndex([&] { return interfaces::MakeChain(setup.m_node); }, BlockFilterType::BASIC, 1_MiB, /*f_memory=*/true, /*f_wipe=*/true));
147 Assert(index.Init());
148 index.Sync();
149 // The index serves the static setup chain only. Leaving it registered
150 // deadlocks with ImmediateBackgroundTaskRunner when a fuzzed block
151 // connects under cs_main.
152 StopIndex(index, setup.m_node);
153 }
154
155 return mature_coinbase;
156}
157
159{
160 Assert(node.validation_signals)->SyncWithValidationInterfaceQueue();
161 index.Stop();
162}
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
void DestroyAllBlockFilterIndexes()
Destroy all open block filter indexes.
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
bool InitBlockFilterIndex(std::function< std::unique_ptr< interfaces::Chain >()> make_chain, BlockFilterType filter_type, size_t n_cache_size, bool f_memory, bool f_wipe)
Initialize a block filter index for the given type if one does not already exist.
#define Assert(val)
Identity function.
Definition: check.h:116
Base class for indices of blockchain data.
Definition: base.h:55
void Stop()
Stops the instance from staying in sync with blockchain updates.
Definition: base.cpp:477
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:94
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:30
Implement this to subscribe to events generated in validation and mempool.
virtual void BlockConnected(const kernel::ChainstateRole &role, const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being connected.
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:550
bool IsInitialBlockDownload() const noexcept
Check whether we are doing an initial block download (synchronizing from disk or network)
Chainstate & ActiveChainstate() const
Alternatives to CurrentChainstate() used by older code to query latest chainstate information without...
std::atomic_bool m_cached_is_ibd
Whether initial block download (IBD) is ongoing.
Definition: validation.h:1059
Helper to initialize the global NodeClock, let a duration elapse, and reset it after use in a test.
Definition: time.h:54
void set(NodeSeconds t)
Set mocktime.
Definition: time.h:71
static void BlockConnected(const kernel::ChainstateRole &role, CValidationInterface &obj, const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Definition: validation.cpp:65
std::set< int > m_dirty_fileinfo
Dirty block file entries.
Definition: blockstorage.h:314
std::set< CBlockIndex * > m_dirty_blockindex
Dirty block index entries.
Definition: blockstorage.h:311
std::vector< CBlockFileInfo > m_blockfile_info
Definition: blockstorage.h:308
constexpr int COINBASE_MATURITY
Coinbase transaction outputs can only be spent after this number of new blocks (network rule)
Definition: consensus.h:19
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
is used externally by mining IPC clients, so it should only declare simple data definitions.
std::unique_ptr< Chain > MakeChain(node::NodeContext &node)
Return implementation of Chain interface.
Definition: messages.h:21
bool init_block_filter_basic
Definition: validation.h:67
void CleanupForFuzzing()
Test-only method to clear internal state for fuzzing.
Definition: validation.cpp:34
void ResetBestInvalid() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.cpp:109
void InvalidChainFound(CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.cpp:85
CBlockIndex * FindMostWorkChain() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.cpp:97
void DisableNextWrite()
Disable the next write of all chainstates.
Definition: validation.cpp:41
void InvalidBlockFound(CBlockIndex *pindex, const BlockValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Wrappers that avoid making chainstatemanager internals public for tests.
Definition: validation.cpp:73
void JumpOutOfIbd()
Toggle IsInitialBlockDownload from true to false.
Definition: validation.cpp:58
void ResetIbd()
Reset the ibd cache to its initial state.
Definition: validation.cpp:52
Testing setup that configures a complete environment.
Definition: setup_common.h:119
Bilingual messages:
Definition: translation.h:24
Information about chainstate that notifications are sent from.
Definition: types.h:18
Block template creation options.
Definition: mining_types.h:33
CScript coinbase_output_script
Script to put in the coinbase transaction.
Definition: mining_types.h:86
NodeContext struct containing references to chain state and connection state.
Definition: context.h:57
#define LOCK(cs)
Definition: sync.h:268
COutPoint MineBlock(const NodeContext &node, const node::BlockCreateOptions &assembler_options)
Returns the generated coin.
Definition: mining.cpp:120
static const CScript P2WSH_OP_TRUE
Definition: script.h:13
CTxMemPool::Options MemPoolOptionsForTest(const NodeContext &node)
Definition: txmempool.cpp:21
std::vector< std::pair< COutPoint, CAmount > > ResetChainmanAndMempool(TestingSetup &setup, FakeNodeClock &node_clock, const ResetOptions &opts)
Definition: validation.cpp:114
void StopIndex(BaseIndex &index, node::NodeContext &node)
Drain validation callbacks before stopping an index, matching Shutdown() in init.cpp.
Definition: validation.cpp:158
static int setup(void)
Definition: tests.c:8289
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
static bool pool cs
Definition: validation.cpp:409
assert(!tx.IsCoinBase())