Bitcoin Core  27.99.0
P2P Digital Currency
bitcoin-chainstate.cpp
Go to the documentation of this file.
1 // Copyright (c) 2022 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 //
5 // The bitcoin-chainstate executable serves to surface the dependencies required
6 // by a program wishing to use Bitcoin Core's consensus engine as it is right
7 // now.
8 //
9 // DEVELOPER NOTE: Since this is a "demo-only", experimental, etc. executable,
10 // it may diverge from Bitcoin Core's coding style.
11 //
12 // It is part of the libbitcoinkernel project.
13 
14 #include <kernel/chainparams.h>
16 #include <kernel/checks.h>
17 #include <kernel/context.h>
19 
20 #include <consensus/validation.h>
21 #include <core_io.h>
22 #include <node/blockstorage.h>
23 #include <node/caches.h>
24 #include <node/chainstate.h>
25 #include <random.h>
26 #include <script/sigcache.h>
27 #include <util/chaintype.h>
28 #include <util/fs.h>
29 #include <util/signalinterrupt.h>
30 #include <util/task_runner.h>
31 #include <validation.h>
32 #include <validationinterface.h>
33 
34 #include <cassert>
35 #include <cstdint>
36 #include <functional>
37 #include <iosfwd>
38 #include <memory>
39 #include <string>
40 
41 int main(int argc, char* argv[])
42 {
43  // SETUP: Argument parsing and handling
44  if (argc != 2) {
45  std::cerr
46  << "Usage: " << argv[0] << " DATADIR" << std::endl
47  << "Display DATADIR information, and process hex-encoded blocks on standard input." << std::endl
48  << std::endl
49  << "IMPORTANT: THIS EXECUTABLE IS EXPERIMENTAL, FOR TESTING ONLY, AND EXPECTED TO" << std::endl
50  << " BREAK IN FUTURE VERSIONS. DO NOT USE ON YOUR ACTUAL DATADIR." << std::endl;
51  return 1;
52  }
53  fs::path abs_datadir{fs::absolute(argv[1])};
54  fs::create_directories(abs_datadir);
55 
56 
57  // SETUP: Context
58  kernel::Context kernel_context{};
59  // We can't use a goto here, but we can use an assert since none of the
60  // things instantiated so far requires running the epilogue to be torn down
61  // properly
62  assert(kernel::SanityChecks(kernel_context));
63 
64  // Necessary for CheckInputScripts (eventually called by ProcessNewBlock),
65  // which will try the script cache first and fall back to actually
66  // performing the check with the signature cache.
67  kernel::ValidationCacheSizes validation_cache_sizes{};
68  Assert(InitSignatureCache(validation_cache_sizes.signature_cache_bytes));
69  Assert(InitScriptExecutionCache(validation_cache_sizes.script_execution_cache_bytes));
70 
71  ValidationSignals validation_signals{std::make_unique<util::ImmediateTaskRunner>()};
72 
73  class KernelNotifications : public kernel::Notifications
74  {
75  public:
77  {
78  std::cout << "Block tip changed" << std::endl;
79  return {};
80  }
81  void headerTip(SynchronizationState, int64_t height, int64_t timestamp, bool presync) override
82  {
83  std::cout << "Header tip changed: " << height << ", " << timestamp << ", " << presync << std::endl;
84  }
85  void progress(const bilingual_str& title, int progress_percent, bool resume_possible) override
86  {
87  std::cout << "Progress: " << title.original << ", " << progress_percent << ", " << resume_possible << std::endl;
88  }
89  void warning(const bilingual_str& warning) override
90  {
91  std::cout << "Warning: " << warning.original << std::endl;
92  }
93  void flushError(const bilingual_str& message) override
94  {
95  std::cerr << "Error flushing block data to disk: " << message.original << std::endl;
96  }
97  void fatalError(const bilingual_str& message) override
98  {
99  std::cerr << "Error: " << message.original << std::endl;
100  }
101  };
102  auto notifications = std::make_unique<KernelNotifications>();
103 
104 
105  // SETUP: Chainstate
106  auto chainparams = CChainParams::Main();
107  const ChainstateManager::Options chainman_opts{
108  .chainparams = *chainparams,
109  .datadir = abs_datadir,
110  .notifications = *notifications,
111  .signals = &validation_signals,
112  };
113  const node::BlockManager::Options blockman_opts{
114  .chainparams = chainman_opts.chainparams,
115  .blocks_dir = abs_datadir / "blocks",
116  .notifications = chainman_opts.notifications,
117  };
118  util::SignalInterrupt interrupt;
119  ChainstateManager chainman{interrupt, chainman_opts, blockman_opts};
120 
121  node::CacheSizes cache_sizes;
122  cache_sizes.block_tree_db = 2 << 20;
123  cache_sizes.coins_db = 2 << 22;
124  cache_sizes.coins = (450 << 20) - (2 << 20) - (2 << 22);
126  auto [status, error] = node::LoadChainstate(chainman, cache_sizes, options);
127  if (status != node::ChainstateLoadStatus::SUCCESS) {
128  std::cerr << "Failed to load Chain state from your datadir." << std::endl;
129  goto epilogue;
130  } else {
131  std::tie(status, error) = node::VerifyLoadedChainstate(chainman, options);
132  if (status != node::ChainstateLoadStatus::SUCCESS) {
133  std::cerr << "Failed to verify loaded Chain state from your datadir." << std::endl;
134  goto epilogue;
135  }
136  }
137 
138  for (Chainstate* chainstate : WITH_LOCK(::cs_main, return chainman.GetAll())) {
139  BlockValidationState state;
140  if (!chainstate->ActivateBestChain(state, nullptr)) {
141  std::cerr << "Failed to connect best block (" << state.ToString() << ")" << std::endl;
142  goto epilogue;
143  }
144  }
145 
146  // Main program logic starts here
147  std::cout
148  << "Hello! I'm going to print out some information about your datadir." << std::endl
149  << "\t"
150  << "Path: " << abs_datadir << std::endl;
151  {
152  LOCK(chainman.GetMutex());
153  std::cout
154  << "\t" << "Reindexing: " << std::boolalpha << chainman.m_blockman.m_reindexing.load() << std::noboolalpha << std::endl
155  << "\t" << "Snapshot Active: " << std::boolalpha << chainman.IsSnapshotActive() << std::noboolalpha << std::endl
156  << "\t" << "Active Height: " << chainman.ActiveHeight() << std::endl
157  << "\t" << "Active IBD: " << std::boolalpha << chainman.IsInitialBlockDownload() << std::noboolalpha << std::endl;
158  CBlockIndex* tip = chainman.ActiveTip();
159  if (tip) {
160  std::cout << "\t" << tip->ToString() << std::endl;
161  }
162  }
163 
164  for (std::string line; std::getline(std::cin, line);) {
165  if (line.empty()) {
166  std::cerr << "Empty line found" << std::endl;
167  break;
168  }
169 
170  std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
171  CBlock& block = *blockptr;
172 
173  if (!DecodeHexBlk(block, line)) {
174  std::cerr << "Block decode failed" << std::endl;
175  break;
176  }
177 
178  if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
179  std::cerr << "Block does not start with a coinbase" << std::endl;
180  break;
181  }
182 
183  uint256 hash = block.GetHash();
184  {
185  LOCK(cs_main);
186  const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(hash);
187  if (pindex) {
188  if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
189  std::cerr << "duplicate" << std::endl;
190  break;
191  }
192  if (pindex->nStatus & BLOCK_FAILED_MASK) {
193  std::cerr << "duplicate-invalid" << std::endl;
194  break;
195  }
196  }
197  }
198 
199  {
200  LOCK(cs_main);
201  const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock);
202  if (pindex) {
203  chainman.UpdateUncommittedBlockStructures(block, pindex);
204  }
205  }
206 
207  // Adapted from rpc/mining.cpp
209  {
210  public:
211  uint256 hash;
212  bool found;
214 
215  explicit submitblock_StateCatcher(const uint256& hashIn) : hash(hashIn), found(false), state() {}
216 
217  protected:
218  void BlockChecked(const CBlock& block, const BlockValidationState& stateIn) override
219  {
220  if (block.GetHash() != hash)
221  return;
222  found = true;
223  state = stateIn;
224  }
225  };
226 
227  bool new_block;
228  auto sc = std::make_shared<submitblock_StateCatcher>(block.GetHash());
229  validation_signals.RegisterSharedValidationInterface(sc);
230  bool accepted = chainman.ProcessNewBlock(blockptr, /*force_processing=*/true, /*min_pow_checked=*/true, /*new_block=*/&new_block);
231  validation_signals.UnregisterSharedValidationInterface(sc);
232  if (!new_block && accepted) {
233  std::cerr << "duplicate" << std::endl;
234  break;
235  }
236  if (!sc->found) {
237  std::cerr << "inconclusive" << std::endl;
238  break;
239  }
240  std::cout << sc->state.ToString() << std::endl;
241  switch (sc->state.GetResult()) {
243  std::cerr << "initial value. Block has not yet been rejected" << std::endl;
244  break;
246  std::cerr << "the block header may be on a too-little-work chain" << std::endl;
247  break;
249  std::cerr << "invalid by consensus rules (excluding any below reasons)" << std::endl;
250  break;
252  std::cerr << "Invalid by a change to consensus rules more recent than SegWit." << std::endl;
253  break;
255  std::cerr << "this block was cached as being invalid and we didn't store the reason why" << std::endl;
256  break;
258  std::cerr << "invalid proof of work or time too old" << std::endl;
259  break;
261  std::cerr << "the block's data didn't match the data committed to by the PoW" << std::endl;
262  break;
264  std::cerr << "We don't have the previous block the checked one is built on" << std::endl;
265  break;
267  std::cerr << "A block this one builds on is invalid" << std::endl;
268  break;
270  std::cerr << "block timestamp was > 2 hours in the future (or our clock is bad)" << std::endl;
271  break;
273  std::cerr << "the block failed to meet one of our checkpoints" << std::endl;
274  break;
275  }
276  }
277 
278 epilogue:
279  // Without this precise shutdown sequence, there will be a lot of nullptr
280  // dereferencing and UB.
281  if (chainman.m_thread_load.joinable()) chainman.m_thread_load.join();
282 
283  validation_signals.FlushBackgroundCallbacks();
284  {
285  LOCK(cs_main);
286  for (Chainstate* chainstate : chainman.GetAll()) {
287  if (chainstate->CanFlushToDisk()) {
288  chainstate->ForceFlushStateToDisk();
289  chainstate->ResetCoinsViews();
290  }
291  }
292  }
293 }
int main(int argc, char *argv[])
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok.
Definition: chain.h:115
@ BLOCK_FAILED_MASK
Definition: chain.h:127
#define Assert(val)
Identity function.
Definition: check.h:77
uint256 hashPrevBlock
Definition: block.h:26
uint256 GetHash() const
Definition: block.cpp:11
Definition: block.h:69
std::vector< CTransactionRef > vtx
Definition: block.h:72
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:141
std::string ToString() const
Definition: chain.cpp:15
bool IsValid(enum BlockStatus nUpTo=BLOCK_VALID_TRANSACTIONS) const EXCLUSIVE_LOCKS_REQUIRED(
Check whether this block index entry is valid up to the passed validity level.
Definition: chain.h:296
static std::unique_ptr< const CChainParams > Main()
Implement this to subscribe to events generated in validation and mempool.
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:490
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:849
std::string ToString() const
Definition: validation.h:128
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:33
A base class defining functions for notifying about certain kernel events.
virtual void headerTip(SynchronizationState state, int64_t height, int64_t timestamp, bool presync)
virtual void fatalError(const bilingual_str &message)
The fatal error notification is sent to notify the user when an error occurs in kernel code that can'...
virtual void warning(const bilingual_str &warning)
virtual void progress(const bilingual_str &title, int progress_percent, bool resume_possible)
virtual void flushError(const bilingual_str &message)
The flush error notification is sent to notify the user that an error occurred while flushing block d...
virtual InterruptResult blockTip(SynchronizationState state, CBlockIndex &index)
void BlockChecked(const CBlock &block, const BlockValidationState &stateIn) override
Notifies listeners of a block validation result.
Definition: mining.cpp:987
submitblock_StateCatcher(const uint256 &hashIn)
Definition: mining.cpp:984
BlockValidationState state
Definition: mining.cpp:982
256-bit opaque blob.
Definition: uint256.h:106
Helper class that manages an interrupt flag, and allows a thread or signal to interrupt another threa...
@ BLOCK_CHECKPOINT
the block failed to meet one of our checkpoints
@ BLOCK_RECENT_CONSENSUS_CHANGE
Invalid by a change to consensus rules more recent than SegWit.
@ BLOCK_HEADER_LOW_WORK
the block header may be on a too-little-work chain
@ BLOCK_INVALID_HEADER
invalid proof of work or time too old
@ BLOCK_CACHED_INVALID
this block was cached as being invalid and we didn't store the reason why
@ BLOCK_CONSENSUS
invalid by consensus rules (excluding any below reasons)
@ BLOCK_MISSING_PREV
We don't have the previous block the checked one is built on.
@ BLOCK_INVALID_PREV
A block this one builds on is invalid.
@ BLOCK_MUTATED
the block's data didn't match the data committed to by the PoW
@ BLOCK_TIME_FUTURE
block timestamp was > 2 hours in the future (or our clock is bad)
@ BLOCK_RESULT_UNSET
initial value. Block has not yet been rejected
bool DecodeHexBlk(CBlock &, const std::string &strHexBlk)
Definition: core_read.cpp:218
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
static path absolute(const path &p)
Definition: fs.h:82
static bool create_directories(const std::filesystem::path &p)
Create directory (and if necessary its parents), unless the leaf directory already exists or is a sym...
Definition: fs.h:190
std::variant< std::monostate, Interrupted > InterruptResult
Simple result type for functions that need to propagate an interrupt status and don't have other retu...
util::Result< void > SanityChecks(const Context &)
Ensure a usable environment with all necessary library support.
Definition: checks.cpp:15
ChainstateLoadResult LoadChainstate(ChainstateManager &chainman, const CacheSizes &cache_sizes, const ChainstateLoadOptions &options)
This sequence can have 4 types of outcomes:
Definition: chainstate.cpp:162
ChainstateLoadResult VerifyLoadedChainstate(ChainstateManager &chainman, const ChainstateLoadOptions &options)
Definition: chainstate.cpp:247
bool InitSignatureCache(size_t max_size_bytes)
Definition: sigcache.cpp:97
Bilingual messages:
Definition: translation.h:18
std::string original
Definition: translation.h:19
An options struct for BlockManager, more ergonomically referred to as BlockManager::Options due to th...
const CChainParams & chainparams
An options struct for ChainstateManager, more ergonomically referred to as ChainstateManager::Options...
Context struct holding the kernel library's logically global state, and passed to external libbitcoin...
Definition: context.h:16
int64_t coins
Definition: caches.h:17
int64_t block_tree_db
Definition: caches.h:15
int64_t coins_db
Definition: caches.h:16
#define LOCK(cs)
Definition: sync.h:257
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:301
This header provides an interface and simple implementation for a task runner.
bool InitScriptExecutionCache(size_t max_size_bytes)
Initializes the script-execution cache.
assert(!tx.IsCoinBase())
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:80