Bitcoin ABC 0.32.11
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 ABC'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 ABC'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>
18
19#include <chainparams.h>
20#include <config.h>
22#include <core_io.h>
23#include <kernel/caches.h>
24#include <logging.h>
25#include <node/blockstorage.h>
26#include <node/chainstate.h>
27#include <scheduler.h>
28#include <script/scriptcache.h>
29#include <script/sigcache.h>
30#include <util/chaintype.h>
31#include <util/fs.h>
32#include <util/thread.h>
33#include <util/translation.h>
34#include <validation.h>
35#include <validationinterface.h>
36
37#include <cassert>
38#include <cstdint>
39#include <functional>
40#include <iosfwd>
41#include <memory>
42
43int main(int argc, char *argv[]) {
44 // We do not enable logging for this app, so explicitly disable it.
45 // To enable logging instead, replace with:
46 // LogInstance().m_print_to_console = true;
47 // LogInstance().StartLogging();
49
50 // SETUP: Argument parsing and handling
51 if (argc != 2) {
52 std::cerr << "Usage: " << argv[0] << " DATADIR" << std::endl
53 << "Display DATADIR information, and process hex-encoded "
54 "blocks on standard input."
55 << std::endl
56 << std::endl
57 << "IMPORTANT: THIS EXECUTABLE IS EXPERIMENTAL, FOR TESTING "
58 "ONLY, AND EXPECTED TO"
59 << std::endl
60 << " BREAK IN FUTURE VERSIONS. DO NOT USE ON YOUR "
61 "ACTUAL DATADIR."
62 << std::endl;
63 return 1;
64 }
65 fs::path abs_datadir{fs::absolute(argv[1])};
66 fs::create_directories(abs_datadir);
67
68 // SETUP: Misc Globals
70
72 auto &config = const_cast<Config &>(GetConfig());
73 config.SetChainParams(*chainparams);
74
75 // ECC_Start, etc.
76 kernel::Context kernel_context{};
77 // We can't use a goto here, but we can use an assert since none of the
78 // things instantiated so far requires running the epilogue to be torn down
79 // properly
80 assert(kernel::SanityChecks(kernel_context));
81
82 // SETUP: Scheduling and Background Signals
83 CScheduler scheduler{};
84 // Start the lightweight task scheduler thread
85 scheduler.m_service_thread = std::thread(util::TraceThread, "scheduler",
86 [&] { scheduler.serviceQueue(); });
87
88 // Gather some entropy once per minute.
89 scheduler.scheduleEvery(
90 [] {
92 return true;
93 },
94 std::chrono::minutes{1});
95
97
98 class KernelNotifications : public kernel::Notifications {
99 public:
100 void blockTip(SynchronizationState, CBlockIndex &) override {
101 std::cout << "Block tip changed" << std::endl;
102 }
103 void headerTip(SynchronizationState, int64_t height, int64_t timestamp,
104 bool presync) override {
105 std::cout << "Header tip changed: " << height << ", " << timestamp
106 << ", " << presync << std::endl;
107 }
108 void progress(const bilingual_str &title, int progress_percent,
109 bool resume_possible) override {
110 std::cout << "Progress: " << title.original << ", "
111 << progress_percent << ", " << resume_possible
112 << std::endl;
113 }
114 void warning(const std::string &warning) override {
115 std::cout << "Warning: " << warning << std::endl;
116 }
117 void flushError(const std::string &debug_message) override {
118 std::cerr << "Error flushing block data to disk: " << debug_message
119 << std::endl;
120 }
121 void fatalError(const std::string &debug_message,
122 const bilingual_str &user_message) override {
123 std::cerr << "Error: " << debug_message << std::endl;
124 std::cerr << (user_message.empty()
125 ? "A fatal internal error occurred."
126 : user_message.original)
127 << std::endl;
128 }
129 };
130 auto notifications = std::make_unique<KernelNotifications>();
131
132 // SETUP: Chainstate
133 const ChainstateManager::Options chainman_opts{
134 .config = config,
135 .datadir = abs_datadir,
136 .adjusted_time_callback = NodeClock::now,
137 .notifications = *notifications,
138 };
139 const node::BlockManager::Options blockman_opts{
140 .chainparams = chainman_opts.config.GetChainParams(),
141 .blocks_dir = abs_datadir / "blocks",
142 .notifications = chainman_opts.notifications,
143 };
144 ChainstateManager chainman{kernel_context.interrupt, chainman_opts,
145 blockman_opts};
146
149 options.check_interrupt = [] { return false; };
150 auto [status, error] = node::LoadChainstate(chainman, cache_sizes, options);
152 std::cerr << "Failed to load Chain state from your datadir."
153 << std::endl;
154 goto epilogue;
155 }
156 std::tie(status, error) = node::VerifyLoadedChainstate(chainman, options);
158 std::cerr << "Failed to verify loaded Chain state from your datadir."
159 << std::endl;
160 goto epilogue;
161 }
162
163 for (Chainstate *chainstate :
164 WITH_LOCK(::cs_main, return chainman.GetAll())) {
166 if (!chainstate->ActivateBestChain(state, nullptr)) {
167 std::cerr << "Failed to connect best block (" << state.ToString()
168 << ")" << std::endl;
169 goto epilogue;
170 }
171 }
172
173 // Main program logic starts here
174 std::cout
175 << "Hello! I'm going to print out some information about your datadir."
176 << std::endl;
177 {
178 LOCK(chainman.GetMutex());
179 std::cout << "\t"
180 << "Path: " << abs_datadir << std::endl
181 << "\t"
182 << "Reindexing: " << std::boolalpha << node::fReindex.load()
183 << std::noboolalpha << std::endl
184 << "\t"
185 << "Snapshot Active: " << std::boolalpha
186 << chainman.IsSnapshotActive() << std::noboolalpha
187 << std::endl
188 << "\t"
189 << "Active Height: " << chainman.ActiveHeight() << std::endl
190 << "\t"
191 << "Active IBD: " << std::boolalpha
192 << chainman.IsInitialBlockDownload() << std::noboolalpha
193 << std::endl;
194 CBlockIndex *tip = chainman.ActiveTip();
195 if (tip) {
196 std::cout << "\t" << tip->ToString() << std::endl;
197 }
198 }
199
200 for (std::string line; std::getline(std::cin, line);) {
201 if (line.empty()) {
202 std::cerr << "Empty line found" << std::endl;
203 break;
204 }
205
206 std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
207 CBlock &block = *blockptr;
208
209 if (!DecodeHexBlk(block, line)) {
210 std::cerr << "Block decode failed" << std::endl;
211 break;
212 }
213
214 if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
215 std::cerr << "Block does not start with a coinbase" << std::endl;
216 break;
217 }
218
219 BlockHash hash = block.GetHash();
220 {
221 LOCK(cs_main);
222 const CBlockIndex *pindex =
223 chainman.m_blockman.LookupBlockIndex(hash);
224 if (pindex) {
225 if (pindex->IsValid(BlockValidity::SCRIPTS)) {
226 std::cerr << "Duplicate" << std::endl;
227 break;
228 }
229 if (pindex->nStatus.hasFailed()) {
230 std::cerr << "Duplicate-invalid" << std::endl;
231 break;
232 }
233 }
234 }
235
236 // Adapted from rpc/mining.cpp
238 public:
240 bool found;
242
243 explicit submitblock_StateCatcher(const BlockHash &hashIn)
244 : hash(hashIn), found(false), state() {}
245
246 protected:
247 void BlockChecked(const CBlock &block,
248 const BlockValidationState &stateIn) override {
249 if (block.GetHash() != hash) {
250 return;
251 }
252 found = true;
253 state = stateIn;
254 }
255 };
256
257 bool new_block;
258 auto sc = std::make_shared<submitblock_StateCatcher>(block.GetHash());
260 bool accepted = chainman.ProcessNewBlock(blockptr,
261 /*force_processing=*/true,
262 /*min_pow_checked=*/true,
263 /*new_block=*/&new_block);
265 if (!new_block && accepted) {
266 std::cerr << "Duplicate" << std::endl;
267 break;
268 }
269 if (!sc->found) {
270 std::cerr << "Inconclusive" << std::endl;
271 break;
272 }
273 std::cout << sc->state.ToString() << std::endl;
274 switch (sc->state.GetResult()) {
276 std::cerr << "Initial value. Block has not yet been rejected"
277 << std::endl;
278 break;
280 std::cerr
281 << "the block header may be on a too-little-work chain"
282 << std::endl;
283 break;
285 std::cerr << "Invalid by consensus rules (excluding any below "
286 "reasons)"
287 << std::endl;
288 break;
290 std::cerr << "This block was cached as being invalid and we "
291 "didn't store the reason why"
292 << std::endl;
293 break;
295 std::cerr << "Invalid proof of work or time too old"
296 << std::endl;
297 break;
299 std::cerr << "The block's data didn't match the data committed "
300 "to by the PoW"
301 << std::endl;
302 break;
304 std::cerr << "We don't have the previous block the checked one "
305 "is built on"
306 << std::endl;
307 break;
309 std::cerr << "A block this one builds on is invalid"
310 << std::endl;
311 break;
313 std::cerr << "Block timestamp was > 2 hours in the future (or "
314 "our clock is bad)"
315 << std::endl;
316 break;
318 std::cerr << "The block failed to meet one of our checkpoints"
319 << std::endl;
320 break;
321 }
322 }
323
324epilogue:
325 // Without this precise shutdown sequence, there will be a lot of nullptr
326 // dereferencing and UB.
327 scheduler.stop();
328 if (chainman.m_thread_load.joinable()) {
329 chainman.m_thread_load.join();
330 }
332
334 {
335 LOCK(cs_main);
336 for (Chainstate *chainstate : chainman.GetAll()) {
337 if (chainstate->CanFlushToDisk()) {
338 chainstate->ForceFlushStateToDisk();
339 chainstate->ResetCoinsViews();
340 }
341 }
342 }
344}
int main(int argc, char *argv[])
@ SCRIPTS
Scripts & signatures ok.
void SelectParams(const ChainType chain)
Sets the params returned by Params() to those for the given BIP70 chain name.
Definition: chainparams.cpp:50
void DisableLogging() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
This offers a slight speedup and slightly smaller memory usage compared to leaving the logging system...
Definition: logging.cpp:119
BlockHash GetHash() const
Definition: block.cpp:11
Definition: block.h:60
std::vector< CTransactionRef > vtx
Definition: block.h:63
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:25
bool IsValid(enum BlockValidity nUpTo=BlockValidity::TRANSACTIONS) const EXCLUSIVE_LOCKS_REQUIRED(
Check whether this block index entry is valid up to the passed validity level.
Definition: blockindex.h:191
std::string ToString() const
Definition: blockindex.cpp:30
static std::unique_ptr< const CChainParams > Main(const ChainOptions &options)
void UnregisterBackgroundSignalScheduler()
Unregister a CScheduler to give callbacks which should run in the background - these callbacks will n...
void RegisterBackgroundSignalScheduler(CScheduler &scheduler)
Register a CScheduler to give callbacks which should run in the background (may only be called once)
void FlushBackgroundCallbacks()
Call any remaining callbacks on the calling thread.
Simple class for background tasks that should be run periodically or once "after a while".
Definition: scheduler.h:41
std::thread m_service_thread
Definition: scheduler.h:46
Implement this to subscribe to events generated in validation.
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:733
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1185
Definition: config.h:19
virtual void SetChainParams(const CChainParams chainParamsIn)=0
std::string ToString() const
Definition: validation.h:125
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
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 flushError(const std::string &debug_message)
The flush error notification is sent to notify the user that an error occurred while flushing block d...
virtual void fatalError(const std::string &debug_message, const bilingual_str &user_message={})
The fatal error notification is sent to notify the user when an error occurs in kernel code that can'...
virtual void warning(const std::string &warning)
virtual void progress(const bilingual_str &title, int progress_percent, bool resume_possible)
virtual void blockTip(SynchronizationState state, CBlockIndex &index)
void BlockChecked(const CBlock &block, const BlockValidationState &stateIn) override
Notifies listeners of a block validation result.
Definition: mining.cpp:1288
submitblock_StateCatcher(const uint256 &hashIn)
Definition: mining.cpp:1285
BlockValidationState state
Definition: mining.cpp:1283
const Config & GetConfig()
Definition: config.cpp:40
@ BLOCK_CHECKPOINT
the block failed to meet one of our checkpoints
@ 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:233
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
static constexpr int64_t DEFAULT_KERNEL_CACHE
Suggested default amount of cache reserved for the kernel (bytes)
Definition: caches.h:14
BCLog::Logger & LogInstance()
Definition: logging.cpp:25
static path absolute(const path &p)
Definition: fs.h:101
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:185
util::Result< void > SanityChecks(const Context &)
Ensure a usable environment with all necessary library support.
Definition: checks.cpp:13
ChainstateLoadResult LoadChainstate(ChainstateManager &chainman, const CacheSizes &cache_sizes, const ChainstateLoadOptions &options)
Definition: chainstate.cpp:171
ChainstateLoadResult VerifyLoadedChainstate(ChainstateManager &chainman, const ChainstateLoadOptions &options)
Definition: chainstate.cpp:275
std::atomic_bool fReindex
void TraceThread(std::string_view thread_name, std::function< void()> thread_func)
A wrapper for do-something-once thread functions.
Definition: thread.cpp:14
void RandAddPeriodic() noexcept
Gather entropy from various expensive sources, and feed them to the PRNG state.
Definition: random.cpp:700
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
static time_point now() noexcept
Return current system time or mocked time, if set.
Definition: time.cpp:28
Bilingual messages:
Definition: translation.h:17
bool empty() const
Definition: translation.h:27
std::string original
Definition: translation.h:18
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:20
std::function< bool()> check_interrupt
Definition: chainstate.h:38
#define LOCK(cs)
Definition: sync.h:306
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:357
void StopScriptCheckWorkerThreads()
Stop all of the script checking worker threads.
assert(!tx.IsCoinBase())
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:118
CMainSignals & GetMainSignals()
void UnregisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Unregister subscriber.
void RegisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Register subscriber.