Bitcoin ABC 0.34.5
P2P Digital Currency
Loading...
Searching...
No Matches
blockchain.cpp
Go to the documentation of this file.
1// Copyright (c) 2010 Satoshi Nakamoto
2// Copyright (c) 2009-2019 The Bitcoin Core developers
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#include <rpc/blockchain.h>
7
9#include <blockfilter.h>
10#include <chain.h>
11#include <chainparams.h>
12#include <clientversion.h>
13#include <coins.h>
14#include <common/args.h>
15#include <config.h>
16#include <consensus/amount.h>
17#include <consensus/params.h>
19#include <core_io.h>
20#include <hash.h>
23#include <logging/timer.h>
24#include <net.h>
25#include <net_processing.h>
26#include <node/blockstorage.h>
27#include <node/coinstats.h>
28#include <node/context.h>
29#include <node/utxo_snapshot.h>
31#include <rpc/server.h>
32#include <rpc/server_util.h>
33#include <rpc/util.h>
34#include <script/descriptor.h>
35#include <serialize.h>
36#include <streams.h>
37#include <txdb.h>
38#include <txmempool.h>
39#include <undo.h>
40#include <util/check.h>
41#include <util/fs.h>
42#include <util/strencodings.h>
43#include <util/string.h>
44#include <util/translation.h>
45#include <validation.h>
46#include <validationinterface.h>
47#include <warnings.h>
48
49#include <condition_variable>
50#include <cstdint>
51#include <memory>
52#include <mutex>
53#include <optional>
54
57
63
68
70static std::condition_variable cond_blockchange;
72
73std::tuple<std::unique_ptr<CCoinsViewCursor>, CCoinsStats, const CBlockIndex *>
75 const std::function<void()> &interruption_point = {})
77
80 CCoinsStats *maybe_stats, const CBlockIndex *tip,
81 AutoFile &afile, const fs::path &path,
82 const fs::path &temppath,
83 const std::function<void()> &interruption_point = {});
84
88double GetDifficulty(const CBlockIndex &blockindex) {
89 int nShift = (blockindex.nBits >> 24) & 0xff;
90 double dDiff = double(0x0000ffff) / double(blockindex.nBits & 0x00ffffff);
91
92 while (nShift < 29) {
93 dDiff *= 256.0;
94 nShift++;
95 }
96 while (nShift > 29) {
97 dDiff /= 256.0;
98 nShift--;
99 }
100
101 return dDiff;
102}
103
105 const CBlockIndex &blockindex,
106 const CBlockIndex *&next) {
107 next = tip.GetAncestor(blockindex.nHeight + 1);
108 if (next && next->pprev == &blockindex) {
109 return tip.nHeight - blockindex.nHeight + 1;
110 }
111 next = nullptr;
112 return &blockindex == &tip ? 1 : -1;
113}
114
115static const CBlockIndex *ParseHashOrHeight(const UniValue &param,
116 ChainstateManager &chainman) {
118 CChain &active_chain = chainman.ActiveChain();
119
120 if (param.isNum()) {
121 const int height{param.getInt<int>()};
122 if (height < 0) {
123 throw JSONRPCError(
125 strprintf("Target block height %d is negative", height));
126 }
127 const int current_tip{active_chain.Height()};
128 if (height > current_tip) {
129 throw JSONRPCError(
131 strprintf("Target block height %d after current tip %d", height,
132 current_tip));
133 }
134
135 return active_chain[height];
136 } else {
137 const BlockHash hash{ParseHashV(param, "hash_or_height")};
138 const CBlockIndex *pindex = chainman.m_blockman.LookupBlockIndex(hash);
139
140 if (!pindex) {
141 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
142 }
143
144 return pindex;
145 }
146}
148 const CBlockIndex &blockindex) {
149 // Serialize passed information without accessing chain state of the active
150 // chain!
151 // For performance reasons
153
154 UniValue result(UniValue::VOBJ);
155 result.pushKV("hash", blockindex.GetBlockHash().GetHex());
156 const CBlockIndex *pnext;
157 int confirmations = ComputeNextBlockAndDepth(tip, blockindex, pnext);
158 result.pushKV("confirmations", confirmations);
159 result.pushKV("height", blockindex.nHeight);
160 result.pushKV("version", blockindex.nVersion);
161 result.pushKV("versionHex", strprintf("%08x", blockindex.nVersion));
162 result.pushKV("merkleroot", blockindex.hashMerkleRoot.GetHex());
163 result.pushKV("time", blockindex.nTime);
164 result.pushKV("mediantime", blockindex.GetMedianTimePast());
165 result.pushKV("nonce", blockindex.nNonce);
166 result.pushKV("bits", strprintf("%08x", blockindex.nBits));
167 result.pushKV("difficulty", GetDifficulty(blockindex));
168 result.pushKV("chainwork", blockindex.nChainWork.GetHex());
169 result.pushKV("nTx", blockindex.nTx);
170
171 if (blockindex.pprev) {
172 result.pushKV("previousblockhash",
173 blockindex.pprev->GetBlockHash().GetHex());
174 }
175 if (pnext) {
176 result.pushKV("nextblockhash", pnext->GetBlockHash().GetHex());
177 }
178 return result;
179}
180
181UniValue blockToJSON(BlockManager &blockman, const CBlock &block,
182 const CBlockIndex &tip, const CBlockIndex &blockindex,
183 TxVerbosity verbosity) {
184 UniValue result = blockheaderToJSON(tip, blockindex);
185
186 result.pushKV("size", (int)::GetSerializeSize(block));
188 switch (verbosity) {
190 for (const CTransactionRef &tx : block.vtx) {
191 txs.push_back(tx->GetId().GetHex());
192 }
193 break;
194
197 CBlockUndo blockUndo;
198 const bool is_not_pruned{WITH_LOCK(
199 ::cs_main, return !blockman.IsBlockPruned(blockindex))};
200 const bool have_undo{is_not_pruned &&
201 blockman.ReadBlockUndo(blockUndo, blockindex)};
202 for (size_t i = 0; i < block.vtx.size(); ++i) {
203 const CTransactionRef &tx = block.vtx.at(i);
204 // coinbase transaction (i == 0) doesn't have undo data
205 const CTxUndo *txundo = (have_undo && i > 0)
206 ? &blockUndo.vtxundo.at(i - 1)
207 : nullptr;
209 TxToUniv(*tx, BlockHash(), objTx, true, txundo, verbosity);
210 txs.push_back(std::move(objTx));
211 }
212 break;
213 }
214
215 result.pushKV("tx", std::move(txs));
216
217 return result;
218}
219
221 return RPCHelpMan{
222 "getblockcount",
223 "Returns the height of the most-work fully-validated chain.\n"
224 "The genesis block has height 0.\n",
225 {},
226 RPCResult{RPCResult::Type::NUM, "", "The current block count"},
227 RPCExamples{HelpExampleCli("getblockcount", "") +
228 HelpExampleRpc("getblockcount", "")},
229 [&](const RPCHelpMan &self, const Config &config,
230 const JSONRPCRequest &request) -> UniValue {
231 ChainstateManager &chainman = EnsureAnyChainman(request.context);
232 LOCK(cs_main);
233 return chainman.ActiveHeight();
234 },
235 };
236}
237
239 return RPCHelpMan{
240 "getbestblockhash",
241 "Returns the hash of the best (tip) block in the "
242 "most-work fully-validated chain.\n",
243 {},
244 RPCResult{RPCResult::Type::STR_HEX, "", "the block hash, hex-encoded"},
245 RPCExamples{HelpExampleCli("getbestblockhash", "") +
246 HelpExampleRpc("getbestblockhash", "")},
247 [&](const RPCHelpMan &self, const Config &config,
248 const JSONRPCRequest &request) -> UniValue {
249 ChainstateManager &chainman = EnsureAnyChainman(request.context);
250 LOCK(cs_main);
251 return chainman.ActiveTip()->GetBlockHash().GetHex();
252 },
253 };
254}
255
257 if (pindex) {
259 latestblock.hash = pindex->GetBlockHash();
260 latestblock.height = pindex->nHeight;
261 }
262 cond_blockchange.notify_all();
263}
264
266 return RPCHelpMan{
267 "waitfornewblock",
268 "Waits for a specific new block and returns useful info about it.\n"
269 "\nReturns the current block on timeout or exit.\n",
270 {
271 {"timeout", RPCArg::Type::NUM, RPCArg::Default{0},
272 "Time in milliseconds to wait for a response. 0 indicates no "
273 "timeout."},
274 },
276 "",
277 "",
278 {
279 {RPCResult::Type::STR_HEX, "hash", "The blockhash"},
280 {RPCResult::Type::NUM, "height", "Block height"},
281 }},
282 RPCExamples{HelpExampleCli("waitfornewblock", "1000") +
283 HelpExampleRpc("waitfornewblock", "1000")},
284 [&](const RPCHelpMan &self, const Config &config,
285 const JSONRPCRequest &request) -> UniValue {
286 int timeout = 0;
287 if (!request.params[0].isNull()) {
288 timeout = request.params[0].getInt<int>();
289 }
290
291 CUpdatedBlock block;
292 {
294 block = latestblock;
295 if (timeout) {
296 cond_blockchange.wait_for(
297 lock, std::chrono::milliseconds(timeout),
299 return latestblock.height != block.height ||
300 latestblock.hash != block.hash ||
301 !IsRPCRunning();
302 });
303 } else {
304 cond_blockchange.wait(
305 lock,
307 return latestblock.height != block.height ||
308 latestblock.hash != block.hash ||
309 !IsRPCRunning();
310 });
311 }
312 block = latestblock;
313 }
315 ret.pushKV("hash", block.hash.GetHex());
316 ret.pushKV("height", block.height);
317 return ret;
318 },
319 };
320}
321
323 return RPCHelpMan{
324 "waitforblock",
325 "Waits for a specific new block and returns useful info about it.\n"
326 "\nReturns the current block on timeout or exit.\n",
327 {
329 "Block hash to wait for."},
330 {"timeout", RPCArg::Type::NUM, RPCArg::Default{0},
331 "Time in milliseconds to wait for a response. 0 indicates no "
332 "timeout."},
333 },
335 "",
336 "",
337 {
338 {RPCResult::Type::STR_HEX, "hash", "The blockhash"},
339 {RPCResult::Type::NUM, "height", "Block height"},
340 }},
341 RPCExamples{HelpExampleCli("waitforblock",
342 "\"0000000000079f8ef3d2c688c244eb7a4570b24c9"
343 "ed7b4a8c619eb02596f8862\" 1000") +
344 HelpExampleRpc("waitforblock",
345 "\"0000000000079f8ef3d2c688c244eb7a4570b24c9"
346 "ed7b4a8c619eb02596f8862\", 1000")},
347 [&](const RPCHelpMan &self, const Config &config,
348 const JSONRPCRequest &request) -> UniValue {
349 int timeout = 0;
350
351 BlockHash hash(ParseHashV(request.params[0], "blockhash"));
352
353 if (!request.params[1].isNull()) {
354 timeout = request.params[1].getInt<int>();
355 }
356
357 CUpdatedBlock block;
358 {
360 if (timeout) {
361 cond_blockchange.wait_for(
362 lock, std::chrono::milliseconds(timeout),
364 return latestblock.hash == hash || !IsRPCRunning();
365 });
366 } else {
367 cond_blockchange.wait(
368 lock,
370 return latestblock.hash == hash || !IsRPCRunning();
371 });
372 }
373 block = latestblock;
374 }
375
377 ret.pushKV("hash", block.hash.GetHex());
378 ret.pushKV("height", block.height);
379 return ret;
380 },
381 };
382}
383
385 return RPCHelpMan{
386 "waitforblockheight",
387 "Waits for (at least) block height and returns the height and "
388 "hash\nof the current tip.\n"
389 "\nReturns the current block on timeout or exit.\n",
390 {
392 "Block height to wait for."},
393 {"timeout", RPCArg::Type::NUM, RPCArg::Default{0},
394 "Time in milliseconds to wait for a response. 0 indicates no "
395 "timeout."},
396 },
398 "",
399 "",
400 {
401 {RPCResult::Type::STR_HEX, "hash", "The blockhash"},
402 {RPCResult::Type::NUM, "height", "Block height"},
403 }},
404 RPCExamples{HelpExampleCli("waitforblockheight", "100 1000") +
405 HelpExampleRpc("waitforblockheight", "100, 1000")},
406 [&](const RPCHelpMan &self, const Config &config,
407 const JSONRPCRequest &request) -> UniValue {
408 int timeout = 0;
409
410 int height = request.params[0].getInt<int>();
411
412 if (!request.params[1].isNull()) {
413 timeout = request.params[1].getInt<int>();
414 }
415
416 CUpdatedBlock block;
417 {
419 if (timeout) {
420 cond_blockchange.wait_for(
421 lock, std::chrono::milliseconds(timeout),
423 return latestblock.height >= height ||
424 !IsRPCRunning();
425 });
426 } else {
427 cond_blockchange.wait(
428 lock,
430 return latestblock.height >= height ||
431 !IsRPCRunning();
432 });
433 }
434 block = latestblock;
435 }
437 ret.pushKV("hash", block.hash.GetHex());
438 ret.pushKV("height", block.height);
439 return ret;
440 },
441 };
442}
443
445 return RPCHelpMan{
446 "syncwithvalidationinterfacequeue",
447 "Waits for the validation interface queue to catch up on everything "
448 "that was there when we entered this function.\n",
449 {},
451 RPCExamples{HelpExampleCli("syncwithvalidationinterfacequeue", "") +
452 HelpExampleRpc("syncwithvalidationinterfacequeue", "")},
453 [&](const RPCHelpMan &self, const Config &config,
454 const JSONRPCRequest &request) -> UniValue {
455 NodeContext &node = EnsureAnyNodeContext(request.context);
456 CHECK_NONFATAL(node.validation_signals)
457 ->SyncWithValidationInterfaceQueue();
458 return UniValue::VNULL;
459 },
460 };
461}
462
464 return RPCHelpMan{
465 "getdifficulty",
466 "Returns the proof-of-work difficulty as a multiple of the minimum "
467 "difficulty.\n",
468 {},
470 "the proof-of-work difficulty as a multiple of the minimum "
471 "difficulty."},
472 RPCExamples{HelpExampleCli("getdifficulty", "") +
473 HelpExampleRpc("getdifficulty", "")},
474 [&](const RPCHelpMan &self, const Config &config,
475 const JSONRPCRequest &request) -> UniValue {
476 ChainstateManager &chainman = EnsureAnyChainman(request.context);
477 LOCK(cs_main);
478 return GetDifficulty(*CHECK_NONFATAL(chainman.ActiveTip()));
479 },
480 };
481}
482
484 return RPCHelpMan{
485 "getblockfrompeer",
486 "Attempt to fetch block from a given peer.\n"
487 "\nWe must have the header for this block, e.g. using submitheader.\n"
488 "The block will not have any undo data which can limit the usage of "
489 "the block data in a context where the undo data is needed.\n"
490 "Subsequent calls for the same block may cause the response from the "
491 "previous peer to be ignored.\n"
492 "Peers generally ignore requests for a stale block that they never "
493 "fully verified, or one that is more than a month old.\n"
494 "When a peer does not respond with a block, we will disconnect.\n"
495 "\nReturns an empty JSON object if the request was successfully "
496 "scheduled.",
497 {
499 "The block hash to try to fetch"},
501 "The peer to fetch it from (see getpeerinfo for peer IDs)"},
502 },
503 RPCResult{RPCResult::Type::OBJ, "", /*optional=*/false, "", {}},
504 RPCExamples{HelpExampleCli("getblockfrompeer",
505 "\"00000000c937983704a73af28acdec37b049d214a"
506 "dbda81d7e2a3dd146f6ed09\" 0") +
507 HelpExampleRpc("getblockfrompeer",
508 "\"00000000c937983704a73af28acdec37b049d214a"
509 "dbda81d7e2a3dd146f6ed09\" 0")},
510 [&](const RPCHelpMan &self, const Config &config,
511 const JSONRPCRequest &request) -> UniValue {
512 const NodeContext &node = EnsureAnyNodeContext(request.context);
514 PeerManager &peerman = EnsurePeerman(node);
515
516 const BlockHash block_hash{
517 ParseHashV(request.params[0], "blockhash")};
518 const NodeId peer_id{request.params[1].getInt<int64_t>()};
519
520 const CBlockIndex *const index = WITH_LOCK(
521 cs_main,
522 return chainman.m_blockman.LookupBlockIndex(block_hash););
523
524 if (!index) {
525 throw JSONRPCError(RPC_MISC_ERROR, "Block header missing");
526 }
527
528 if (WITH_LOCK(::cs_main, return index->nStatus.hasData())) {
529 throw JSONRPCError(RPC_MISC_ERROR, "Block already downloaded");
530 }
531
532 if (const auto err{peerman.FetchBlock(config, peer_id, *index)}) {
533 throw JSONRPCError(RPC_MISC_ERROR, err.value());
534 }
535 return UniValue::VOBJ;
536 },
537 };
538}
539
541 return RPCHelpMan{
542 "getblockhash",
543 "Returns hash of block in best-block-chain at height provided.\n",
544 {
546 "The height index"},
547 },
548 RPCResult{RPCResult::Type::STR_HEX, "", "The block hash"},
549 RPCExamples{HelpExampleCli("getblockhash", "1000") +
550 HelpExampleRpc("getblockhash", "1000")},
551 [&](const RPCHelpMan &self, const Config &config,
552 const JSONRPCRequest &request) -> UniValue {
553 ChainstateManager &chainman = EnsureAnyChainman(request.context);
554 LOCK(cs_main);
555 const CChain &active_chain = chainman.ActiveChain();
556
557 int nHeight = request.params[0].getInt<int>();
558 if (nHeight < 0 || nHeight > active_chain.Height()) {
560 "Block height out of range");
561 }
562
563 const CBlockIndex *pblockindex = active_chain[nHeight];
564 return pblockindex->GetBlockHash().GetHex();
565 },
566 };
567}
568
570 return RPCHelpMan{
571 "getblockheader",
572 "If verbose is false, returns a string that is serialized, hex-encoded "
573 "data for blockheader 'hash'.\n"
574 "If verbose is true, returns an Object with information about "
575 "blockheader <hash>.\n",
576 {
578 "The block hash"},
579 {"verbose", RPCArg::Type::BOOL, RPCArg::Default{true},
580 "true for a json object, false for the hex-encoded data"},
581 },
582 {
583 RPCResult{
584 "for verbose = true",
586 "",
587 "",
588 {
590 "the block hash (same as provided)"},
591 {RPCResult::Type::NUM, "confirmations",
592 "The number of confirmations, or -1 if the block is not "
593 "on the main chain"},
594 {RPCResult::Type::NUM, "height",
595 "The block height or index"},
596 {RPCResult::Type::NUM, "version", "The block version"},
597 {RPCResult::Type::STR_HEX, "versionHex",
598 "The block version formatted in hexadecimal"},
599 {RPCResult::Type::STR_HEX, "merkleroot", "The merkle root"},
601 "The block time expressed in " + UNIX_EPOCH_TIME},
602 {RPCResult::Type::NUM_TIME, "mediantime",
603 "The median block time expressed in " + UNIX_EPOCH_TIME},
604 {RPCResult::Type::NUM, "nonce", "The nonce"},
605 {RPCResult::Type::STR_HEX, "bits", "The bits"},
606 {RPCResult::Type::NUM, "difficulty", "The difficulty"},
607 {RPCResult::Type::STR_HEX, "chainwork",
608 "Expected number of hashes required to produce the "
609 "current chain"},
610 {RPCResult::Type::NUM, "nTx",
611 "The number of transactions in the block"},
612 {RPCResult::Type::STR_HEX, "previousblockhash",
613 /* optional */ true,
614 "The hash of the previous block (if available)"},
615 {RPCResult::Type::STR_HEX, "nextblockhash",
616 /* optional */ true,
617 "The hash of the next block (if available)"},
618 }},
619 RPCResult{"for verbose=false", RPCResult::Type::STR_HEX, "",
620 "A string that is serialized, hex-encoded data for block "
621 "'hash'"},
622 },
623 RPCExamples{HelpExampleCli("getblockheader",
624 "\"00000000c937983704a73af28acdec37b049d214a"
625 "dbda81d7e2a3dd146f6ed09\"") +
626 HelpExampleRpc("getblockheader",
627 "\"00000000c937983704a73af28acdec37b049d214a"
628 "dbda81d7e2a3dd146f6ed09\"")},
629 [&](const RPCHelpMan &self, const Config &config,
630 const JSONRPCRequest &request) -> UniValue {
631 BlockHash hash(ParseHashV(request.params[0], "hash"));
632
633 bool fVerbose = true;
634 if (!request.params[1].isNull()) {
635 fVerbose = request.params[1].get_bool();
636 }
637
638 const CBlockIndex *pblockindex;
639 const CBlockIndex *tip;
640 {
641 ChainstateManager &chainman =
642 EnsureAnyChainman(request.context);
643 LOCK(cs_main);
644 pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
645 tip = chainman.ActiveTip();
646 }
647
648 if (!pblockindex) {
650 "Block not found");
651 }
652
653 if (!fVerbose) {
654 DataStream ssBlock{};
655 ssBlock << pblockindex->GetBlockHeader();
656 std::string strHex = HexStr(ssBlock);
657 return strHex;
658 }
659
660 return blockheaderToJSON(*tip, *pblockindex);
661 },
662 };
663}
664
666 const CBlockIndex &blockindex) {
667 CBlock block;
668 {
669 LOCK(cs_main);
670 if (blockman.IsBlockPruned(blockindex)) {
672 "Block not available (pruned data)");
673 }
674 }
675
676 if (!blockman.ReadBlock(block, blockindex)) {
677 // Block not found on disk. This could be because we have the block
678 // header in our index but not yet have the block or did not accept the
679 // block. Or if the block was pruned right after we released the lock
680 // above.
681 throw JSONRPCError(RPC_MISC_ERROR, "Block not found on disk");
682 }
683
684 return block;
685}
686
688 const CBlockIndex &blockindex) {
689 CBlockUndo blockUndo;
690
691 {
692 LOCK(cs_main);
693 if (blockman.IsBlockPruned(blockindex)) {
695 "Undo data not available (pruned data)");
696 }
697 }
698
699 if (!blockman.ReadBlockUndo(blockUndo, blockindex)) {
700 throw JSONRPCError(RPC_MISC_ERROR, "Can't read undo data from disk");
701 }
702
703 return blockUndo;
704}
705
707 return RPCHelpMan{
708 "getblock",
709 "If verbosity is 0 or false, returns a string that is serialized, "
710 "hex-encoded data for block 'hash'.\n"
711 "If verbosity is 1 or true, returns an Object with information about "
712 "block <hash>.\n"
713 "If verbosity is 2, returns an Object with information about block "
714 "<hash> and information about each transaction.\n"
715 "If verbosity is 3, returns an Object with information about block "
716 "<hash> and information about each transaction, including prevout "
717 "information for inputs (only for unpruned blocks in the current best "
718 "chain).\n",
719 {
721 "The block hash"},
722 {"verbosity|verbose", RPCArg::Type::NUM, RPCArg::Default{1},
723 "0 for hex-encoded data, 1 for a json object, and 2 for json "
724 "object with transaction data",
726 },
727 {
728 RPCResult{"for verbosity = 0", RPCResult::Type::STR_HEX, "",
729 "A string that is serialized, hex-encoded data for block "
730 "'hash'"},
731 RPCResult{
732 "for verbosity = 1",
734 "",
735 "",
736 {
738 "the block hash (same as provided)"},
739 {RPCResult::Type::NUM, "confirmations",
740 "The number of confirmations, or -1 if the block is not "
741 "on the main chain"},
742 {RPCResult::Type::NUM, "size", "The block size"},
743 {RPCResult::Type::NUM, "height",
744 "The block height or index"},
745 {RPCResult::Type::NUM, "version", "The block version"},
746 {RPCResult::Type::STR_HEX, "versionHex",
747 "The block version formatted in hexadecimal"},
748 {RPCResult::Type::STR_HEX, "merkleroot", "The merkle root"},
750 "tx",
751 "The transaction ids",
752 {{RPCResult::Type::STR_HEX, "", "The transaction id"}}},
754 "The block time expressed in " + UNIX_EPOCH_TIME},
755 {RPCResult::Type::NUM_TIME, "mediantime",
756 "The median block time expressed in " + UNIX_EPOCH_TIME},
757 {RPCResult::Type::NUM, "nonce", "The nonce"},
758 {RPCResult::Type::STR_HEX, "bits", "The bits"},
759 {RPCResult::Type::NUM, "difficulty", "The difficulty"},
760 {RPCResult::Type::STR_HEX, "chainwork",
761 "Expected number of hashes required to produce the chain "
762 "up to this block (in hex)"},
763 {RPCResult::Type::NUM, "nTx",
764 "The number of transactions in the block"},
765 {RPCResult::Type::STR_HEX, "previousblockhash",
766 /* optional */ true,
767 "The hash of the previous block (if available)"},
768 {RPCResult::Type::STR_HEX, "nextblockhash",
769 /* optional */ true,
770 "The hash of the next block (if available)"},
771 }},
772 RPCResult{"for verbosity = 2",
774 "",
775 "",
776 {
778 "Same output as verbosity = 1"},
780 "tx",
781 "",
782 {
784 "",
785 "",
786 {
788 "The transactions in the format of the "
789 "getrawtransaction RPC. Different from "
790 "verbosity = 1 \"tx\" result"},
792 "The transaction fee in " +
794 ", omitted if block undo data is not "
795 "available"},
796 }},
797 }},
798 }},
799 },
801 HelpExampleCli("getblock", "\"00000000c937983704a73af28acdec37b049d"
802 "214adbda81d7e2a3dd146f6ed09\"") +
803 HelpExampleRpc("getblock", "\"00000000c937983704a73af28acdec37b049d"
804 "214adbda81d7e2a3dd146f6ed09\"")},
805 [&](const RPCHelpMan &self, const Config &config,
806 const JSONRPCRequest &request) -> UniValue {
807 BlockHash hash(ParseHashV(request.params[0], "blockhash"));
808
809 int verbosity{ParseVerbosity(request.params[1],
810 /*default_verbosity=*/1,
811 /*allow_bool=*/true)};
812
813 const CBlockIndex *pblockindex;
814 const CBlockIndex *tip;
815 ChainstateManager &chainman = EnsureAnyChainman(request.context);
816 {
817 LOCK(cs_main);
818 pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
819 tip = chainman.ActiveTip();
820
821 if (!pblockindex) {
823 "Block not found");
824 }
825 }
826
827 const CBlock block =
828 GetBlockChecked(chainman.m_blockman, *pblockindex);
829
830 if (verbosity <= 0) {
831 DataStream ssBlock{};
832 ssBlock << block;
833 std::string strHex = HexStr(ssBlock);
834 return strHex;
835 }
836
837 TxVerbosity tx_verbosity;
838 if (verbosity == 1) {
839 tx_verbosity = TxVerbosity::SHOW_TXID;
840 } else if (verbosity == 2) {
841 tx_verbosity = TxVerbosity::SHOW_DETAILS;
842 } else {
844 }
845
846 return blockToJSON(chainman.m_blockman, block, *tip, *pblockindex,
847 tx_verbosity);
848 },
849 };
850}
851
852std::optional<int> GetPruneHeight(const BlockManager &blockman,
853 const CChain &chain) {
855
856 // Search for the last block missing block data or undo data. Don't let the
857 // search consider the genesis block, because the genesis block does not
858 // have undo data, but should not be considered pruned.
859 const CBlockIndex *first_block{chain[1]};
860 const CBlockIndex *chain_tip{chain.Tip()};
861
862 // If there are no blocks after the genesis block, or no blocks at all,
863 // nothing is pruned.
864 if (!first_block || !chain_tip) {
865 return std::nullopt;
866 }
867
868 // If the chain tip is pruned, everything is pruned.
869 if (!(chain_tip->nStatus.hasData() && chain_tip->nStatus.hasUndo())) {
870 return chain_tip->nHeight;
871 }
872
873 // Get first block with data, after the last block without data.
874 // This is the start of the unpruned range of blocks.
875 const CBlockIndex *first_unpruned{CHECK_NONFATAL(
876 blockman.GetFirstBlock(*chain_tip,
877 /*status_test=*/[](const BlockStatus &status) {
878 return status.hasData() && status.hasUndo();
879 }))};
880 if (first_unpruned == first_block) {
881 // All blocks between first_block and chain_tip have data, so nothing is
882 // pruned.
883 return std::nullopt;
884 }
885
886 // Block before the first unpruned block is the last pruned block.
887 return CHECK_NONFATAL(first_unpruned->pprev)->nHeight;
888}
889
891 return RPCHelpMan{
892 "pruneblockchain",
893 "",
894 {
896 "The block height to prune up to. May be set to a discrete "
897 "height, or to a " +
899 "\n"
900 " to prune blocks whose block time is at "
901 "least 2 hours older than the provided timestamp."},
902 },
903 RPCResult{RPCResult::Type::NUM, "", "Height of the last block pruned"},
904 RPCExamples{HelpExampleCli("pruneblockchain", "1000") +
905 HelpExampleRpc("pruneblockchain", "1000")},
906 [&](const RPCHelpMan &self, const Config &config,
907 const JSONRPCRequest &request) -> UniValue {
908 ChainstateManager &chainman = EnsureAnyChainman(request.context);
909 if (!chainman.m_blockman.IsPruneMode()) {
910 throw JSONRPCError(
912 "Cannot prune blocks because node is not in prune mode.");
913 }
914
915 LOCK(cs_main);
916 Chainstate &active_chainstate = chainman.ActiveChainstate();
917 CChain &active_chain = active_chainstate.m_chain;
918
919 int heightParam = request.params[0].getInt<int>();
920 if (heightParam < 0) {
922 "Negative block height.");
923 }
924
925 // Height value more than a billion is too high to be a block
926 // height, and too low to be a block time (corresponds to timestamp
927 // from Sep 2001).
928 if (heightParam > 1000000000) {
929 // Add a 2 hour buffer to include blocks which might have had
930 // old timestamps
931 const CBlockIndex *pindex = active_chain.FindEarliestAtLeast(
932 heightParam - TIMESTAMP_WINDOW, 0);
933 if (!pindex) {
935 "Could not find block with at least the "
936 "specified timestamp.");
937 }
938 heightParam = pindex->nHeight;
939 }
940
941 unsigned int height = (unsigned int)heightParam;
942 unsigned int chainHeight = (unsigned int)active_chain.Height();
943 if (chainHeight < config.GetChainParams().PruneAfterHeight()) {
945 "Blockchain is too short for pruning.");
946 } else if (height > chainHeight) {
947 throw JSONRPCError(
949 "Blockchain is shorter than the attempted prune height.");
950 } else if (height > chainHeight - MIN_BLOCKS_TO_KEEP) {
952 "Attempt to prune blocks close to the tip. "
953 "Retaining the minimum number of blocks.\n");
954 height = chainHeight - MIN_BLOCKS_TO_KEEP;
955 }
956
957 PruneBlockFilesManual(active_chainstate, height);
958 return GetPruneHeight(chainman.m_blockman, active_chain)
959 .value_or(-1);
960 },
961 };
962}
963
964static CoinStatsHashType ParseHashType(const std::string &hash_type_input) {
965 if (hash_type_input == "hash_serialized") {
966 return CoinStatsHashType::HASH_SERIALIZED;
967 } else if (hash_type_input == "muhash") {
968 return CoinStatsHashType::MUHASH;
969 } else if (hash_type_input == "none") {
970 return CoinStatsHashType::NONE;
971 } else {
972 throw JSONRPCError(
974 strprintf("%s is not a valid hash_type", hash_type_input));
975 }
976}
977
979 return RPCHelpMan{
980 "gettxoutsetinfo",
981 "Returns statistics about the unspent transaction output set.\n"
982 "Note this call may take some time if you are not using "
983 "coinstatsindex.\n",
984 {
985 {"hash_type", RPCArg::Type::STR, RPCArg::Default{"hash_serialized"},
986 "Which UTXO set hash should be calculated. Options: "
987 "'hash_serialized' (the legacy algorithm), 'muhash', 'none'."},
989 "The block hash or height of the target height (only available "
990 "with coinstatsindex).",
992 .type_str = {"", "string or numeric"}}},
993 {"use_index", RPCArg::Type::BOOL, RPCArg::Default{true},
994 "Use coinstatsindex, if available."},
995 },
996 RPCResult{
998 "",
999 "",
1000 {
1001 {RPCResult::Type::NUM, "height",
1002 "The current block height (index)"},
1003 {RPCResult::Type::STR_HEX, "bestblock",
1004 "The hash of the block at the tip of the chain"},
1005 {RPCResult::Type::NUM, "txouts",
1006 "The number of unspent transaction outputs"},
1007 {RPCResult::Type::NUM, "bogosize",
1008 "Database-independent, meaningless metric indicating "
1009 "the UTXO set size"},
1010 {RPCResult::Type::STR_HEX, "hash_serialized",
1011 /* optional */ true,
1012 "The serialized hash (only present if 'hash_serialized' "
1013 "hash_type is chosen)"},
1014 {RPCResult::Type::STR_HEX, "muhash", /* optional */ true,
1015 "The serialized hash (only present if 'muhash' "
1016 "hash_type is chosen)"},
1017 {RPCResult::Type::NUM, "transactions",
1018 "The number of transactions with unspent outputs (not "
1019 "available when coinstatsindex is used)"},
1020 {RPCResult::Type::NUM, "disk_size",
1021 "The estimated size of the chainstate on disk (not "
1022 "available when coinstatsindex is used)"},
1023 {RPCResult::Type::STR_AMOUNT, "total_amount",
1024 "The total amount"},
1025 {RPCResult::Type::STR_AMOUNT, "total_unspendable_amount",
1026 "The total amount of coins permanently excluded from the UTXO "
1027 "set (only available if coinstatsindex is used)"},
1029 "block_info",
1030 "Info on amounts in the block at this block height (only "
1031 "available if coinstatsindex is used)",
1032 {{RPCResult::Type::STR_AMOUNT, "prevout_spent",
1033 "Total amount of all prevouts spent in this block"},
1034 {RPCResult::Type::STR_AMOUNT, "coinbase",
1035 "Coinbase subsidy amount of this block"},
1036 {RPCResult::Type::STR_AMOUNT, "new_outputs_ex_coinbase",
1037 "Total amount of new outputs created by this block"},
1038 {RPCResult::Type::STR_AMOUNT, "unspendable",
1039 "Total amount of unspendable outputs created in this block"},
1041 "unspendables",
1042 "Detailed view of the unspendable categories",
1043 {
1044 {RPCResult::Type::STR_AMOUNT, "genesis_block",
1045 "The unspendable amount of the Genesis block subsidy"},
1047 "Transactions overridden by duplicates (no longer "
1048 "possible with BIP30)"},
1049 {RPCResult::Type::STR_AMOUNT, "scripts",
1050 "Amounts sent to scripts that are unspendable (for "
1051 "example OP_RETURN outputs)"},
1052 {RPCResult::Type::STR_AMOUNT, "unclaimed_rewards",
1053 "Fee rewards that miners did not claim in their "
1054 "coinbase transaction"},
1055 }}}},
1056 }},
1058 HelpExampleCli("gettxoutsetinfo", "") +
1059 HelpExampleCli("gettxoutsetinfo", R"("none")") +
1060 HelpExampleCli("gettxoutsetinfo", R"("none" 1000)") +
1062 "gettxoutsetinfo",
1063 R"("none" '"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"')") +
1064 HelpExampleRpc("gettxoutsetinfo", "") +
1065 HelpExampleRpc("gettxoutsetinfo", R"("none")") +
1066 HelpExampleRpc("gettxoutsetinfo", R"("none", 1000)") +
1068 "gettxoutsetinfo",
1069 R"("none", "00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09")")},
1070 [&](const RPCHelpMan &self, const Config &config,
1071 const JSONRPCRequest &request) -> UniValue {
1073
1074 const CBlockIndex *pindex{nullptr};
1075 const CoinStatsHashType hash_type{
1076 request.params[0].isNull()
1077 ? CoinStatsHashType::HASH_SERIALIZED
1078 : ParseHashType(request.params[0].get_str())};
1079 bool index_requested =
1080 request.params[2].isNull() || request.params[2].get_bool();
1081
1082 NodeContext &node = EnsureAnyNodeContext(request.context);
1084 Chainstate &active_chainstate = chainman.ActiveChainstate();
1085 active_chainstate.ForceFlushStateToDisk();
1086
1087 CCoinsView *coins_view;
1088 BlockManager *blockman;
1089 {
1090 LOCK(::cs_main);
1091 coins_view = &active_chainstate.CoinsDB();
1092 blockman = &active_chainstate.m_blockman;
1093 pindex = blockman->LookupBlockIndex(coins_view->GetBestBlock());
1094 }
1095
1096 if (!request.params[1].isNull()) {
1097 if (!g_coin_stats_index) {
1099 "Querying specific block heights "
1100 "requires coinstatsindex");
1101 }
1102
1103 if (hash_type == CoinStatsHashType::HASH_SERIALIZED) {
1105 "hash_serialized hash type cannot be "
1106 "queried for a specific block");
1107 }
1108
1109 pindex = ParseHashOrHeight(request.params[1], chainman);
1110 }
1111
1112 if (index_requested && g_coin_stats_index) {
1113 if (!g_coin_stats_index->BlockUntilSyncedToCurrentChain()) {
1114 const IndexSummary summary{
1115 g_coin_stats_index->GetSummary()};
1116
1117 // If a specific block was requested and the index has
1118 // already synced past that height, we can return the data
1119 // already even though the index is not fully synced yet.
1120 if (pindex->nHeight > summary.best_block_height) {
1121 throw JSONRPCError(
1123 strprintf(
1124 "Unable to get data because coinstatsindex is "
1125 "still syncing. Current height: %d",
1126 summary.best_block_height));
1127 }
1128 }
1129 }
1130
1131 const std::optional<CCoinsStats> maybe_stats = GetUTXOStats(
1132 coins_view, *blockman, hash_type, node.rpc_interruption_point,
1133 pindex, index_requested);
1134 if (maybe_stats.has_value()) {
1135 const CCoinsStats &stats = maybe_stats.value();
1136 ret.pushKV("height", int64_t(stats.nHeight));
1137 ret.pushKV("bestblock", stats.hashBlock.GetHex());
1138 ret.pushKV("txouts", int64_t(stats.nTransactionOutputs));
1139 ret.pushKV("bogosize", int64_t(stats.nBogoSize));
1140 if (hash_type == CoinStatsHashType::HASH_SERIALIZED) {
1141 ret.pushKV("hash_serialized",
1142 stats.hashSerialized.GetHex());
1143 }
1144 if (hash_type == CoinStatsHashType::MUHASH) {
1145 ret.pushKV("muhash", stats.hashSerialized.GetHex());
1146 }
1147 CHECK_NONFATAL(stats.total_amount.has_value());
1148 ret.pushKV("total_amount", stats.total_amount.value());
1149 if (!stats.index_used) {
1150 ret.pushKV("transactions",
1151 static_cast<int64_t>(stats.nTransactions));
1152 ret.pushKV("disk_size", stats.nDiskSize);
1153 } else {
1154 ret.pushKV("total_unspendable_amount",
1156
1157 CCoinsStats prev_stats{};
1158 if (pindex->nHeight > 0) {
1159 const std::optional<CCoinsStats> maybe_prev_stats =
1160 GetUTXOStats(coins_view, *blockman, hash_type,
1161 node.rpc_interruption_point,
1162 pindex->pprev, index_requested);
1163 if (!maybe_prev_stats) {
1165 "Unable to read UTXO set");
1166 }
1167 prev_stats = maybe_prev_stats.value();
1168 }
1169
1170 UniValue block_info(UniValue::VOBJ);
1171 block_info.pushKV(
1172 "prevout_spent",
1174 prev_stats.total_prevout_spent_amount);
1175 block_info.pushKV("coinbase",
1176 stats.total_coinbase_amount -
1177 prev_stats.total_coinbase_amount);
1178 block_info.pushKV(
1179 "new_outputs_ex_coinbase",
1181 prev_stats.total_new_outputs_ex_coinbase_amount);
1182 block_info.pushKV("unspendable",
1184 prev_stats.total_unspendable_amount);
1185
1186 UniValue unspendables(UniValue::VOBJ);
1187 unspendables.pushKV(
1188 "genesis_block",
1190 prev_stats.total_unspendables_genesis_block);
1191 unspendables.pushKV(
1192 "bip30", stats.total_unspendables_bip30 -
1193 prev_stats.total_unspendables_bip30);
1194 unspendables.pushKV(
1195 "scripts", stats.total_unspendables_scripts -
1196 prev_stats.total_unspendables_scripts);
1197 unspendables.pushKV(
1198 "unclaimed_rewards",
1200 prev_stats.total_unspendables_unclaimed_rewards);
1201 block_info.pushKV("unspendables", std::move(unspendables));
1202
1203 ret.pushKV("block_info", std::move(block_info));
1204 }
1205 } else {
1207 "Unable to read UTXO set");
1208 }
1209 return ret;
1210 },
1211 };
1212}
1213
1215 return RPCHelpMan{
1216 "gettxout",
1217 "Returns details about an unspent transaction output.\n",
1218 {
1220 "The transaction id"},
1221 {"n", RPCArg::Type::NUM, RPCArg::Optional::NO, "vout number"},
1222 {"include_mempool", RPCArg::Type::BOOL, RPCArg::Default{true},
1223 "Whether to include the mempool. Note that an unspent output that "
1224 "is spent in the mempool won't appear."},
1225 },
1226 {
1227 RPCResult{"If the UTXO was not found", RPCResult::Type::NONE, "",
1228 ""},
1229 RPCResult{
1230 "Otherwise",
1232 "",
1233 "",
1234 {
1235 {RPCResult::Type::STR_HEX, "bestblock",
1236 "The hash of the block at the tip of the chain"},
1237 {RPCResult::Type::NUM, "confirmations",
1238 "The number of confirmations"},
1240 "The transaction value in " + Currency::getTicker()},
1242 "scriptPubKey",
1243 "",
1244 {
1245 {RPCResult::Type::STR_HEX, "asm", ""},
1246 {RPCResult::Type::STR_HEX, "hex", ""},
1247 {RPCResult::Type::NUM, "reqSigs",
1248 "Number of required signatures"},
1249 {RPCResult::Type::STR_HEX, "type",
1250 "The type, eg pubkeyhash"},
1252 "addresses",
1253 "array of eCash addresses",
1254 {{RPCResult::Type::STR, "address", "eCash address"}}},
1255 }},
1256 {RPCResult::Type::BOOL, "coinbase", "Coinbase or not"},
1257 }},
1258 },
1259 RPCExamples{"\nGet unspent transactions\n" +
1260 HelpExampleCli("listunspent", "") + "\nView the details\n" +
1261 HelpExampleCli("gettxout", "\"txid\" 1") +
1262 "\nAs a JSON-RPC call\n" +
1263 HelpExampleRpc("gettxout", "\"txid\", 1")},
1264 [&](const RPCHelpMan &self, const Config &config,
1265 const JSONRPCRequest &request) -> UniValue {
1266 NodeContext &node = EnsureAnyNodeContext(request.context);
1268 LOCK(cs_main);
1269
1271
1272 TxId txid(ParseHashV(request.params[0], "txid"));
1273 int n = request.params[1].getInt<int>();
1274 COutPoint out(txid, n);
1275 bool fMempool = true;
1276 if (!request.params[2].isNull()) {
1277 fMempool = request.params[2].get_bool();
1278 }
1279
1280 Chainstate &active_chainstate = chainman.ActiveChainstate();
1281 CCoinsViewCache *coins_view = &active_chainstate.CoinsTip();
1282
1283 std::optional<Coin> coin;
1284 if (fMempool) {
1285 const CTxMemPool &mempool = EnsureMemPool(node);
1286 LOCK(mempool.cs);
1287 CCoinsViewMemPool view(coins_view, mempool);
1288 if (!mempool.isSpent(out)) {
1289 coin = view.GetCoin(out);
1290 }
1291 } else {
1292 coin = coins_view->GetCoin(out);
1293 }
1294 if (!coin) {
1295 return UniValue::VNULL;
1296 }
1297
1298 const CBlockIndex *pindex =
1299 active_chainstate.m_blockman.LookupBlockIndex(
1300 coins_view->GetBestBlock());
1301 ret.pushKV("bestblock", pindex->GetBlockHash().GetHex());
1302 if (coin->GetHeight() == MEMPOOL_HEIGHT) {
1303 ret.pushKV("confirmations", 0);
1304 } else {
1305 ret.pushKV("confirmations",
1306 int64_t(pindex->nHeight - coin->GetHeight() + 1));
1307 }
1308 ret.pushKV("value", coin->GetTxOut().nValue);
1310 ScriptPubKeyToUniv(coin->GetTxOut().scriptPubKey, o, true);
1311 ret.pushKV("scriptPubKey", std::move(o));
1312 ret.pushKV("coinbase", coin->IsCoinBase());
1313
1314 return ret;
1315 },
1316 };
1317}
1318
1320 return RPCHelpMan{
1321 "verifychain",
1322 "Verifies blockchain database.\n",
1323 {
1324 {"checklevel", RPCArg::Type::NUM,
1326 strprintf("%d, range=0-4", DEFAULT_CHECKLEVEL)},
1327 strprintf("How thorough the block verification is:\n%s",
1328 MakeUnorderedList(CHECKLEVEL_DOC))},
1329 {"nblocks", RPCArg::Type::NUM,
1331 "The number of blocks to check."},
1332 },
1334 "Verification finished successfully. If false, check "
1335 "debug.log for reason."},
1336 RPCExamples{HelpExampleCli("verifychain", "") +
1337 HelpExampleRpc("verifychain", "")},
1338 [&](const RPCHelpMan &self, const Config &config,
1339 const JSONRPCRequest &request) -> UniValue {
1340 const int check_level{request.params[0].isNull()
1342 : request.params[0].getInt<int>()};
1343 const int check_depth{request.params[1].isNull()
1345 : request.params[1].getInt<int>()};
1346
1347 ChainstateManager &chainman = EnsureAnyChainman(request.context);
1348 LOCK(cs_main);
1349
1350 Chainstate &active_chainstate = chainman.ActiveChainstate();
1351 return CVerifyDB(chainman.GetNotifications())
1352 .VerifyDB(active_chainstate,
1353 active_chainstate.CoinsTip(), check_level,
1354 check_depth) == VerifyDBResult::SUCCESS;
1355 },
1356 };
1357}
1358
1360 return RPCHelpMan{
1361 "getblockchaininfo",
1362 "Returns an object containing various state info regarding blockchain "
1363 "processing.\n",
1364 {},
1365 RPCResult{
1367 "",
1368 "",
1369 {
1370 {RPCResult::Type::STR, "chain",
1371 "current network name (main, test, regtest)"},
1372 {RPCResult::Type::NUM, "blocks",
1373 "the height of the most-work fully-validated "
1374 "non-parked chain. The genesis block has height 0"},
1375 {RPCResult::Type::NUM, "headers",
1376 "the current number of headers we have validated"},
1377 {RPCResult::Type::NUM, "finalized_blockhash",
1378 "the hash of the avalanche finalized tip if any, otherwise "
1379 "the genesis block hash"},
1380 {RPCResult::Type::STR, "bestblockhash",
1381 "the hash of the currently best block"},
1382 {RPCResult::Type::NUM, "difficulty", "the current difficulty"},
1384 "The block time expressed in " + UNIX_EPOCH_TIME},
1385 {RPCResult::Type::NUM_TIME, "mediantime",
1386 "The median block time expressed in " + UNIX_EPOCH_TIME},
1387 {RPCResult::Type::NUM, "verificationprogress",
1388 "estimate of verification progress [0..1]"},
1389 {RPCResult::Type::BOOL, "initialblockdownload",
1390 "(debug information) estimate of whether this node is in "
1391 "Initial Block Download mode"},
1392 {RPCResult::Type::STR_HEX, "chainwork",
1393 "total amount of work in active chain, in hexadecimal"},
1394 {RPCResult::Type::NUM, "size_on_disk",
1395 "the estimated size of the block and undo files on disk"},
1396 {RPCResult::Type::BOOL, "pruned",
1397 "if the blocks are subject to pruning"},
1398 {RPCResult::Type::NUM, "pruneheight",
1399 "lowest-height complete block stored (only present if pruning "
1400 "is enabled)"},
1401 {RPCResult::Type::BOOL, "automatic_pruning",
1402 "whether automatic pruning is enabled (only present if "
1403 "pruning is enabled)"},
1404 {RPCResult::Type::NUM, "prune_target_size",
1405 "the target size used by pruning (only present if automatic "
1406 "pruning is enabled)"},
1407 {RPCResult::Type::STR, "warnings",
1408 "any network and blockchain warnings"},
1409 }},
1410 RPCExamples{HelpExampleCli("getblockchaininfo", "") +
1411 HelpExampleRpc("getblockchaininfo", "")},
1412 [&](const RPCHelpMan &self, const Config &config,
1413 const JSONRPCRequest &request) -> UniValue {
1414 const CChainParams &chainparams = config.GetChainParams();
1415
1416 ChainstateManager &chainman = EnsureAnyChainman(request.context);
1417 LOCK(cs_main);
1418 Chainstate &active_chainstate = chainman.ActiveChainstate();
1419
1420 const CBlockIndex &tip{
1421 *CHECK_NONFATAL(active_chainstate.m_chain.Tip())};
1422 const int height{tip.nHeight};
1423
1425 obj.pushKV("chain", chainparams.GetChainTypeString());
1426 obj.pushKV("blocks", height);
1427 obj.pushKV("headers", chainman.m_best_header
1428 ? chainman.m_best_header->nHeight
1429 : -1);
1430 auto avalanche_finalized_tip{chainman.GetAvalancheFinalizedTip()};
1431 obj.pushKV("finalized_blockhash",
1432 avalanche_finalized_tip
1433 ? avalanche_finalized_tip->GetBlockHash().GetHex()
1434 : chainparams.GenesisBlock().GetHash().GetHex());
1435 obj.pushKV("bestblockhash", tip.GetBlockHash().GetHex());
1436 obj.pushKV("difficulty", GetDifficulty(tip));
1437 obj.pushKV("time", tip.GetBlockTime());
1438 obj.pushKV("mediantime", tip.GetMedianTimePast());
1439 obj.pushKV(
1440 "verificationprogress",
1441 GuessVerificationProgress(chainman.GetParams().TxData(), &tip));
1442 obj.pushKV("initialblockdownload",
1443 chainman.IsInitialBlockDownload());
1444 obj.pushKV("chainwork", tip.nChainWork.GetHex());
1445 obj.pushKV("size_on_disk",
1447 obj.pushKV("pruned", chainman.m_blockman.IsPruneMode());
1448
1449 if (chainman.m_blockman.IsPruneMode()) {
1450 const auto prune_height{GetPruneHeight(
1451 chainman.m_blockman, active_chainstate.m_chain)};
1452 obj.pushKV("pruneheight",
1453 prune_height ? prune_height.value() + 1 : 0);
1454
1455 const bool automatic_pruning{
1456 chainman.m_blockman.GetPruneTarget() !=
1458 obj.pushKV("automatic_pruning", automatic_pruning);
1459 if (automatic_pruning) {
1460 obj.pushKV("prune_target_size",
1461 chainman.m_blockman.GetPruneTarget());
1462 }
1463 }
1464
1465 obj.pushKV("warnings", GetWarnings(false).original);
1466 return obj;
1467 },
1468 };
1469}
1470
1473 bool operator()(const CBlockIndex *a, const CBlockIndex *b) const {
1474 // Make sure that unequal blocks with the same height do not compare
1475 // equal. Use the pointers themselves to make a distinction.
1476 if (a->nHeight != b->nHeight) {
1477 return (a->nHeight > b->nHeight);
1478 }
1479
1480 return a < b;
1481 }
1482};
1483
1485 return RPCHelpMan{
1486 "getchaintips",
1487 "Return information about all known tips in the block tree, including "
1488 "the main chain as well as orphaned branches.\n",
1489 {},
1490 RPCResult{
1492 "",
1493 "",
1495 "",
1496 "",
1497 {
1498 {RPCResult::Type::NUM, "height", "height of the chain tip"},
1499 {RPCResult::Type::STR_HEX, "hash", "block hash of the tip"},
1500 {RPCResult::Type::NUM, "branchlen",
1501 "zero for main chain, otherwise length of branch connecting "
1502 "the tip to the main chain"},
1503 {RPCResult::Type::STR, "status",
1504 "status of the chain, \"active\" for the main chain\n"
1505 "Possible values for status:\n"
1506 "1. \"invalid\" This branch contains at "
1507 "least one invalid block\n"
1508 "2. \"parked\" This branch contains at "
1509 "least one parked block\n"
1510 "3. \"headers-only\" Not all blocks for this "
1511 "branch are available, but the headers are valid\n"
1512 "4. \"valid-headers\" All blocks are available for "
1513 "this branch, but they were never fully validated\n"
1514 "5. \"valid-fork\" This branch is not part of "
1515 "the active chain, but is fully validated\n"
1516 "6. \"active\" This is the tip of the "
1517 "active main chain, which is certainly valid"},
1518 }}}},
1519 RPCExamples{HelpExampleCli("getchaintips", "") +
1520 HelpExampleRpc("getchaintips", "")},
1521 [&](const RPCHelpMan &self, const Config &config,
1522 const JSONRPCRequest &request) -> UniValue {
1523 ChainstateManager &chainman = EnsureAnyChainman(request.context);
1524 LOCK(cs_main);
1525 CChain &active_chain = chainman.ActiveChain();
1526
1538 std::set<const CBlockIndex *, CompareBlocksByHeight> setTips;
1539 std::set<const CBlockIndex *> setOrphans;
1540 std::set<const CBlockIndex *> setPrevs;
1541
1542 for (const auto &[_, block_index] : chainman.BlockIndex()) {
1543 if (!active_chain.Contains(&block_index)) {
1544 setOrphans.insert(&block_index);
1545 setPrevs.insert(block_index.pprev);
1546 }
1547 }
1548
1549 for (std::set<const CBlockIndex *>::iterator it =
1550 setOrphans.begin();
1551 it != setOrphans.end(); ++it) {
1552 if (setPrevs.erase(*it) == 0) {
1553 setTips.insert(*it);
1554 }
1555 }
1556
1557 // Always report the currently active tip.
1558 setTips.insert(active_chain.Tip());
1559
1560 /* Construct the output array. */
1562 for (const CBlockIndex *block : setTips) {
1564 obj.pushKV("height", block->nHeight);
1565 obj.pushKV("hash", block->phashBlock->GetHex());
1566
1567 const int branchLen =
1568 block->nHeight - active_chain.FindFork(block)->nHeight;
1569 obj.pushKV("branchlen", branchLen);
1570
1571 std::string status;
1572 if (active_chain.Contains(block)) {
1573 // This block is part of the currently active chain.
1574 status = "active";
1575 } else if (block->nStatus.isInvalid()) {
1576 // This block or one of its ancestors is invalid.
1577 status = "invalid";
1578 } else if (block->nStatus.isOnParkedChain()) {
1579 // This block or one of its ancestors is parked.
1580 status = "parked";
1581 } else if (!block->HaveNumChainTxs()) {
1582 // This block cannot be connected because full block data
1583 // for it or one of its parents is missing.
1584 status = "headers-only";
1585 } else if (block->IsValid(BlockValidity::SCRIPTS)) {
1586 // This block is fully validated, but no longer part of the
1587 // active chain. It was probably the active block once, but
1588 // was reorganized.
1589 status = "valid-fork";
1590 } else if (block->IsValid(BlockValidity::TREE)) {
1591 // The headers for this block are valid, but it has not been
1592 // validated. It was probably never part of the most-work
1593 // chain.
1594 status = "valid-headers";
1595 } else {
1596 // No clue.
1597 status = "unknown";
1598 }
1599 obj.pushKV("status", status);
1600
1601 res.push_back(std::move(obj));
1602 }
1603
1604 return res;
1605 },
1606 };
1607}
1608
1610 return RPCHelpMan{
1611 "preciousblock",
1612 "Treats a block as if it were received before others with the same "
1613 "work.\n"
1614 "\nA later preciousblock call can override the effect of an earlier "
1615 "one.\n"
1616 "\nThe effects of preciousblock are not retained across restarts.\n",
1617 {
1619 "the hash of the block to mark as precious"},
1620 },
1622 RPCExamples{HelpExampleCli("preciousblock", "\"blockhash\"") +
1623 HelpExampleRpc("preciousblock", "\"blockhash\"")},
1624 [&](const RPCHelpMan &self, const Config &config,
1625 const JSONRPCRequest &request) -> UniValue {
1626 BlockHash hash(ParseHashV(request.params[0], "blockhash"));
1627 CBlockIndex *pblockindex;
1628
1629 NodeContext &node = EnsureAnyNodeContext(request.context);
1631 {
1632 LOCK(cs_main);
1633 pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
1634 if (!pblockindex) {
1636 "Block not found");
1637 }
1638 }
1639
1641 chainman.ActiveChainstate().PreciousBlock(state, pblockindex,
1642 node.avalanche.get());
1643
1644 if (!state.IsValid()) {
1646 }
1647
1648 // Block to make sure wallet/indexers sync before returning
1649 CHECK_NONFATAL(node.validation_signals)
1650 ->SyncWithValidationInterfaceQueue();
1651
1652 return NullUniValue;
1653 },
1654 };
1655}
1656
1659 const BlockHash &block_hash) {
1661 CBlockIndex *pblockindex;
1662 {
1663 LOCK(chainman.GetMutex());
1664 pblockindex = chainman.m_blockman.LookupBlockIndex(block_hash);
1665 if (!pblockindex) {
1666 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
1667 }
1668 }
1669 chainman.ActiveChainstate().InvalidateBlock(state, pblockindex);
1670
1671 if (state.IsValid()) {
1672 chainman.ActiveChainstate().ActivateBestChain(state, /*pblock=*/nullptr,
1673 avalanche);
1674 }
1675
1676 if (!state.IsValid()) {
1678 }
1679}
1680
1682 return RPCHelpMan{
1683 "invalidateblock",
1684 "Permanently marks a block as invalid, as if it violated a consensus "
1685 "rule.\n",
1686 {
1688 "the hash of the block to mark as invalid"},
1689 },
1691 RPCExamples{HelpExampleCli("invalidateblock", "\"blockhash\"") +
1692 HelpExampleRpc("invalidateblock", "\"blockhash\"")},
1693 [&](const RPCHelpMan &self, const Config &config,
1694 const JSONRPCRequest &request) -> UniValue {
1695 NodeContext &node = EnsureAnyNodeContext(request.context);
1697 const BlockHash hash(ParseHashV(request.params[0], "blockhash"));
1698
1699 InvalidateBlock(chainman, node.avalanche.get(), hash);
1700 // Block to make sure wallet/indexers sync before returning
1701 CHECK_NONFATAL(node.validation_signals)
1702 ->SyncWithValidationInterfaceQueue();
1703
1704 return NullUniValue;
1705 },
1706 };
1707}
1708
1710 return RPCHelpMan{
1711 "parkblock",
1712 "Marks a block as parked.\n",
1713 {
1715 "the hash of the block to park"},
1716 },
1718 RPCExamples{HelpExampleCli("parkblock", "\"blockhash\"") +
1719 HelpExampleRpc("parkblock", "\"blockhash\"")},
1720 [&](const RPCHelpMan &self, const Config &config,
1721 const JSONRPCRequest &request) -> UniValue {
1722 const std::string strHash = request.params[0].get_str();
1723 const BlockHash hash(uint256S(strHash));
1725
1726 NodeContext &node = EnsureAnyNodeContext(request.context);
1728 Chainstate &active_chainstate = chainman.ActiveChainstate();
1729 CBlockIndex *pblockindex = nullptr;
1730 {
1731 LOCK(cs_main);
1732 pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
1733 if (!pblockindex) {
1735 "Block not found");
1736 }
1737
1738 if (active_chainstate.IsBlockAvalancheFinalized(pblockindex)) {
1739 // Reset avalanche finalization if we park a finalized
1740 // block.
1741 active_chainstate.ClearAvalancheFinalizedBlock();
1742 }
1743 }
1744
1745 active_chainstate.ParkBlock(state, pblockindex);
1746
1747 if (state.IsValid()) {
1748 active_chainstate.ActivateBestChain(state, /*pblock=*/nullptr,
1749 node.avalanche.get());
1750 }
1751
1752 if (!state.IsValid()) {
1754 }
1755
1756 // Block to make sure wallet/indexers sync before returning
1757 CHECK_NONFATAL(node.validation_signals)
1758 ->SyncWithValidationInterfaceQueue();
1759
1760 return NullUniValue;
1761 },
1762 };
1763}
1764
1767 const BlockHash &block_hash) {
1768 {
1769 LOCK(chainman.GetMutex());
1770 CBlockIndex *pblockindex =
1771 chainman.m_blockman.LookupBlockIndex(block_hash);
1772 if (!pblockindex) {
1773 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
1774 }
1775
1776 chainman.ActiveChainstate().ResetBlockFailureFlags(pblockindex);
1777 chainman.RecalculateBestHeader();
1778 }
1779
1781 chainman.ActiveChainstate().ActivateBestChain(state, /*pblock=*/nullptr,
1782 avalanche);
1783
1784 if (!state.IsValid()) {
1786 }
1787}
1788
1790 return RPCHelpMan{
1791 "reconsiderblock",
1792 "Removes invalidity status of a block, its ancestors and its"
1793 "descendants, reconsider them for activation.\n"
1794 "This can be used to undo the effects of invalidateblock.\n",
1795 {
1797 "the hash of the block to reconsider"},
1798 },
1800 RPCExamples{HelpExampleCli("reconsiderblock", "\"blockhash\"") +
1801 HelpExampleRpc("reconsiderblock", "\"blockhash\"")},
1802 [&](const RPCHelpMan &self, const Config &config,
1803 const JSONRPCRequest &request) -> UniValue {
1804 NodeContext &node = EnsureAnyNodeContext(request.context);
1806 const BlockHash hash(ParseHashV(request.params[0], "blockhash"));
1807
1808 ReconsiderBlock(chainman, node.avalanche.get(), hash);
1809
1810 // Block to make sure wallet/indexers sync before returning
1811 CHECK_NONFATAL(node.validation_signals)
1812 ->SyncWithValidationInterfaceQueue();
1813
1814 return NullUniValue;
1815 },
1816 };
1817}
1818
1820 return RPCHelpMan{
1821 "unparkblock",
1822 "Removes parked status of a block and its descendants, reconsider "
1823 "them for activation.\n"
1824 "This can be used to undo the effects of parkblock.\n",
1825 {
1827 "the hash of the block to unpark"},
1828 },
1830 RPCExamples{HelpExampleCli("unparkblock", "\"blockhash\"") +
1831 HelpExampleRpc("unparkblock", "\"blockhash\"")},
1832 [&](const RPCHelpMan &self, const Config &config,
1833 const JSONRPCRequest &request) -> UniValue {
1834 const std::string strHash = request.params[0].get_str();
1835 NodeContext &node = EnsureAnyNodeContext(request.context);
1837 const BlockHash hash(uint256S(strHash));
1838 Chainstate &active_chainstate = chainman.ActiveChainstate();
1839
1840 {
1841 LOCK(cs_main);
1842
1843 CBlockIndex *pblockindex =
1844 chainman.m_blockman.LookupBlockIndex(hash);
1845 if (!pblockindex) {
1847 "Block not found");
1848 }
1849
1850 if (!pblockindex->nStatus.isOnParkedChain()) {
1851 // Block to unpark is not parked so there is nothing to do.
1852 return NullUniValue;
1853 }
1854
1855 const CBlockIndex *tip = active_chainstate.m_chain.Tip();
1856 if (tip) {
1857 const CBlockIndex *ancestor =
1858 LastCommonAncestor(tip, pblockindex);
1859 if (active_chainstate.IsBlockAvalancheFinalized(ancestor)) {
1860 // Only reset avalanche finalization if we unpark a
1861 // block that might conflict with avalanche finalized
1862 // blocks.
1863 active_chainstate.ClearAvalancheFinalizedBlock();
1864 }
1865 }
1866
1867 active_chainstate.UnparkBlockAndChildren(pblockindex);
1868 }
1869
1871 active_chainstate.ActivateBestChain(state, /*pblock=*/nullptr,
1872 node.avalanche.get());
1873
1874 if (!state.IsValid()) {
1876 }
1877
1878 // Block to make sure wallet/indexers sync before returning
1879 CHECK_NONFATAL(node.validation_signals)
1880 ->SyncWithValidationInterfaceQueue();
1881
1882 return NullUniValue;
1883 },
1884 };
1885}
1886
1888 return RPCHelpMan{
1889 "getchaintxstats",
1890 "Compute statistics about the total number and rate of transactions "
1891 "in the chain.\n",
1892 {
1893 {"nblocks", RPCArg::Type::NUM, RPCArg::DefaultHint{"one month"},
1894 "Size of the window in number of blocks"},
1895 {"blockhash", RPCArg::Type::STR_HEX,
1896 RPCArg::DefaultHint{"chain tip"},
1897 "The hash of the block that ends the window."},
1898 },
1899 RPCResult{
1901 "",
1902 "",
1903 {
1905 "The timestamp for the final block in the window, "
1906 "expressed in " +
1908 {RPCResult::Type::NUM, "txcount", /*optional=*/true,
1909 "The total number of transactions in the chain up to "
1910 "that point, if known. It may be unknown when using "
1911 "assumeutxo."},
1912 {RPCResult::Type::STR_HEX, "window_final_block_hash",
1913 "The hash of the final block in the window"},
1914 {RPCResult::Type::NUM, "window_final_block_height",
1915 "The height of the final block in the window."},
1916 {RPCResult::Type::NUM, "window_block_count",
1917 "Size of the window in number of blocks"},
1918 {RPCResult::Type::NUM, "window_interval",
1919 "The elapsed time in the window in seconds. Only "
1920 "returned if \"window_block_count\" is > 0"},
1921 {RPCResult::Type::NUM, "window_tx_count", /*optional=*/true,
1922 "The number of transactions in the window. Only "
1923 "returned if \"window_block_count\" is > 0 and if "
1924 "txcount exists for the start and end of the window."},
1925 {RPCResult::Type::NUM, "txrate", /*optional=*/true,
1926 "The average rate of transactions per second in the "
1927 "window. Only returned if \"window_interval\" is > 0 "
1928 "and if window_tx_count exists."},
1929 }},
1930 RPCExamples{HelpExampleCli("getchaintxstats", "") +
1931 HelpExampleRpc("getchaintxstats", "2016")},
1932 [&](const RPCHelpMan &self, const Config &config,
1933 const JSONRPCRequest &request) -> UniValue {
1934 ChainstateManager &chainman = EnsureAnyChainman(request.context);
1935 const CBlockIndex *pindex;
1936
1937 // By default: 1 month
1938 int blockcount =
1939 30 * 24 * 60 * 60 /
1940 config.GetChainParams().GetConsensus().nPowTargetSpacing;
1941
1942 if (request.params[1].isNull()) {
1943 LOCK(cs_main);
1944 pindex = chainman.ActiveTip();
1945 } else {
1946 BlockHash hash(ParseHashV(request.params[1], "blockhash"));
1947 LOCK(cs_main);
1948 pindex = chainman.m_blockman.LookupBlockIndex(hash);
1949 if (!pindex) {
1951 "Block not found");
1952 }
1953 if (!chainman.ActiveChain().Contains(pindex)) {
1955 "Block is not in main chain");
1956 }
1957 }
1958
1959 CHECK_NONFATAL(pindex != nullptr);
1960
1961 if (request.params[0].isNull()) {
1962 blockcount =
1963 std::max(0, std::min(blockcount, pindex->nHeight - 1));
1964 } else {
1965 blockcount = request.params[0].getInt<int>();
1966
1967 if (blockcount < 0 ||
1968 (blockcount > 0 && blockcount >= pindex->nHeight)) {
1970 "Invalid block count: "
1971 "should be between 0 and "
1972 "the block's height - 1");
1973 }
1974 }
1975
1976 const CBlockIndex &past_block{*CHECK_NONFATAL(
1977 pindex->GetAncestor(pindex->nHeight - blockcount))};
1978 const int64_t nTimeDiff{pindex->GetMedianTimePast() -
1979 past_block.GetMedianTimePast()};
1980
1982 ret.pushKV("time", pindex->GetBlockTime());
1983 if (pindex->m_chain_tx_count) {
1984 ret.pushKV("txcount", pindex->m_chain_tx_count);
1985 }
1986 ret.pushKV("window_final_block_hash",
1987 pindex->GetBlockHash().GetHex());
1988 ret.pushKV("window_final_block_height", pindex->nHeight);
1989 ret.pushKV("window_block_count", blockcount);
1990 if (blockcount > 0) {
1991 ret.pushKV("window_interval", nTimeDiff);
1992 if (pindex->m_chain_tx_count != 0 &&
1993 past_block.m_chain_tx_count != 0) {
1994 uint64_t window_tx_count =
1995 pindex->m_chain_tx_count - past_block.m_chain_tx_count;
1996 ret.pushKV("window_tx_count", window_tx_count);
1997 if (nTimeDiff > 0) {
1998 ret.pushKV("txrate",
1999 double(window_tx_count) / nTimeDiff);
2000 }
2001 }
2002 }
2003
2004 return ret;
2005 },
2006 };
2007}
2008
2009template <typename T>
2010static T CalculateTruncatedMedian(std::vector<T> &scores) {
2011 size_t size = scores.size();
2012 if (size == 0) {
2013 return T();
2014 }
2015
2016 std::sort(scores.begin(), scores.end());
2017 if (size % 2 == 0) {
2018 return (scores[size / 2 - 1] + scores[size / 2]) / 2;
2019 } else {
2020 return scores[size / 2];
2021 }
2022}
2023
2024template <typename T> static inline bool SetHasKeys(const std::set<T> &set) {
2025 return false;
2026}
2027template <typename T, typename Tk, typename... Args>
2028static inline bool SetHasKeys(const std::set<T> &set, const Tk &key,
2029 const Args &...args) {
2030 return (set.count(key) != 0) || SetHasKeys(set, args...);
2031}
2032
2033// outpoint (needed for the utxo index) + nHeight + fCoinBase
2034static constexpr size_t PER_UTXO_OVERHEAD =
2035 sizeof(COutPoint) + sizeof(uint32_t) + sizeof(bool);
2036
2038 const auto ticker = Currency::getTicker();
2039 return RPCHelpMan{
2040 "getblockstats",
2041 "Compute per block statistics for a given window. All amounts are "
2042 "in " +
2043 ticker +
2044 ".\n"
2045 "It won't work for some heights with pruning.\n",
2046 {
2047 {"hash_or_height", RPCArg::Type::NUM, RPCArg::Optional::NO,
2048 "The block hash or height of the target block",
2050 .type_str = {"", "string or numeric"}}},
2051 {"stats",
2053 RPCArg::DefaultHint{"all values"},
2054 "Values to plot (see result below)",
2055 {
2057 "Selected statistic"},
2059 "Selected statistic"},
2060 },
2062 },
2063 RPCResult{
2065 "",
2066 "",
2067 {
2068 {RPCResult::Type::NUM, "avgfee", "Average fee in the block"},
2069 {RPCResult::Type::NUM, "avgfeerate",
2070 "Average feerate (in satoshis per virtual byte)"},
2071 {RPCResult::Type::NUM, "avgtxsize", "Average transaction size"},
2072 {RPCResult::Type::STR_HEX, "blockhash",
2073 "The block hash (to check for potential reorgs)"},
2074 {RPCResult::Type::NUM, "height", "The height of the block"},
2075 {RPCResult::Type::NUM, "ins",
2076 "The number of inputs (excluding coinbase)"},
2077 {RPCResult::Type::NUM, "maxfee", "Maximum fee in the block"},
2078 {RPCResult::Type::NUM, "maxfeerate",
2079 "Maximum feerate (in satoshis per virtual byte)"},
2080 {RPCResult::Type::NUM, "maxtxsize", "Maximum transaction size"},
2081 {RPCResult::Type::NUM, "medianfee",
2082 "Truncated median fee in the block"},
2083 {RPCResult::Type::NUM, "medianfeerate",
2084 "Truncated median feerate (in " + ticker + " per byte)"},
2085 {RPCResult::Type::NUM, "mediantime",
2086 "The block median time past"},
2087 {RPCResult::Type::NUM, "mediantxsize",
2088 "Truncated median transaction size"},
2089 {RPCResult::Type::NUM, "minfee", "Minimum fee in the block"},
2090 {RPCResult::Type::NUM, "minfeerate",
2091 "Minimum feerate (in satoshis per virtual byte)"},
2092 {RPCResult::Type::NUM, "mintxsize", "Minimum transaction size"},
2093 {RPCResult::Type::NUM, "outs", "The number of outputs"},
2094 {RPCResult::Type::NUM, "subsidy", "The block subsidy"},
2095 {RPCResult::Type::NUM, "time", "The block time"},
2096 {RPCResult::Type::NUM, "total_out",
2097 "Total amount in all outputs (excluding coinbase and thus "
2098 "reward [ie subsidy + totalfee])"},
2099 {RPCResult::Type::NUM, "total_size",
2100 "Total size of all non-coinbase transactions"},
2101 {RPCResult::Type::NUM, "totalfee", "The fee total"},
2102 {RPCResult::Type::NUM, "txs",
2103 "The number of transactions (including coinbase)"},
2104 {RPCResult::Type::NUM, "utxo_increase",
2105 "The increase/decrease in the number of unspent outputs"},
2106 {RPCResult::Type::NUM, "utxo_size_inc",
2107 "The increase/decrease in size for the utxo index (not "
2108 "discounting op_return and similar)"},
2109 }},
2112 "getblockstats",
2113 R"('"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"' '["minfeerate","avgfeerate"]')") +
2114 HelpExampleCli("getblockstats",
2115 R"(1000 '["minfeerate","avgfeerate"]')") +
2117 "getblockstats",
2118 R"("00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09", ["minfeerate","avgfeerate"])") +
2119 HelpExampleRpc("getblockstats",
2120 R"(1000, ["minfeerate","avgfeerate"])")},
2121 [&](const RPCHelpMan &self, const Config &config,
2122 const JSONRPCRequest &request) -> UniValue {
2123 ChainstateManager &chainman = EnsureAnyChainman(request.context);
2124 const CBlockIndex &pindex{*CHECK_NONFATAL(
2125 ParseHashOrHeight(request.params[0], chainman))};
2126
2127 std::set<std::string> stats;
2128 if (!request.params[1].isNull()) {
2129 const UniValue stats_univalue = request.params[1].get_array();
2130 for (unsigned int i = 0; i < stats_univalue.size(); i++) {
2131 const std::string stat = stats_univalue[i].get_str();
2132 stats.insert(stat);
2133 }
2134 }
2135
2136 const CBlock &block = GetBlockChecked(chainman.m_blockman, pindex);
2137 const CBlockUndo &blockUndo =
2138 GetUndoChecked(chainman.m_blockman, pindex);
2139
2140 // Calculate everything if nothing selected (default)
2141 const bool do_all = stats.size() == 0;
2142 const bool do_mediantxsize =
2143 do_all || stats.count("mediantxsize") != 0;
2144 const bool do_medianfee = do_all || stats.count("medianfee") != 0;
2145 const bool do_medianfeerate =
2146 do_all || stats.count("medianfeerate") != 0;
2147 const bool loop_inputs =
2148 do_all || do_medianfee || do_medianfeerate ||
2149 SetHasKeys(stats, "utxo_size_inc", "totalfee", "avgfee",
2150 "avgfeerate", "minfee", "maxfee", "minfeerate",
2151 "maxfeerate");
2152 const bool loop_outputs =
2153 do_all || loop_inputs || stats.count("total_out");
2154 const bool do_calculate_size =
2155 do_mediantxsize || loop_inputs ||
2156 SetHasKeys(stats, "total_size", "avgtxsize", "mintxsize",
2157 "maxtxsize");
2158
2159 const int64_t blockMaxSize = config.GetMaxBlockSize();
2160 Amount maxfee = Amount::zero();
2161 Amount maxfeerate = Amount::zero();
2162 Amount minfee = MAX_MONEY;
2163 Amount minfeerate = MAX_MONEY;
2164 Amount total_out = Amount::zero();
2165 Amount totalfee = Amount::zero();
2166 int64_t inputs = 0;
2167 int64_t maxtxsize = 0;
2168 int64_t mintxsize = blockMaxSize;
2169 int64_t outputs = 0;
2170 int64_t total_size = 0;
2171 int64_t utxo_size_inc = 0;
2172 std::vector<Amount> fee_array;
2173 std::vector<Amount> feerate_array;
2174 std::vector<int64_t> txsize_array;
2175
2176 for (size_t i = 0; i < block.vtx.size(); ++i) {
2177 const auto &tx = block.vtx.at(i);
2178 outputs += tx->vout.size();
2179 Amount tx_total_out = Amount::zero();
2180 if (loop_outputs) {
2181 for (const CTxOut &out : tx->vout) {
2182 tx_total_out += out.nValue;
2183 utxo_size_inc +=
2185 }
2186 }
2187
2188 if (tx->IsCoinBase()) {
2189 continue;
2190 }
2191
2192 // Don't count coinbase's fake input
2193 inputs += tx->vin.size();
2194 // Don't count coinbase reward
2195 total_out += tx_total_out;
2196
2197 int64_t tx_size = 0;
2198 if (do_calculate_size) {
2199 tx_size = tx->GetTotalSize();
2200 if (do_mediantxsize) {
2201 txsize_array.push_back(tx_size);
2202 }
2203 maxtxsize = std::max(maxtxsize, tx_size);
2204 mintxsize = std::min(mintxsize, tx_size);
2205 total_size += tx_size;
2206 }
2207
2208 if (loop_inputs) {
2209 Amount tx_total_in = Amount::zero();
2210 const auto &txundo = blockUndo.vtxundo.at(i - 1);
2211 for (const Coin &coin : txundo.vprevout) {
2212 const CTxOut &prevoutput = coin.GetTxOut();
2213
2214 tx_total_in += prevoutput.nValue;
2215 utxo_size_inc -=
2216 GetSerializeSize(prevoutput) + PER_UTXO_OVERHEAD;
2217 }
2218
2219 Amount txfee = tx_total_in - tx_total_out;
2220 CHECK_NONFATAL(MoneyRange(txfee));
2221 if (do_medianfee) {
2222 fee_array.push_back(txfee);
2223 }
2224 maxfee = std::max(maxfee, txfee);
2225 minfee = std::min(minfee, txfee);
2226 totalfee += txfee;
2227
2228 Amount feerate = txfee / tx_size;
2229 if (do_medianfeerate) {
2230 feerate_array.push_back(feerate);
2231 }
2232 maxfeerate = std::max(maxfeerate, feerate);
2233 minfeerate = std::min(minfeerate, feerate);
2234 }
2235 }
2236
2237 UniValue ret_all(UniValue::VOBJ);
2238 ret_all.pushKV("avgfee",
2239 block.vtx.size() > 1
2240 ? (totalfee / int((block.vtx.size() - 1)))
2241 : Amount::zero());
2242 ret_all.pushKV("avgfeerate", total_size > 0
2243 ? (totalfee / total_size)
2244 : Amount::zero());
2245 ret_all.pushKV("avgtxsize",
2246 (block.vtx.size() > 1)
2247 ? total_size / (block.vtx.size() - 1)
2248 : 0);
2249 ret_all.pushKV("blockhash", pindex.GetBlockHash().GetHex());
2250 ret_all.pushKV("height", (int64_t)pindex.nHeight);
2251 ret_all.pushKV("ins", inputs);
2252 ret_all.pushKV("maxfee", maxfee);
2253 ret_all.pushKV("maxfeerate", maxfeerate);
2254 ret_all.pushKV("maxtxsize", maxtxsize);
2255 ret_all.pushKV("medianfee", CalculateTruncatedMedian(fee_array));
2256 ret_all.pushKV("medianfeerate",
2257 CalculateTruncatedMedian(feerate_array));
2258 ret_all.pushKV("mediantime", pindex.GetMedianTimePast());
2259 ret_all.pushKV("mediantxsize",
2260 CalculateTruncatedMedian(txsize_array));
2261 ret_all.pushKV("minfee",
2262 minfee == MAX_MONEY ? Amount::zero() : minfee);
2263 ret_all.pushKV("minfeerate", minfeerate == MAX_MONEY
2264 ? Amount::zero()
2265 : minfeerate);
2266 ret_all.pushKV("mintxsize",
2267 mintxsize == blockMaxSize ? 0 : mintxsize);
2268 ret_all.pushKV("outs", outputs);
2269 ret_all.pushKV("subsidy", GetBlockSubsidy(pindex.nHeight,
2270 chainman.GetConsensus()));
2271 ret_all.pushKV("time", pindex.GetBlockTime());
2272 ret_all.pushKV("total_out", total_out);
2273 ret_all.pushKV("total_size", total_size);
2274 ret_all.pushKV("totalfee", totalfee);
2275 ret_all.pushKV("txs", (int64_t)block.vtx.size());
2276 ret_all.pushKV("utxo_increase", outputs - inputs);
2277 ret_all.pushKV("utxo_size_inc", utxo_size_inc);
2278
2279 if (do_all) {
2280 return ret_all;
2281 }
2282
2284 for (const std::string &stat : stats) {
2285 const UniValue &value = ret_all[stat];
2286 if (value.isNull()) {
2287 throw JSONRPCError(
2289 strprintf("Invalid selected statistic %s", stat));
2290 }
2291 ret.pushKV(stat, value);
2292 }
2293 return ret;
2294 },
2295 };
2296}
2297
2298namespace {
2300static bool FindScriptPubKey(std::atomic<int> &scan_progress,
2301 const std::atomic<bool> &should_abort,
2302 int64_t &count, CCoinsViewCursor *cursor,
2303 const std::set<CScript> &needles,
2304 std::map<COutPoint, Coin> &out_results,
2305 std::function<void()> &interruption_point) {
2306 scan_progress = 0;
2307 count = 0;
2308 while (cursor->Valid()) {
2309 COutPoint key;
2310 Coin coin;
2311 if (!cursor->GetKey(key) || !cursor->GetValue(coin)) {
2312 return false;
2313 }
2314 if (++count % 8192 == 0) {
2315 interruption_point();
2316 if (should_abort) {
2317 // allow to abort the scan via the abort reference
2318 return false;
2319 }
2320 }
2321 if (count % 256 == 0) {
2322 // update progress reference every 256 item
2323 const TxId &txid = key.GetTxId();
2324 uint32_t high = 0x100 * *txid.begin() + *(txid.begin() + 1);
2325 scan_progress = int(high * 100.0 / 65536.0 + 0.5);
2326 }
2327 if (needles.count(coin.GetTxOut().scriptPubKey)) {
2328 out_results.emplace(key, coin);
2329 }
2330 cursor->Next();
2331 }
2332 scan_progress = 100;
2333 return true;
2334}
2335} // namespace
2336
2338static std::atomic<int> g_scan_progress;
2339static std::atomic<bool> g_scan_in_progress;
2340static std::atomic<bool> g_should_abort_scan;
2342private:
2343 bool m_could_reserve{false};
2344
2345public:
2346 explicit CoinsViewScanReserver() = default;
2347
2348 bool reserve() {
2350 if (g_scan_in_progress.exchange(true)) {
2351 return false;
2352 }
2353 m_could_reserve = true;
2354 return true;
2355 }
2356
2358 if (m_could_reserve) {
2359 g_scan_in_progress = false;
2360 }
2361 }
2362};
2363
2365 const auto ticker = Currency::getTicker();
2366 return RPCHelpMan{
2367 "scantxoutset",
2368 "Scans the unspent transaction output set for entries that match "
2369 "certain output descriptors.\n"
2370 "Examples of output descriptors are:\n"
2371 " addr(<address>) Outputs whose scriptPubKey "
2372 "corresponds to the specified address (does not include P2PK)\n"
2373 " raw(<hex script>) Outputs whose scriptPubKey "
2374 "equals the specified hex scripts\n"
2375 " combo(<pubkey>) P2PK and P2PKH outputs for "
2376 "the given pubkey\n"
2377 " pkh(<pubkey>) P2PKH outputs for the given "
2378 "pubkey\n"
2379 " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for "
2380 "the given threshold and pubkeys\n"
2381 "\nIn the above, <pubkey> either refers to a fixed public key in "
2382 "hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
2383 "or more path elements separated by \"/\", and optionally ending in "
2384 "\"/*\" (unhardened), or \"/*'\" or \"/*h\" (hardened) to specify all\n"
2385 "unhardened or hardened child keys.\n"
2386 "In the latter case, a range needs to be specified by below if "
2387 "different from 1000.\n"
2388 "For more information on output descriptors, see the documentation in "
2389 "the doc/descriptors.md file.\n",
2390 {
2392 "The action to execute\n"
2393 " \"start\" for starting a "
2394 "scan\n"
2395 " \"abort\" for aborting the "
2396 "current scan (returns true when abort was successful)\n"
2397 " \"status\" for "
2398 "progress report (in %) of the current scan"},
2399 {"scanobjects",
2402 "Array of scan objects. Required for \"start\" action\n"
2403 " Every scan object is either a "
2404 "string descriptor or an object:",
2405 {
2407 "An output descriptor"},
2408 {
2409 "",
2412 "An object with output descriptor and metadata",
2413 {
2415 "An output descriptor"},
2416 {"range", RPCArg::Type::RANGE, RPCArg::Default{1000},
2417 "The range of HD chain indexes to explore (either "
2418 "end or [begin,end])"},
2419 },
2420 },
2421 },
2422 RPCArgOptions{.oneline_description = "[scanobjects,...]"}},
2423 },
2424 {
2425 RPCResult{"When action=='abort'", RPCResult::Type::BOOL, "", ""},
2426 RPCResult{"When action=='status' and no scan is in progress",
2427 RPCResult::Type::NONE, "", ""},
2428 RPCResult{
2429 "When action=='status' and scan is in progress",
2431 "",
2432 "",
2433 {
2434 {RPCResult::Type::NUM, "progress", "The scan progress"},
2435 }},
2436 RPCResult{
2437 "When action=='start'",
2439 "",
2440 "",
2441 {
2442 {RPCResult::Type::BOOL, "success",
2443 "Whether the scan was completed"},
2444 {RPCResult::Type::NUM, "txouts",
2445 "The number of unspent transaction outputs scanned"},
2446 {RPCResult::Type::NUM, "height",
2447 "The current block height (index)"},
2448 {RPCResult::Type::STR_HEX, "bestblock",
2449 "The hash of the block at the tip of the chain"},
2451 "unspents",
2452 "",
2453 {
2455 "",
2456 "",
2457 {
2458 {RPCResult::Type::STR_HEX, "txid",
2459 "The transaction id"},
2460 {RPCResult::Type::NUM, "vout", "The vout value"},
2461 {RPCResult::Type::STR_HEX, "scriptPubKey",
2462 "The script key"},
2463 {RPCResult::Type::STR, "desc",
2464 "A specialized descriptor for the matched "
2465 "scriptPubKey"},
2466 {RPCResult::Type::STR_AMOUNT, "amount",
2467 "The total amount in " + ticker +
2468 " of the unspent output"},
2469 {RPCResult::Type::BOOL, "coinbase",
2470 "Whether this is a coinbase output"},
2471 {RPCResult::Type::NUM, "height",
2472 "Height of the unspent transaction output"},
2473 }},
2474 }},
2475 {RPCResult::Type::STR_AMOUNT, "total_amount",
2476 "The total amount of all found unspent outputs in " +
2477 ticker},
2478 }},
2479 },
2480 RPCExamples{""},
2481 [&](const RPCHelpMan &self, const Config &config,
2482 const JSONRPCRequest &request) -> UniValue {
2483 UniValue result(UniValue::VOBJ);
2484 const auto action{self.Arg<std::string>("action")};
2485 if (action == "status") {
2486 CoinsViewScanReserver reserver;
2487 if (reserver.reserve()) {
2488 // no scan in progress
2489 return NullUniValue;
2490 }
2491 result.pushKV("progress", g_scan_progress.load());
2492 return result;
2493 } else if (action == "abort") {
2494 CoinsViewScanReserver reserver;
2495 if (reserver.reserve()) {
2496 // reserve was possible which means no scan was running
2497 return false;
2498 }
2499 // set the abort flag
2500 g_should_abort_scan = true;
2501 return true;
2502 } else if (action == "start") {
2503 CoinsViewScanReserver reserver;
2504 if (!reserver.reserve()) {
2506 "Scan already in progress, use action "
2507 "\"abort\" or \"status\"");
2508 }
2509
2510 if (request.params.size() < 2) {
2512 "scanobjects argument is required for "
2513 "the start action");
2514 }
2515
2516 std::set<CScript> needles;
2517 std::map<CScript, std::string> descriptors;
2518 Amount total_in = Amount::zero();
2519
2520 // loop through the scan objects
2521 for (const UniValue &scanobject :
2522 request.params[1].get_array().getValues()) {
2523 FlatSigningProvider provider;
2524 auto scripts =
2525 EvalDescriptorStringOrObject(scanobject, provider);
2526 for (CScript &script : scripts) {
2527 std::string inferred =
2528 InferDescriptor(script, provider)->ToString();
2529 needles.emplace(script);
2530 descriptors.emplace(std::move(script),
2531 std::move(inferred));
2532 }
2533 }
2534
2535 // Scan the unspent transaction output set for inputs
2536 UniValue unspents(UniValue::VARR);
2537 std::vector<CTxOut> input_txos;
2538 std::map<COutPoint, Coin> coins;
2539 g_should_abort_scan = false;
2540 g_scan_progress = 0;
2541 int64_t count = 0;
2542 std::unique_ptr<CCoinsViewCursor> pcursor;
2543 const CBlockIndex *tip;
2544 NodeContext &node = EnsureAnyNodeContext(request.context);
2545 {
2547 LOCK(cs_main);
2548 Chainstate &active_chainstate = chainman.ActiveChainstate();
2549 active_chainstate.ForceFlushStateToDisk();
2550 pcursor = CHECK_NONFATAL(std::unique_ptr<CCoinsViewCursor>(
2551 active_chainstate.CoinsDB().Cursor()));
2552 tip = CHECK_NONFATAL(active_chainstate.m_chain.Tip());
2553 }
2554 bool res = FindScriptPubKey(
2555 g_scan_progress, g_should_abort_scan, count, pcursor.get(),
2556 needles, coins, node.rpc_interruption_point);
2557 result.pushKV("success", res);
2558 result.pushKV("txouts", count);
2559 result.pushKV("height", tip->nHeight);
2560 result.pushKV("bestblock", tip->GetBlockHash().GetHex());
2561
2562 for (const auto &it : coins) {
2563 const COutPoint &outpoint = it.first;
2564 const Coin &coin = it.second;
2565 const CTxOut &txo = coin.GetTxOut();
2566 input_txos.push_back(txo);
2567 total_in += txo.nValue;
2568
2569 UniValue unspent(UniValue::VOBJ);
2570 unspent.pushKV("txid", outpoint.GetTxId().GetHex());
2571 unspent.pushKV("vout", int32_t(outpoint.GetN()));
2572 unspent.pushKV("scriptPubKey", HexStr(txo.scriptPubKey));
2573 unspent.pushKV("desc", descriptors[txo.scriptPubKey]);
2574 unspent.pushKV("amount", txo.nValue);
2575 unspent.pushKV("coinbase", coin.IsCoinBase());
2576 unspent.pushKV("height", int32_t(coin.GetHeight()));
2577
2578 unspents.push_back(std::move(unspent));
2579 }
2580 result.pushKV("unspents", std::move(unspents));
2581 result.pushKV("total_amount", total_in);
2582 } else {
2584 strprintf("Invalid action '%s'", action));
2585 }
2586 return result;
2587 },
2588 };
2589}
2590
2592 return RPCHelpMan{
2593 "getblockfilter",
2594 "Retrieve a BIP 157 content filter for a particular block.\n",
2595 {
2597 "The hash of the block"},
2598 {"filtertype", RPCArg::Type::STR, RPCArg::Default{"basic"},
2599 "The type name of the filter"},
2600 },
2602 "",
2603 "",
2604 {
2605 {RPCResult::Type::STR_HEX, "filter",
2606 "the hex-encoded filter data"},
2607 {RPCResult::Type::STR_HEX, "header",
2608 "the hex-encoded filter header"},
2609 }},
2611 HelpExampleCli("getblockfilter",
2612 "\"00000000c937983704a73af28acdec37b049d214a"
2613 "dbda81d7e2a3dd146f6ed09\" \"basic\"") +
2614 HelpExampleRpc("getblockfilter",
2615 "\"00000000c937983704a73af28acdec37b049d214adbda81d7"
2616 "e2a3dd146f6ed09\", \"basic\"")},
2617 [&](const RPCHelpMan &self, const Config &config,
2618 const JSONRPCRequest &request) -> UniValue {
2619 const BlockHash block_hash(
2620 ParseHashV(request.params[0], "blockhash"));
2621 std::string filtertype_name = "basic";
2622 if (!request.params[1].isNull()) {
2623 filtertype_name = request.params[1].get_str();
2624 }
2625
2626 BlockFilterType filtertype;
2627 if (!BlockFilterTypeByName(filtertype_name, filtertype)) {
2629 "Unknown filtertype");
2630 }
2631
2632 BlockFilterIndex *index = GetBlockFilterIndex(filtertype);
2633 if (!index) {
2635 "Index is not enabled for filtertype " +
2636 filtertype_name);
2637 }
2638
2639 const CBlockIndex *block_index;
2640 bool block_was_connected;
2641 {
2642 ChainstateManager &chainman =
2643 EnsureAnyChainman(request.context);
2644 LOCK(cs_main);
2645 block_index = chainman.m_blockman.LookupBlockIndex(block_hash);
2646 if (!block_index) {
2648 "Block not found");
2649 }
2650 block_was_connected =
2651 block_index->IsValid(BlockValidity::SCRIPTS);
2652 }
2653
2654 bool index_ready = index->BlockUntilSyncedToCurrentChain();
2655
2656 BlockFilter filter;
2657 uint256 filter_header;
2658 if (!index->LookupFilter(block_index, filter) ||
2659 !index->LookupFilterHeader(block_index, filter_header)) {
2660 int err_code;
2661 std::string errmsg = "Filter not found.";
2662
2663 if (!block_was_connected) {
2664 err_code = RPC_INVALID_ADDRESS_OR_KEY;
2665 errmsg += " Block was not connected to active chain.";
2666 } else if (!index_ready) {
2667 err_code = RPC_MISC_ERROR;
2668 errmsg += " Block filters are still in the process of "
2669 "being indexed.";
2670 } else {
2671 err_code = RPC_INTERNAL_ERROR;
2672 errmsg += " This error is unexpected and indicates index "
2673 "corruption.";
2674 }
2675
2676 throw JSONRPCError(err_code, errmsg);
2677 }
2678
2680 ret.pushKV("filter", HexStr(filter.GetEncodedFilter()));
2681 ret.pushKV("header", filter_header.GetHex());
2682 return ret;
2683 },
2684 };
2685}
2686
2693
2694public:
2695 NetworkDisable(CConnman &connman) : m_connman(connman) {
2699 "Network activity could not be suspended.");
2700 }
2701 };
2703};
2704
2728
2735 return RPCHelpMan{
2736 "dumptxoutset",
2737 "Write the serialized UTXO set to a file. This can be used in "
2738 "loadtxoutset afterwards if this snapshot height is supported in the "
2739 "chainparams as well.\n\n"
2740 "Unless the the \"latest\" type is requested, the node will roll back "
2741 "to the requested height and network activity will be suspended during "
2742 "this process. "
2743 "Because of this it is discouraged to interact with the node in any "
2744 "other way during the execution of this call to avoid inconsistent "
2745 "results and race conditions, particularly RPCs that interact with "
2746 "blockstorage.\n\n"
2747 "This call may take several minutes. Make sure to use no RPC timeout "
2748 "(bitcoin-cli -rpcclienttimeout=0)",
2749
2750 {
2752 "path to the output file. If relative, will be prefixed by "
2753 "datadir."},
2754 {"type", RPCArg::Type::STR, RPCArg::Default(""),
2755 "The type of snapshot to create. Can be \"latest\" to create a "
2756 "snapshot of the current UTXO set or \"rollback\" to temporarily "
2757 "roll back the state of the node to a historical block before "
2758 "creating the snapshot of a historical UTXO set. This parameter "
2759 "can be omitted if a separate \"rollback\" named parameter is "
2760 "specified indicating the height or hash of a specific historical "
2761 "block. If \"rollback\" is specified and separate \"rollback\" "
2762 "named parameter is not specified, this will roll back to the "
2763 "latest valid snapshot block that can currently be loaded with "
2764 "loadtxoutset."},
2765 {
2766 "options",
2769 "",
2770 {
2772 "Height or hash of the block to roll back to before "
2773 "creating the snapshot. Note: The further this number is "
2774 "from the tip, the longer this process will take. "
2775 "Consider setting a higher -rpcclienttimeout value in "
2776 "this case.",
2778 .type_str = {"", "string or numeric"}}},
2779 },
2780 },
2781 },
2783 "",
2784 "",
2785 {
2786 {RPCResult::Type::NUM, "coins_written",
2787 "the number of coins written in the snapshot"},
2788 {RPCResult::Type::STR_HEX, "base_hash",
2789 "the hash of the base of the snapshot"},
2790 {RPCResult::Type::NUM, "base_height",
2791 "the height of the base of the snapshot"},
2792 {RPCResult::Type::STR, "path",
2793 "the absolute path that the snapshot was written to"},
2794 {RPCResult::Type::STR_HEX, "txoutset_hash",
2795 "the hash of the UTXO set contents"},
2796 {RPCResult::Type::NUM, "nchaintx",
2797 "the number of transactions in the chain up to and "
2798 "including the base block"},
2799 }},
2800 RPCExamples{HelpExampleCli("-rpcclienttimeout=0 dumptxoutset",
2801 "utxo.dat latest") +
2802 HelpExampleCli("-rpcclienttimeout=0 dumptxoutset",
2803 "utxo.dat rollback") +
2804 HelpExampleCli("-rpcclienttimeout=0 -named dumptxoutset",
2805 R"(utxo.dat rollback=853456)")},
2806 [&](const RPCHelpMan &self, const Config &config,
2807 const JSONRPCRequest &request) -> UniValue {
2808 NodeContext &node = EnsureAnyNodeContext(request.context);
2809 const CBlockIndex *tip{WITH_LOCK(
2810 ::cs_main, return node.chainman->ActiveChain().Tip())};
2811 const CBlockIndex *target_index{nullptr};
2812 const std::string snapshot_type{self.Arg<std::string>("type")};
2813 const UniValue options{request.params[2].isNull()
2815 : request.params[2]};
2816 if (options.exists("rollback")) {
2817 if (!snapshot_type.empty() && snapshot_type != "rollback") {
2818 throw JSONRPCError(
2820 strprintf("Invalid snapshot type \"%s\" specified with "
2821 "rollback option",
2822 snapshot_type));
2823 }
2824 target_index =
2825 ParseHashOrHeight(options["rollback"], *node.chainman);
2826 } else if (snapshot_type == "rollback") {
2827 auto snapshot_heights =
2828 node.chainman->GetParams().GetAvailableSnapshotHeights();
2829 CHECK_NONFATAL(snapshot_heights.size() > 0);
2830 auto max_height = std::max_element(snapshot_heights.begin(),
2831 snapshot_heights.end());
2832 target_index = ParseHashOrHeight(*max_height, *node.chainman);
2833 } else if (snapshot_type == "latest") {
2834 target_index = tip;
2835 } else {
2836 throw JSONRPCError(
2838 strprintf("Invalid snapshot type \"%s\" specified. Please "
2839 "specify \"rollback\" or \"latest\"",
2840 snapshot_type));
2841 }
2842
2843 const ArgsManager &args{EnsureAnyArgsman(request.context)};
2844 const fs::path path = fsbridge::AbsPathJoin(
2845 args.GetDataDirNet(), fs::u8path(request.params[0].get_str()));
2846 // Write to a temporary path and then move into `path` on completion
2847 // to avoid confusion due to an interruption.
2848 const fs::path temppath = fsbridge::AbsPathJoin(
2849 args.GetDataDirNet(),
2850 fs::u8path(request.params[0].get_str() + ".incomplete"));
2851
2852 if (fs::exists(path)) {
2854 path.u8string() +
2855 " already exists. If you are sure this "
2856 "is what you want, "
2857 "move it out of the way first");
2858 }
2859
2860 FILE *file{fsbridge::fopen(temppath, "wb")};
2861 AutoFile afile{file};
2862
2863 CConnman &connman = EnsureConnman(node);
2864 const CBlockIndex *invalidate_index{nullptr};
2865 std::optional<NetworkDisable> disable_network;
2866 std::optional<TemporaryRollback> temporary_rollback;
2867
2868 // If the user wants to dump the txoutset of the current tip, we
2869 // don't have to roll back at all
2870 if (target_index != tip) {
2871 // If the node is running in pruned mode we ensure all necessary
2872 // block data is available before starting to roll back.
2873 if (node.chainman->m_blockman.IsPruneMode()) {
2874 LOCK(node.chainman->GetMutex());
2875 const CBlockIndex *current_tip{
2876 node.chainman->ActiveChain().Tip()};
2877 const CBlockIndex *first_block{
2878 node.chainman->m_blockman.GetFirstBlock(
2879 *current_tip,
2880 /*status_test=*/[](const BlockStatus &status) {
2881 return status.hasData() && status.hasUndo();
2882 })};
2883 if (first_block->nHeight > target_index->nHeight) {
2884 throw JSONRPCError(
2886 "Could not roll back to requested height since "
2887 "necessary block data is already pruned.");
2888 }
2889 }
2890
2891 // Suspend network activity for the duration of the process when
2892 // we are rolling back the chain to get a utxo set from a past
2893 // height. We do this so we don't punish peers that send us that
2894 // send us data that seems wrong in this temporary state. For
2895 // example a normal new block would be classified as a block
2896 // connecting an invalid block.
2897 // Skip if the network is already disabled because this
2898 // automatically re-enables the network activity at the end of
2899 // the process which may not be what the user wants.
2900 if (connman.GetNetworkActive()) {
2901 disable_network.emplace(connman);
2902 }
2903
2904 invalidate_index = WITH_LOCK(
2905 ::cs_main,
2906 return node.chainman->ActiveChain().Next(target_index));
2907 temporary_rollback.emplace(*node.chainman, node.avalanche.get(),
2908 *invalidate_index);
2909 }
2910
2911 Chainstate *chainstate;
2912 std::unique_ptr<CCoinsViewCursor> cursor;
2913 CCoinsStats stats;
2914 {
2915 // Lock the chainstate before calling PrepareUtxoSnapshot, to
2916 // be able to get a UTXO database cursor while the chain is
2917 // pointing at the target block. After that, release the lock
2918 // while calling WriteUTXOSnapshot. The cursor will remain
2919 // valid and be used by WriteUTXOSnapshot to write a consistent
2920 // snapshot even if the chainstate changes.
2921 LOCK(node.chainman->GetMutex());
2922 chainstate = &node.chainman->ActiveChainstate();
2923
2924 // In case there is any issue with a block being read from disk
2925 // we need to stop here, otherwise the dump could still be
2926 // created for the wrong height. The new tip could also not be
2927 // the target block if we have a stale sister block of
2928 // invalidate_index. This block (or a descendant) would be
2929 // activated as the new tip and we would not get to
2930 // new_tip_index.
2931 if (target_index != chainstate->m_chain.Tip()) {
2933 "Failed to roll back to requested height, "
2934 "reverting to tip.\n");
2935 throw JSONRPCError(
2937 "Could not roll back to requested height.");
2938 } else {
2939 std::tie(cursor, stats, tip) = PrepareUTXOSnapshot(
2940 *chainstate, node.rpc_interruption_point);
2941 }
2942 }
2943
2944 UniValue result =
2945 WriteUTXOSnapshot(*chainstate, cursor.get(), &stats, tip, afile,
2946 path, temppath, node.rpc_interruption_point);
2947 fs::rename(temppath, path);
2948
2949 return result;
2950 },
2951 };
2952}
2953
2954std::tuple<std::unique_ptr<CCoinsViewCursor>, CCoinsStats, const CBlockIndex *>
2956 const std::function<void()> &interruption_point) {
2957 std::unique_ptr<CCoinsViewCursor> pcursor;
2958 std::optional<CCoinsStats> maybe_stats;
2959 const CBlockIndex *tip;
2960
2961 {
2962 // We need to lock cs_main to ensure that the coinsdb isn't
2963 // written to between (i) flushing coins cache to disk
2964 // (coinsdb), (ii) getting stats based upon the coinsdb, and
2965 // (iii) constructing a cursor to the coinsdb for use in
2966 // WriteUTXOSnapshot.
2967 //
2968 // Cursors returned by leveldb iterate over snapshots, so the
2969 // contents of the pcursor will not be affected by simultaneous
2970 // writes during use below this block.
2971 //
2972 // See discussion here:
2973 // https://github.com/bitcoin/bitcoin/pull/15606#discussion_r274479369
2974 //
2976
2977 chainstate.ForceFlushStateToDisk();
2978
2979 maybe_stats = GetUTXOStats(&chainstate.CoinsDB(), chainstate.m_blockman,
2980 CoinStatsHashType::HASH_SERIALIZED,
2981 interruption_point);
2982 if (!maybe_stats) {
2983 throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set");
2984 }
2985
2986 pcursor =
2987 std::unique_ptr<CCoinsViewCursor>(chainstate.CoinsDB().Cursor());
2988 tip = CHECK_NONFATAL(
2989 chainstate.m_blockman.LookupBlockIndex(maybe_stats->hashBlock));
2990 }
2991
2992 return {std::move(pcursor), *CHECK_NONFATAL(maybe_stats), tip};
2993}
2994
2996 CCoinsStats *maybe_stats, const CBlockIndex *tip,
2997 AutoFile &afile, const fs::path &path,
2998 const fs::path &temppath,
2999 const std::function<void()> &interruption_point) {
3001 strprintf("writing UTXO snapshot at height %s (%s) to file %s (via %s)",
3002 tip->nHeight, tip->GetBlockHash().ToString(),
3003 fs::PathToString(path), fs::PathToString(temppath)));
3004
3005 SnapshotMetadata metadata{chainstate.m_chainman.GetParams().DiskMagic(),
3006 tip->GetBlockHash(), maybe_stats->coins_count};
3007
3008 afile << metadata;
3009
3010 COutPoint key;
3011 TxId last_txid;
3012 Coin coin;
3013 unsigned int iter{0};
3014 size_t written_coins_count{0};
3015 std::vector<std::pair<uint32_t, Coin>> coins;
3016
3017 // To reduce space the serialization format of the snapshot avoids
3018 // duplication of tx hashes. The code takes advantage of the guarantee by
3019 // leveldb that keys are lexicographically sorted.
3020 // In the coins vector we collect all coins that belong to a certain tx hash
3021 // (key.hash) and when we have them all (key.hash != last_hash) we write
3022 // them to file using the below lambda function.
3023 // See also https://github.com/bitcoin/bitcoin/issues/25675
3024 auto write_coins_to_file =
3025 [&](AutoFile &afile, const TxId &last_txid,
3026 const std::vector<std::pair<uint32_t, Coin>> &coins,
3027 size_t &written_coins_count) {
3028 afile << last_txid;
3029 WriteCompactSize(afile, coins.size());
3030 for (const auto &[n, coin_] : coins) {
3031 WriteCompactSize(afile, n);
3032 afile << coin_;
3033 ++written_coins_count;
3034 }
3035 };
3036
3037 pcursor->GetKey(key);
3038 last_txid = key.GetTxId();
3039 while (pcursor->Valid()) {
3040 if (iter % 5000 == 0) {
3041 interruption_point();
3042 }
3043 ++iter;
3044 if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
3045 if (key.GetTxId() != last_txid) {
3046 write_coins_to_file(afile, last_txid, coins,
3047 written_coins_count);
3048 last_txid = key.GetTxId();
3049 coins.clear();
3050 }
3051 coins.emplace_back(key.GetN(), coin);
3052 }
3053 pcursor->Next();
3054 }
3055
3056 if (!coins.empty()) {
3057 write_coins_to_file(afile, last_txid, coins, written_coins_count);
3058 }
3059
3060 CHECK_NONFATAL(written_coins_count == maybe_stats->coins_count);
3061
3062 afile.fclose();
3063
3064 UniValue result(UniValue::VOBJ);
3065 result.pushKV("coins_written", written_coins_count);
3066 result.pushKV("base_hash", tip->GetBlockHash().ToString());
3067 result.pushKV("base_height", tip->nHeight);
3068 result.pushKV("path", path.u8string());
3069 result.pushKV("txoutset_hash", maybe_stats->hashSerialized.ToString());
3070 result.pushKV("nchaintx", tip->m_chain_tx_count);
3071 return result;
3072}
3073
3075 AutoFile &afile, const fs::path &path,
3076 const fs::path &tmppath) {
3077 auto [cursor, stats, tip]{WITH_LOCK(
3078 ::cs_main,
3079 return PrepareUTXOSnapshot(chainstate, node.rpc_interruption_point))};
3080 return WriteUTXOSnapshot(chainstate, cursor.get(), &stats, tip, afile, path,
3081 tmppath, node.rpc_interruption_point);
3082}
3083
3085 return RPCHelpMan{
3086 "loadtxoutset",
3087 "Load the serialized UTXO set from a file.\n"
3088 "Once this snapshot is loaded, its contents will be deserialized into "
3089 "a second chainstate data structure, which is then used to sync to the "
3090 "network's tip. "
3091 "Meanwhile, the original chainstate will complete the initial block "
3092 "download process in the background, eventually validating up to the "
3093 "block that the snapshot is based upon.\n\n"
3094 "The result is a usable bitcoind instance that is current with the "
3095 "network tip in a matter of minutes rather than hours. UTXO snapshot "
3096 "are typically obtained from third-party sources (HTTP, torrent, etc.) "
3097 "which is reasonable since their contents are always checked by "
3098 "hash.\n\n"
3099 "This RPC is incompatible with the -chronik init option, and a node "
3100 "with multiple chainstates may not be restarted with -chronik. After "
3101 "the background validation is finished and the chainstates are merged, "
3102 "the node can be restarted again with Chronik.\n\n"
3103 "You can find more information on this process in the `assumeutxo` "
3104 "design document (https://www.bitcoinabc.org/doc/assumeutxo.html).",
3105 {
3107 "path to the snapshot file. If relative, will be prefixed by "
3108 "datadir."},
3109 },
3111 "",
3112 "",
3113 {
3114 {RPCResult::Type::NUM, "coins_loaded",
3115 "the number of coins loaded from the snapshot"},
3116 {RPCResult::Type::STR_HEX, "tip_hash",
3117 "the hash of the base of the snapshot"},
3118 {RPCResult::Type::NUM, "base_height",
3119 "the height of the base of the snapshot"},
3120 {RPCResult::Type::STR, "path",
3121 "the absolute path that the snapshot was loaded from"},
3122 }},
3124 HelpExampleCli("loadtxoutset -rpcclienttimeout=0", "utxo.dat")},
3125 [&](const RPCHelpMan &self, const Config &config,
3126 const JSONRPCRequest &request) -> UniValue {
3127 NodeContext &node = EnsureAnyNodeContext(request.context);
3130 const fs::path path{AbsPathForConfigVal(
3131 args, fs::u8path(self.Arg<std::string>("path")))};
3132
3133 if (args.GetBoolArg("-chronik", false)) {
3134 throw JSONRPCError(
3136 "loadtxoutset is not compatible with Chronik.");
3137 }
3138
3139 FILE *file{fsbridge::fopen(path, "rb")};
3140 AutoFile afile{file};
3141 if (afile.IsNull()) {
3143 "Couldn't open file " + path.u8string() +
3144 " for reading.");
3145 }
3146
3147 SnapshotMetadata metadata{chainman.GetParams().DiskMagic()};
3148 try {
3149 afile >> metadata;
3150 } catch (const std::ios_base::failure &e) {
3151 throw JSONRPCError(
3153 strprintf("Unable to parse metadata: %s", e.what()));
3154 }
3155
3156 auto activation_result{
3157 chainman.ActivateSnapshot(afile, metadata, false)};
3158 if (!activation_result) {
3159 throw JSONRPCError(
3161 strprintf("Unable to load UTXO snapshot: %s. (%s)",
3162 util::ErrorString(activation_result).original,
3163 path.u8string()));
3164 }
3165
3166 CBlockIndex &snapshot_index{*CHECK_NONFATAL(*activation_result)};
3167
3168 // Because we can't provide historical blocks during tip or
3169 // background sync. Update local services to reflect we are a
3170 // limited peer until we are fully sync.
3171 node.connman->RemoveLocalServices(NODE_NETWORK);
3172 // Setting the limited state is usually redundant because the node
3173 // can always provide the last 288 blocks, but it doesn't hurt to
3174 // set it.
3175 node.connman->AddLocalServices(NODE_NETWORK_LIMITED);
3176
3177 UniValue result(UniValue::VOBJ);
3178 result.pushKV("coins_loaded", metadata.m_coins_count);
3179 result.pushKV("tip_hash", snapshot_index.GetBlockHash().ToString());
3180 result.pushKV("base_height", snapshot_index.nHeight);
3181 result.pushKV("path", fs::PathToString(path));
3182 return result;
3183 },
3184 };
3185}
3186
3187const std::vector<RPCResult> RPCHelpForChainstate{
3188 {RPCResult::Type::NUM, "blocks", "number of blocks in this chainstate"},
3189 {RPCResult::Type::STR_HEX, "bestblockhash", "blockhash of the tip"},
3190 {RPCResult::Type::NUM, "difficulty", "difficulty of the tip"},
3191 {RPCResult::Type::NUM, "verificationprogress",
3192 "progress towards the network tip"},
3193 {RPCResult::Type::STR_HEX, "snapshot_blockhash", /*optional=*/true,
3194 "the base block of the snapshot this chainstate is based on, if any"},
3195 {RPCResult::Type::NUM, "coins_db_cache_bytes", "size of the coinsdb cache"},
3196 {RPCResult::Type::NUM, "coins_tip_cache_bytes",
3197 "size of the coinstip cache"},
3198 {RPCResult::Type::BOOL, "validated",
3199 "whether the chainstate is fully validated. True if all blocks in the "
3200 "chainstate were validated, false if the chain is based on a snapshot and "
3201 "the snapshot has not yet been validated."},
3202
3203};
3204
3206 return RPCHelpMan{
3207 "getchainstates",
3208 "\nReturn information about chainstates.\n",
3209 {},
3211 "",
3212 "",
3213 {
3214 {RPCResult::Type::NUM, "headers",
3215 "the number of headers seen so far"},
3217 "chainstates",
3218 "list of the chainstates ordered by work, with the "
3219 "most-work (active) chainstate last",
3220 {
3222 }},
3223 }},
3224 RPCExamples{HelpExampleCli("getchainstates", "") +
3225 HelpExampleRpc("getchainstates", "")},
3226 [&](const RPCHelpMan &self, const Config &config,
3227 const JSONRPCRequest &request) -> UniValue {
3228 LOCK(cs_main);
3230
3231 ChainstateManager &chainman = EnsureAnyChainman(request.context);
3232
3233 auto make_chain_data =
3234 [&](const Chainstate &chainstate,
3235 bool validated) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
3238 if (!chainstate.m_chain.Tip()) {
3239 return data;
3240 }
3241 const CChain &chain = chainstate.m_chain;
3242 const CBlockIndex *tip = chain.Tip();
3243
3244 data.pushKV("blocks", chain.Height());
3245 data.pushKV("bestblockhash", tip->GetBlockHash().GetHex());
3246 data.pushKV("difficulty", GetDifficulty(*tip));
3247 data.pushKV(
3248 "verificationprogress",
3249 GuessVerificationProgress(Params().TxData(), tip));
3250 data.pushKV("coins_db_cache_bytes",
3251 chainstate.m_coinsdb_cache_size_bytes);
3252 data.pushKV("coins_tip_cache_bytes",
3253 chainstate.m_coinstip_cache_size_bytes);
3254 if (chainstate.m_from_snapshot_blockhash) {
3255 data.pushKV(
3256 "snapshot_blockhash",
3257 chainstate.m_from_snapshot_blockhash->ToString());
3258 }
3259 data.pushKV("validated", validated);
3260 return data;
3261 };
3262
3263 obj.pushKV("headers", chainman.m_best_header
3264 ? chainman.m_best_header->nHeight
3265 : -1);
3266
3267 const auto &chainstates = chainman.GetAll();
3268 UniValue obj_chainstates{UniValue::VARR};
3269 for (Chainstate *cs : chainstates) {
3270 obj_chainstates.push_back(
3271 make_chain_data(*cs, !cs->m_from_snapshot_blockhash ||
3272 chainstates.size() == 1));
3273 }
3274 obj.pushKV("chainstates", std::move(obj_chainstates));
3275 return obj;
3276 }};
3277}
3278
3280 // clang-format off
3281 static const CRPCCommand commands[] = {
3282 // category actor (function)
3283 // ------------------ ----------------------
3284 { "blockchain", getbestblockhash, },
3285 { "blockchain", getblock, },
3286 { "blockchain", getblockfrompeer, },
3287 { "blockchain", getblockchaininfo, },
3288 { "blockchain", getblockcount, },
3289 { "blockchain", getblockhash, },
3290 { "blockchain", getblockheader, },
3291 { "blockchain", getblockstats, },
3292 { "blockchain", getchaintips, },
3293 { "blockchain", getchaintxstats, },
3294 { "blockchain", getdifficulty, },
3295 { "blockchain", gettxout, },
3296 { "blockchain", gettxoutsetinfo, },
3297 { "blockchain", pruneblockchain, },
3298 { "blockchain", verifychain, },
3299 { "blockchain", preciousblock, },
3300 { "blockchain", scantxoutset, },
3301 { "blockchain", getblockfilter, },
3302 { "blockchain", dumptxoutset, },
3303 { "blockchain", loadtxoutset, },
3304 { "blockchain", getchainstates, },
3305
3306 /* Not shown in help */
3307 { "hidden", invalidateblock, },
3308 { "hidden", parkblock, },
3309 { "hidden", reconsiderblock, },
3310 { "hidden", syncwithvalidationinterfacequeue, },
3311 { "hidden", unparkblock, },
3312 { "hidden", waitfornewblock, },
3313 { "hidden", waitforblock, },
3314 { "hidden", waitforblockheight, },
3315 };
3316 // clang-format on
3317 for (const auto &c : commands) {
3318 t.appendCommand(c.name, &c);
3319 }
3320}
bool MoneyRange(const Amount nValue)
Definition amount.h:177
static constexpr Amount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition amount.h:176
fs::path AbsPathForConfigVal(const ArgsManager &args, const fs::path &path, bool net_specific=true)
Most paths passed as configuration arguments are treated as relative to the datadir if they are not a...
RPCHelpMan gettxout()
static RPCHelpMan getblock()
static RPCHelpMan getdifficulty()
static std::atomic< bool > g_scan_in_progress
static bool SetHasKeys(const std::set< T > &set)
static RPCHelpMan reconsiderblock()
static void InvalidateBlock(ChainstateManager &chainman, avalanche::Processor *const avalanche, const BlockHash &block_hash)
static T CalculateTruncatedMedian(std::vector< T > &scores)
static RPCHelpMan invalidateblock()
static int ComputeNextBlockAndDepth(const CBlockIndex &tip, const CBlockIndex &blockindex, const CBlockIndex *&next)
static RPCHelpMan syncwithvalidationinterfacequeue()
static CBlockUndo GetUndoChecked(BlockManager &blockman, const CBlockIndex &blockindex)
static RPCHelpMan getchaintips()
static RPCHelpMan loadtxoutset()
static RPCHelpMan gettxoutsetinfo()
static RPCHelpMan getchainstates()
std::tuple< std::unique_ptr< CCoinsViewCursor >, CCoinsStats, const CBlockIndex * > PrepareUTXOSnapshot(Chainstate &chainstate, const std::function< void()> &interruption_point)
static RPCHelpMan getblockstats()
static CoinStatsHashType ParseHashType(const std::string &hash_type_input)
static RPCHelpMan preciousblock()
static constexpr size_t PER_UTXO_OVERHEAD
double GetDifficulty(const CBlockIndex &blockindex)
Calculate the difficulty for a given block index.
static RPCHelpMan scantxoutset()
static std::condition_variable cond_blockchange
static std::atomic< int > g_scan_progress
RAII object to prevent concurrency issue when scanning the txout set.
static CBlock GetBlockChecked(BlockManager &blockman, const CBlockIndex &blockindex)
std::optional< int > GetPruneHeight(const BlockManager &blockman, const CChain &chain)
static void ReconsiderBlock(ChainstateManager &chainman, avalanche::Processor *const avalanche, const BlockHash &block_hash)
static RPCHelpMan getblockfilter()
static RPCHelpMan getbestblockhash()
RPCHelpMan getblockchaininfo()
static RPCHelpMan getchaintxstats()
UniValue CreateUTXOSnapshot(node::NodeContext &node, Chainstate &chainstate, AutoFile &afile, const fs::path &path, const fs::path &tmppath)
Test-only helper to create UTXO snapshots given a chainstate and a file handle.
static RPCHelpMan waitforblock()
std::tuple< std::unique_ptr< CCoinsViewCursor >, CCoinsStats, const CBlockIndex * > PrepareUTXOSnapshot(Chainstate &chainstate, const std::function< void()> &interruption_point={}) EXCLUSIVE_LOCKS_REQUIRED(UniValue WriteUTXOSnapshot(Chainstate &chainstate, CCoinsViewCursor *pcursor, CCoinsStats *maybe_stats, const CBlockIndex *tip, AutoFile &afile, const fs::path &path, const fs::path &temppath, const std::function< void()> &interruption_point={})
static RPCHelpMan getblockfrompeer()
static RPCHelpMan getblockhash()
void RegisterBlockchainRPCCommands(CRPCTable &t)
static RPCHelpMan verifychain()
static std::atomic< bool > g_should_abort_scan
const std::vector< RPCResult > RPCHelpForChainstate
UniValue blockheaderToJSON(const CBlockIndex &tip, const CBlockIndex &blockindex)
Block header to JSON.
RPCHelpMan unparkblock()
static RPCHelpMan waitforblockheight()
static const CBlockIndex * ParseHashOrHeight(const UniValue &param, ChainstateManager &chainman)
UniValue blockToJSON(BlockManager &blockman, const CBlock &block, const CBlockIndex &tip, const CBlockIndex &blockindex, TxVerbosity verbosity)
Block description to JSON.
static RPCHelpMan pruneblockchain()
static RPCHelpMan getblockheader()
RPCHelpMan parkblock()
static GlobalMutex cs_blockchange
static RPCHelpMan dumptxoutset()
Serialize the UTXO set to a file for loading elsewhere.
static RPCHelpMan getblockcount()
static RPCHelpMan waitfornewblock()
void RPCNotifyBlockChange(const CBlockIndex *pindex)
Callback for when block tip changed.
bool BlockFilterTypeByName(const std::string &name, BlockFilterType &filter_type)
Find a filter type by its human-readable name.
BlockFilterType
Definition blockfilter.h:88
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
@ SCRIPTS
Scripts & signatures ok.
@ TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
Definition chain.cpp:112
static constexpr int64_t TIMESTAMP_WINDOW
Timestamp window used as a grace period by code that compares external timestamps (such as timestamps...
Definition chain.h:36
const CChainParams & Params()
Return the currently selected parameters.
#define CHECK_NONFATAL(condition)
Identity function.
Definition check.h:83
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition args.cpp:524
Non-refcounted RAII wrapper for FILE*.
Definition streams.h:433
bool IsNull() const
Return true if the wrapped FILE* is nullptr, false otherwise.
Definition streams.h:475
int fclose()
Definition streams.h:448
Complete block filter struct as defined in BIP 157.
const std::vector< uint8_t > & GetEncodedFilter() const
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
bool LookupFilter(const CBlockIndex *block_index, BlockFilter &filter_out) const
Get a single filter by block.
bool LookupFilterHeader(const CBlockIndex *block_index, uint256 &header_out) EXCLUSIVE_LOCKS_REQUIRED(!m_cs_headers_cache)
Get a single filter header by block.
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:190
uint256 hashMerkleRoot
Definition blockindex.h:74
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition blockindex.h:32
uint64_t m_chain_tx_count
(memory only) Number of transactions in the chain up to and including this block.
Definition blockindex.h:67
CBlockHeader GetBlockHeader() const
Definition blockindex.h:116
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition blockindex.h:51
uint32_t nTime
Definition blockindex.h:75
uint32_t nNonce
Definition blockindex.h:77
int64_t GetBlockTime() const
Definition blockindex.h:159
int64_t GetMedianTimePast() const
Definition blockindex.h:171
uint32_t nBits
Definition blockindex.h:76
unsigned int nTx
Number of transactions in this block.
Definition blockindex.h:55
int32_t nVersion
block header
Definition blockindex.h:73
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
BlockHash GetBlockHash() const
Definition blockindex.h:129
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition blockindex.h:38
Undo information for a CBlock.
Definition undo.h:72
std::vector< CTxUndo > vtxundo
Definition undo.h:75
An in-memory indexed chain of blocks.
Definition chain.h:138
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition chain.h:154
CBlockIndex * FindEarliestAtLeast(int64_t nTime, int height) const
Find the earliest block with timestamp equal or greater than the given time and height equal or great...
Definition chain.cpp:62
int Height() const
Return the maximal height in the chain.
Definition chain.h:190
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
Definition chain.cpp:49
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition chain.h:170
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition chainparams.h:86
std::string GetChainTypeString() const
Return the chain type string.
const CBlock & GenesisBlock() const
const CMessageHeader::MessageMagic & DiskMagic() const
Definition chainparams.h:99
const ChainTxData & TxData() const
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition coins.h:357
BlockHash GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition coins.cpp:217
std::optional< Coin > GetCoin(const COutPoint &outpoint) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition coins.cpp:89
Cursor for iterating over CoinsView state.
Definition coins.h:217
virtual void Next()=0
virtual bool Valid() const =0
virtual bool GetKey(COutPoint &key) const =0
virtual bool GetValue(Coin &coin) const =0
CCoinsViewCursor * Cursor() const override
Get a cursor to iterate over the whole state.
Definition txdb.cpp:228
Abstract view on the open txout dataset.
Definition coins.h:303
virtual BlockHash GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
Definition coins.cpp:16
CCoinsView that brings transactions from a mempool into view.
Definition txmempool.h:650
std::optional< Coin > GetCoin(const COutPoint &outpoint) const override
GetCoin, returning whether it exists and is not spent.
bool GetNetworkActive() const
Definition net.h:930
void SetNetworkActive(bool active)
Definition net.cpp:2478
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition transaction.h:20
const TxId & GetTxId() const
Definition transaction.h:35
uint32_t GetN() const
Definition transaction.h:36
RPC command dispatcher.
Definition server.h:194
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition server.cpp:330
Serialized script, used inside transaction inputs and outputs.
Definition script.h:434
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition txmempool.h:222
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition txmempool.h:316
bool isSpent(const COutPoint &outpoint) const
An output of a transaction.
CScript scriptPubKey
Amount nValue
Restore the UTXO in a Coin at a given COutPoint.
Definition undo.h:61
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition validation.h:641
VerifyDBResult VerifyDB(Chainstate &chainstate, CCoinsView &coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition validation.h:725
bool IsBlockAvalancheFinalized(const CBlockIndex *pindex) const EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex)
Checks if a block is finalized by avalanche voting.
const std::optional< BlockHash > m_from_snapshot_blockhash
The blockhash which is the base of the snapshot this chainstate was created from.
Definition validation.h:832
bool ActivateBestChain(BlockValidationState &state, std::shared_ptr< const CBlock > pblock=nullptr, avalanche::Processor *const avalanche=nullptr) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex
Find the best known block, and make it the tip of the block chain.
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition validation.h:824
size_t m_coinstip_cache_size_bytes
The cache size of the in-memory coins view.
Definition validation.h:884
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition validation.h:851
size_t m_coinsdb_cache_size_bytes
The cache size of the on-disk coins view.
Definition validation.h:881
void ForceFlushStateToDisk()
Unconditionally flush all changes to disk.
void UnparkBlockAndChildren(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove parked status from a block and its descendants.
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
Definition validation.h:858
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
Definition validation.h:787
bool AvalancheFinalizeBlock(CBlockIndex *pindex, avalanche::Processor &avalanche) EXCLUSIVE_LOCKS_REQUIRED(voi ClearAvalancheFinalizedBlock)() EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex)
Mark a block as finalized by avalanche.
Definition validation.h:987
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
Definition validation.h:782
bool ParkBlock(BlockValidationState &state, CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex
Park a block.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
SnapshotCompletionResult MaybeCompleteSnapshotValidation() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(Chainstate ActiveChainstate)() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
kernel::Notifications & GetNotifications() const
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network)
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
const CChainParams & GetParams() const
const Consensus::Params & GetConsensus() const
const CBlockIndex * GetAvalancheFinalizedTip() const
util::Result< CBlockIndex * > ActivateSnapshot(AutoFile &coins_file, const node::SnapshotMetadata &metadata, bool in_memory)
Construct and activate a Chainstate on the basis of UTXO snapshot data.
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
A UTXO entry.
Definition coins.h:31
uint32_t GetHeight() const
Definition coins.h:48
bool IsCoinBase() const
Definition coins.h:49
CTxOut & GetTxOut()
Definition coins.h:52
CoinsViewScanReserver()=default
Double ended buffer combining vector and stream-like interfaces.
Definition streams.h:118
Different type to mark Mutex at global scope.
Definition sync.h:144
RAII class that disables the network in its constructor and enables it in its destructor.
NetworkDisable(CConnman &connman)
CConnman & m_connman
virtual std::optional< std::string > FetchBlock(const Config &config, NodeId peer_id, const CBlockIndex &block_index)=0
Attempt to manually fetch block from a given peer.
auto Arg(size_t i) const
Helper to get a required or default-valued request argument.
Definition util.h:429
RAII class that temporarily rolls back the local chain in it's constructor and rolls it forward again...
avalanche::Processor *const m_avalanche
const CBlockIndex & m_invalidate_index
TemporaryRollback(ChainstateManager &chainman, avalanche::Processor *const avalanche, const CBlockIndex &index)
ChainstateManager & m_chainman
void push_back(UniValue val)
Definition univalue.cpp:96
const std::string & get_str() const
bool isNull() const
Definition univalue.h:104
size_t size() const
Definition univalue.h:92
Int getInt() const
Definition univalue.h:157
const UniValue & get_array() const
bool isNum() const
Definition univalue.h:109
void pushKV(std::string key, UniValue val)
Definition univalue.cpp:115
bool IsValid() const
Definition validation.h:119
std::string GetRejectReason() const
Definition validation.h:123
std::string ToString() const
Definition validation.h:125
constexpr uint8_t * begin()
Definition uint256.h:122
std::string ToString() const
Definition uint256.h:117
std::string GetHex() const
Definition uint256.cpp:10
std::string GetHex() const
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition fs.h:30
std::string u8string() const
Definition fs.h:72
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
static constexpr auto PRUNE_TARGET_MANUAL
bool ReadBlockUndo(CBlockUndo &blockundo, const CBlockIndex &index) const
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
uint64_t GetPruneTarget() const
Attempt to stay below this number of bytes of block files.
uint64_t CalculateCurrentUsage()
Calculate the amount of disk space the block & undo files currently use.
bool IsPruneMode() const
Whether running in -prune mode.
bool ReadBlock(CBlock &block, const FlatFilePos &pos) const
Functions for disk access for blocks.
Metadata describing a serialized version of a UTXO set from which an assumeutxo Chainstate can be con...
256-bit opaque blob.
Definition uint256.h:199
std::unique_ptr< CoinStatsIndex > g_coin_stats_index
The global UTXO set hash object.
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
TxVerbosity
Verbose level for block's transaction.
Definition core_io.h:29
@ SHOW_DETAILS_AND_PREVOUT
The same as previous option with information about prevouts if available.
@ SHOW_TXID
Only TXID for each block's transaction.
@ SHOW_DETAILS
Include TXID, inputs, outputs, and other common block's transaction information.
void TxToUniv(const CTransaction &tx, const BlockHash &hashBlock, UniValue &entry, bool include_hex=true, const CTxUndo *txundo=nullptr, TxVerbosity verbosity=TxVerbosity::SHOW_DETAILS, std::function< bool(const CTxOut &)> is_change_func={})
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition cs_main.cpp:7
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible.
int64_t NodeId
Definition eviction.h:16
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition hex_base.cpp:30
#define LogPrintLevel(category, level,...)
Definition logging.h:437
#define LogDebug(category,...)
Definition logging.h:446
unsigned int nHeight
static void pool cs
@ RPC
Definition logging.h:76
static path u8path(const std::string &utf8_str)
Definition fs.h:90
static bool exists(const path &p)
Definition fs.h:107
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition fs.h:147
FILE * fopen(const fs::path &p, const char *mode)
Definition fs.cpp:30
fs::path AbsPathJoin(const fs::path &base, const fs::path &path)
Helper function for joining two paths.
Definition fs.cpp:39
CoinStatsHashType
Definition coinstats.h:24
std::optional< kernel::CCoinsStats > GetUTXOStats(CCoinsView *view, BlockManager &blockman, kernel::CoinStatsHashType hash_type, const std::function< void()> &interruption_point, const CBlockIndex *pindex, bool index_requested)
Calculate statistics about the unspent transaction output set.
Definition coinstats.cpp:17
bilingual_str ErrorString(const Result< T > &result)
Definition result.h:90
std::string MakeUnorderedList(const std::vector< std::string > &items)
Create an unordered multi-line list of items.
Definition string.h:136
std::shared_ptr< const CTransaction > CTransactionRef
@ NODE_NETWORK_LIMITED
Definition protocol.h:364
@ NODE_NETWORK
Definition protocol.h:342
UniValue JSONRPCError(int code, const std::string &message)
Definition request.cpp:58
@ RPC_MISC_ERROR
General application defined errors std::exception thrown in command handling.
Definition protocol.h:38
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
Definition protocol.h:46
@ RPC_INTERNAL_ERROR
Definition protocol.h:33
@ RPC_DATABASE_ERROR
Database error.
Definition protocol.h:48
@ RPC_DESERIALIZATION_ERROR
Error parsing or validating structure in raw format.
Definition protocol.h:50
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
Definition protocol.h:42
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition util.cpp:182
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition util.cpp:199
std::vector< CScript > EvalDescriptorStringOrObject(const UniValue &scanobject, FlatSigningProvider &provider)
Evaluate a descriptor given as a string, or as a {"desc":...,"range":...} object, with default range ...
Definition util.cpp:1401
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
Definition util.cpp:36
int ParseVerbosity(const UniValue &arg, int default_verbosity, bool allow_bool)
Parses verbosity from provided UniValue.
Definition util.cpp:126
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded values (throws error if not hex).
Definition util.cpp:87
size_t GetSerializeSize(const T &t)
Definition serialize.h:1264
void WriteCompactSize(SizeComputer &os, uint64_t nSize)
Definition serialize.h:1260
bool IsRPCRunning()
Query whether RPC is running.
Definition server.cpp:381
ChainstateManager & EnsureAnyChainman(const std::any &context)
NodeContext & EnsureAnyNodeContext(const std::any &context)
CTxMemPool & EnsureMemPool(const NodeContext &node)
PeerManager & EnsurePeerman(const NodeContext &node)
ChainstateManager & EnsureChainman(const NodeContext &node)
ArgsManager & EnsureArgsman(const NodeContext &node)
CConnman & EnsureConnman(const NodeContext &node)
ArgsManager & EnsureAnyArgsman(const std::any &context)
static constexpr Amount zero() noexcept
Definition amount.h:36
A BlockHash is a unqiue identifier for a block.
Definition blockhash.h:13
bool hasUndo() const
Definition blockstatus.h:65
bool hasData() const
Definition blockstatus.h:59
BlockHash hash
Comparison function for sorting the getchaintips heads.
bool operator()(const CBlockIndex *a, const CBlockIndex *b) const
static std::string getTicker()
Definition amount.h:163
@ RANGE
Special type that is a NUM or [NUM,NUM].
@ STR_HEX
Special type that is a STR with only hex chars.
@ OBJ_NAMED_PARAMS
Special type that behaves almost exactly like OBJ, defining an options object with a list of pre-defi...
std::string DefaultHint
Hint for default value.
Definition util.h:225
@ OMITTED
Optional argument for which the default value is omitted from help text for one of two reasons:
@ NO
Required arg.
UniValue Default
Default constant value.
Definition util.h:227
std::string oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
Definition util.h:162
bool skip_type_check
Definition util.h:159
@ ELISION
Special type to denote elision (...)
@ NUM_TIME
Special numeric to denote unix epoch time.
@ STR_HEX
Special string with only hex chars.
@ STR_AMOUNT
Special string to represent a floating point amount.
A TxId is the identifier of a transaction.
Definition txid.h:14
std::string original
Definition translation.h:18
Amount total_unspendables_scripts
Total cumulative amount of outputs sent to unspendable scripts (OP_RETURN for example) up to and incl...
Definition coinstats.h:69
Amount total_coinbase_amount
Total cumulative amount of coinbase outputs up to and including this block.
Definition coinstats.h:62
Amount total_unspendables_genesis_block
The unspendable coinbase amount from the genesis block.
Definition coinstats.h:64
uint64_t coins_count
The number of coins contained.
Definition coinstats.h:42
uint64_t nTransactions
Definition coinstats.h:33
uint64_t nTransactionOutputs
Definition coinstats.h:34
bool index_used
Signals if the coinstatsindex was used to retrieve the statistics.
Definition coinstats.h:45
Amount total_unspendables_bip30
The two unspendable coinbase outputs total amount caused by BIP30.
Definition coinstats.h:66
Amount total_prevout_spent_amount
Total cumulative amount of prevouts spent up to and including this block.
Definition coinstats.h:56
BlockHash hashBlock
Definition coinstats.h:32
Amount total_unspendables_unclaimed_rewards
Total cumulative amount of coins lost due to unclaimed miner rewards up to and including this block.
Definition coinstats.h:72
uint256 hashSerialized
Definition coinstats.h:36
std::optional< Amount > total_amount
The total amount, or nullopt if an overflow occurred calculating it.
Definition coinstats.h:39
Amount total_new_outputs_ex_coinbase_amount
Total cumulative amount of outputs created up to and including this block.
Definition coinstats.h:59
Amount total_unspendable_amount
Total cumulative amount of unspendable coins up to and including this block.
Definition coinstats.h:54
NodeContext struct containing references to chain state and connection state.
Definition context.h:50
#define WAIT_LOCK(cs, name)
Definition sync.h:304
#define AssertLockNotHeld(cs)
Definition sync.h:163
#define LOCK(cs)
Definition sync.h:295
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition sync.h:343
#define AssertLockHeld(cs)
Definition sync.h:146
static int count
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#define GUARDED_BY(x)
#define LOG_TIME_SECONDS(end_msg)
Definition timer.h:103
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
bilingual_str _(const char *psz)
Translation function.
Definition translation.h:68
static const uint32_t MEMPOOL_HEIGHT
Fake height value used in Coins to signify they are only in the memory pool(since 0....
Definition txmempool.h:56
uint256 uint256S(std::string_view str)
DEPRECATED.
Definition uint256.h:221
const UniValue NullUniValue
Definition univalue.cpp:16
Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess how far we are in the verification process at the given block index require cs_main if pindex h...
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
void PruneBlockFilesManual(Chainstate &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
static constexpr int DEFAULT_CHECKLEVEL
Definition validation.h:90
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pr...
Definition validation.h:88
static const signed int DEFAULT_CHECKBLOCKS
Definition validation.h:89
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.
Definition warnings.cpp:43