Bitcoin ABC 0.33.8
P2P Digital Currency
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
66 int height;
67};
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 {
456 return NullUniValue;
457 },
458 };
459}
460
462 return RPCHelpMan{
463 "getdifficulty",
464 "Returns the proof-of-work difficulty as a multiple of the minimum "
465 "difficulty.\n",
466 {},
468 "the proof-of-work difficulty as a multiple of the minimum "
469 "difficulty."},
470 RPCExamples{HelpExampleCli("getdifficulty", "") +
471 HelpExampleRpc("getdifficulty", "")},
472 [&](const RPCHelpMan &self, const Config &config,
473 const JSONRPCRequest &request) -> UniValue {
474 ChainstateManager &chainman = EnsureAnyChainman(request.context);
475 LOCK(cs_main);
476 return GetDifficulty(*CHECK_NONFATAL(chainman.ActiveTip()));
477 },
478 };
479}
480
482 return RPCHelpMan{
483 "getblockfrompeer",
484 "Attempt to fetch block from a given peer.\n"
485 "\nWe must have the header for this block, e.g. using submitheader.\n"
486 "The block will not have any undo data which can limit the usage of "
487 "the block data in a context where the undo data is needed.\n"
488 "Subsequent calls for the same block may cause the response from the "
489 "previous peer to be ignored.\n"
490 "Peers generally ignore requests for a stale block that they never "
491 "fully verified, or one that is more than a month old.\n"
492 "When a peer does not respond with a block, we will disconnect.\n"
493 "\nReturns an empty JSON object if the request was successfully "
494 "scheduled.",
495 {
497 "The block hash to try to fetch"},
499 "The peer to fetch it from (see getpeerinfo for peer IDs)"},
500 },
501 RPCResult{RPCResult::Type::OBJ, "", /*optional=*/false, "", {}},
502 RPCExamples{HelpExampleCli("getblockfrompeer",
503 "\"00000000c937983704a73af28acdec37b049d214a"
504 "dbda81d7e2a3dd146f6ed09\" 0") +
505 HelpExampleRpc("getblockfrompeer",
506 "\"00000000c937983704a73af28acdec37b049d214a"
507 "dbda81d7e2a3dd146f6ed09\" 0")},
508 [&](const RPCHelpMan &self, const Config &config,
509 const JSONRPCRequest &request) -> UniValue {
510 const NodeContext &node = EnsureAnyNodeContext(request.context);
512 PeerManager &peerman = EnsurePeerman(node);
513
514 const BlockHash block_hash{
515 ParseHashV(request.params[0], "blockhash")};
516 const NodeId peer_id{request.params[1].getInt<int64_t>()};
517
518 const CBlockIndex *const index = WITH_LOCK(
519 cs_main,
520 return chainman.m_blockman.LookupBlockIndex(block_hash););
521
522 if (!index) {
523 throw JSONRPCError(RPC_MISC_ERROR, "Block header missing");
524 }
525
526 if (WITH_LOCK(::cs_main, return index->nStatus.hasData())) {
527 throw JSONRPCError(RPC_MISC_ERROR, "Block already downloaded");
528 }
529
530 if (const auto err{peerman.FetchBlock(config, peer_id, *index)}) {
531 throw JSONRPCError(RPC_MISC_ERROR, err.value());
532 }
533 return UniValue::VOBJ;
534 },
535 };
536}
537
539 return RPCHelpMan{
540 "getblockhash",
541 "Returns hash of block in best-block-chain at height provided.\n",
542 {
544 "The height index"},
545 },
546 RPCResult{RPCResult::Type::STR_HEX, "", "The block hash"},
547 RPCExamples{HelpExampleCli("getblockhash", "1000") +
548 HelpExampleRpc("getblockhash", "1000")},
549 [&](const RPCHelpMan &self, const Config &config,
550 const JSONRPCRequest &request) -> UniValue {
551 ChainstateManager &chainman = EnsureAnyChainman(request.context);
552 LOCK(cs_main);
553 const CChain &active_chain = chainman.ActiveChain();
554
555 int nHeight = request.params[0].getInt<int>();
556 if (nHeight < 0 || nHeight > active_chain.Height()) {
558 "Block height out of range");
559 }
560
561 const CBlockIndex *pblockindex = active_chain[nHeight];
562 return pblockindex->GetBlockHash().GetHex();
563 },
564 };
565}
566
568 return RPCHelpMan{
569 "getblockheader",
570 "If verbose is false, returns a string that is serialized, hex-encoded "
571 "data for blockheader 'hash'.\n"
572 "If verbose is true, returns an Object with information about "
573 "blockheader <hash>.\n",
574 {
576 "The block hash"},
577 {"verbose", RPCArg::Type::BOOL, RPCArg::Default{true},
578 "true for a json object, false for the hex-encoded data"},
579 },
580 {
581 RPCResult{
582 "for verbose = true",
584 "",
585 "",
586 {
588 "the block hash (same as provided)"},
589 {RPCResult::Type::NUM, "confirmations",
590 "The number of confirmations, or -1 if the block is not "
591 "on the main chain"},
592 {RPCResult::Type::NUM, "height",
593 "The block height or index"},
594 {RPCResult::Type::NUM, "version", "The block version"},
595 {RPCResult::Type::STR_HEX, "versionHex",
596 "The block version formatted in hexadecimal"},
597 {RPCResult::Type::STR_HEX, "merkleroot", "The merkle root"},
599 "The block time expressed in " + UNIX_EPOCH_TIME},
600 {RPCResult::Type::NUM_TIME, "mediantime",
601 "The median block time expressed in " + UNIX_EPOCH_TIME},
602 {RPCResult::Type::NUM, "nonce", "The nonce"},
603 {RPCResult::Type::STR_HEX, "bits", "The bits"},
604 {RPCResult::Type::NUM, "difficulty", "The difficulty"},
605 {RPCResult::Type::STR_HEX, "chainwork",
606 "Expected number of hashes required to produce the "
607 "current chain"},
608 {RPCResult::Type::NUM, "nTx",
609 "The number of transactions in the block"},
610 {RPCResult::Type::STR_HEX, "previousblockhash",
611 /* optional */ true,
612 "The hash of the previous block (if available)"},
613 {RPCResult::Type::STR_HEX, "nextblockhash",
614 /* optional */ true,
615 "The hash of the next block (if available)"},
616 }},
617 RPCResult{"for verbose=false", RPCResult::Type::STR_HEX, "",
618 "A string that is serialized, hex-encoded data for block "
619 "'hash'"},
620 },
621 RPCExamples{HelpExampleCli("getblockheader",
622 "\"00000000c937983704a73af28acdec37b049d214a"
623 "dbda81d7e2a3dd146f6ed09\"") +
624 HelpExampleRpc("getblockheader",
625 "\"00000000c937983704a73af28acdec37b049d214a"
626 "dbda81d7e2a3dd146f6ed09\"")},
627 [&](const RPCHelpMan &self, const Config &config,
628 const JSONRPCRequest &request) -> UniValue {
629 BlockHash hash(ParseHashV(request.params[0], "hash"));
630
631 bool fVerbose = true;
632 if (!request.params[1].isNull()) {
633 fVerbose = request.params[1].get_bool();
634 }
635
636 const CBlockIndex *pblockindex;
637 const CBlockIndex *tip;
638 {
639 ChainstateManager &chainman =
640 EnsureAnyChainman(request.context);
641 LOCK(cs_main);
642 pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
643 tip = chainman.ActiveTip();
644 }
645
646 if (!pblockindex) {
648 "Block not found");
649 }
650
651 if (!fVerbose) {
652 DataStream ssBlock{};
653 ssBlock << pblockindex->GetBlockHeader();
654 std::string strHex = HexStr(ssBlock);
655 return strHex;
656 }
657
658 return blockheaderToJSON(*tip, *pblockindex);
659 },
660 };
661}
662
664 const CBlockIndex &blockindex) {
665 CBlock block;
666 {
667 LOCK(cs_main);
668 if (blockman.IsBlockPruned(blockindex)) {
670 "Block not available (pruned data)");
671 }
672 }
673
674 if (!blockman.ReadBlock(block, blockindex)) {
675 // Block not found on disk. This could be because we have the block
676 // header in our index but not yet have the block or did not accept the
677 // block. Or if the block was pruned right after we released the lock
678 // above.
679 throw JSONRPCError(RPC_MISC_ERROR, "Block not found on disk");
680 }
681
682 return block;
683}
684
686 const CBlockIndex &blockindex) {
687 CBlockUndo blockUndo;
688
689 {
690 LOCK(cs_main);
691 if (blockman.IsBlockPruned(blockindex)) {
693 "Undo data not available (pruned data)");
694 }
695 }
696
697 if (!blockman.ReadBlockUndo(blockUndo, blockindex)) {
698 throw JSONRPCError(RPC_MISC_ERROR, "Can't read undo data from disk");
699 }
700
701 return blockUndo;
702}
703
705 return RPCHelpMan{
706 "getblock",
707 "If verbosity is 0 or false, returns a string that is serialized, "
708 "hex-encoded data for block 'hash'.\n"
709 "If verbosity is 1 or true, returns an Object with information about "
710 "block <hash>.\n"
711 "If verbosity is 2, returns an Object with information about block "
712 "<hash> and information about each transaction.\n"
713 "If verbosity is 3, returns an Object with information about block "
714 "<hash> and information about each transaction, including prevout "
715 "information for inputs (only for unpruned blocks in the current best "
716 "chain).\n",
717 {
719 "The block hash"},
720 {"verbosity|verbose", RPCArg::Type::NUM, RPCArg::Default{1},
721 "0 for hex-encoded data, 1 for a json object, and 2 for json "
722 "object with transaction data",
724 },
725 {
726 RPCResult{"for verbosity = 0", RPCResult::Type::STR_HEX, "",
727 "A string that is serialized, hex-encoded data for block "
728 "'hash'"},
729 RPCResult{
730 "for verbosity = 1",
732 "",
733 "",
734 {
736 "the block hash (same as provided)"},
737 {RPCResult::Type::NUM, "confirmations",
738 "The number of confirmations, or -1 if the block is not "
739 "on the main chain"},
740 {RPCResult::Type::NUM, "size", "The block size"},
741 {RPCResult::Type::NUM, "height",
742 "The block height or index"},
743 {RPCResult::Type::NUM, "version", "The block version"},
744 {RPCResult::Type::STR_HEX, "versionHex",
745 "The block version formatted in hexadecimal"},
746 {RPCResult::Type::STR_HEX, "merkleroot", "The merkle root"},
748 "tx",
749 "The transaction ids",
750 {{RPCResult::Type::STR_HEX, "", "The transaction id"}}},
752 "The block time expressed in " + UNIX_EPOCH_TIME},
753 {RPCResult::Type::NUM_TIME, "mediantime",
754 "The median block time expressed in " + UNIX_EPOCH_TIME},
755 {RPCResult::Type::NUM, "nonce", "The nonce"},
756 {RPCResult::Type::STR_HEX, "bits", "The bits"},
757 {RPCResult::Type::NUM, "difficulty", "The difficulty"},
758 {RPCResult::Type::STR_HEX, "chainwork",
759 "Expected number of hashes required to produce the chain "
760 "up to this block (in hex)"},
761 {RPCResult::Type::NUM, "nTx",
762 "The number of transactions in the block"},
763 {RPCResult::Type::STR_HEX, "previousblockhash",
764 /* optional */ true,
765 "The hash of the previous block (if available)"},
766 {RPCResult::Type::STR_HEX, "nextblockhash",
767 /* optional */ true,
768 "The hash of the next block (if available)"},
769 }},
770 RPCResult{"for verbosity = 2",
772 "",
773 "",
774 {
776 "Same output as verbosity = 1"},
778 "tx",
779 "",
780 {
782 "",
783 "",
784 {
786 "The transactions in the format of the "
787 "getrawtransaction RPC. Different from "
788 "verbosity = 1 \"tx\" result"},
790 "The transaction fee in " +
792 ", omitted if block undo data is not "
793 "available"},
794 }},
795 }},
796 }},
797 },
799 HelpExampleCli("getblock", "\"00000000c937983704a73af28acdec37b049d"
800 "214adbda81d7e2a3dd146f6ed09\"") +
801 HelpExampleRpc("getblock", "\"00000000c937983704a73af28acdec37b049d"
802 "214adbda81d7e2a3dd146f6ed09\"")},
803 [&](const RPCHelpMan &self, const Config &config,
804 const JSONRPCRequest &request) -> UniValue {
805 BlockHash hash(ParseHashV(request.params[0], "blockhash"));
806
807 int verbosity = 1;
808 if (!request.params[1].isNull()) {
809 if (request.params[1].isNum()) {
810 verbosity = request.params[1].getInt<int>();
811 } else {
812 verbosity = request.params[1].get_bool() ? 1 : 0;
813 }
814 }
815
816 const CBlockIndex *pblockindex;
817 const CBlockIndex *tip;
818 ChainstateManager &chainman = EnsureAnyChainman(request.context);
819 {
820 LOCK(cs_main);
821 pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
822 tip = chainman.ActiveTip();
823
824 if (!pblockindex) {
826 "Block not found");
827 }
828 }
829
830 const CBlock block =
831 GetBlockChecked(chainman.m_blockman, *pblockindex);
832
833 if (verbosity <= 0) {
834 DataStream ssBlock{};
835 ssBlock << block;
836 std::string strHex = HexStr(ssBlock);
837 return strHex;
838 }
839
840 TxVerbosity tx_verbosity;
841 if (verbosity == 1) {
842 tx_verbosity = TxVerbosity::SHOW_TXID;
843 } else if (verbosity == 2) {
844 tx_verbosity = TxVerbosity::SHOW_DETAILS;
845 } else {
847 }
848
849 return blockToJSON(chainman.m_blockman, block, *tip, *pblockindex,
850 tx_verbosity);
851 },
852 };
853}
854
855std::optional<int> GetPruneHeight(const BlockManager &blockman,
856 const CChain &chain) {
858
859 // Search for the last block missing block data or undo data. Don't let the
860 // search consider the genesis block, because the genesis block does not
861 // have undo data, but should not be considered pruned.
862 const CBlockIndex *first_block{chain[1]};
863 const CBlockIndex *chain_tip{chain.Tip()};
864
865 // If there are no blocks after the genesis block, or no blocks at all,
866 // nothing is pruned.
867 if (!first_block || !chain_tip) {
868 return std::nullopt;
869 }
870
871 // If the chain tip is pruned, everything is pruned.
872 if (!(chain_tip->nStatus.hasData() && chain_tip->nStatus.hasUndo())) {
873 return chain_tip->nHeight;
874 }
875
876 // Get first block with data, after the last block without data.
877 // This is the start of the unpruned range of blocks.
878 const CBlockIndex *first_unpruned{CHECK_NONFATAL(
879 blockman.GetFirstBlock(*chain_tip,
880 /*status_test=*/[](const BlockStatus &status) {
881 return status.hasData() && status.hasUndo();
882 }))};
883 if (first_unpruned == first_block) {
884 // All blocks between first_block and chain_tip have data, so nothing is
885 // pruned.
886 return std::nullopt;
887 }
888
889 // Block before the first unpruned block is the last pruned block.
890 return CHECK_NONFATAL(first_unpruned->pprev)->nHeight;
891}
892
894 return RPCHelpMan{
895 "pruneblockchain",
896 "",
897 {
899 "The block height to prune up to. May be set to a discrete "
900 "height, or to a " +
902 "\n"
903 " to prune blocks whose block time is at "
904 "least 2 hours older than the provided timestamp."},
905 },
906 RPCResult{RPCResult::Type::NUM, "", "Height of the last block pruned"},
907 RPCExamples{HelpExampleCli("pruneblockchain", "1000") +
908 HelpExampleRpc("pruneblockchain", "1000")},
909 [&](const RPCHelpMan &self, const Config &config,
910 const JSONRPCRequest &request) -> UniValue {
911 ChainstateManager &chainman = EnsureAnyChainman(request.context);
912 if (!chainman.m_blockman.IsPruneMode()) {
913 throw JSONRPCError(
915 "Cannot prune blocks because node is not in prune mode.");
916 }
917
918 LOCK(cs_main);
919 Chainstate &active_chainstate = chainman.ActiveChainstate();
920 CChain &active_chain = active_chainstate.m_chain;
921
922 int heightParam = request.params[0].getInt<int>();
923 if (heightParam < 0) {
925 "Negative block height.");
926 }
927
928 // Height value more than a billion is too high to be a block
929 // height, and too low to be a block time (corresponds to timestamp
930 // from Sep 2001).
931 if (heightParam > 1000000000) {
932 // Add a 2 hour buffer to include blocks which might have had
933 // old timestamps
934 const CBlockIndex *pindex = active_chain.FindEarliestAtLeast(
935 heightParam - TIMESTAMP_WINDOW, 0);
936 if (!pindex) {
938 "Could not find block with at least the "
939 "specified timestamp.");
940 }
941 heightParam = pindex->nHeight;
942 }
943
944 unsigned int height = (unsigned int)heightParam;
945 unsigned int chainHeight = (unsigned int)active_chain.Height();
946 if (chainHeight < config.GetChainParams().PruneAfterHeight()) {
948 "Blockchain is too short for pruning.");
949 } else if (height > chainHeight) {
950 throw JSONRPCError(
952 "Blockchain is shorter than the attempted prune height.");
953 } else if (height > chainHeight - MIN_BLOCKS_TO_KEEP) {
955 "Attempt to prune blocks close to the tip. "
956 "Retaining the minimum number of blocks.\n");
957 height = chainHeight - MIN_BLOCKS_TO_KEEP;
958 }
959
960 PruneBlockFilesManual(active_chainstate, height);
961 return GetPruneHeight(chainman.m_blockman, active_chain)
962 .value_or(-1);
963 },
964 };
965}
966
967static CoinStatsHashType ParseHashType(const std::string &hash_type_input) {
968 if (hash_type_input == "hash_serialized") {
969 return CoinStatsHashType::HASH_SERIALIZED;
970 } else if (hash_type_input == "muhash") {
971 return CoinStatsHashType::MUHASH;
972 } else if (hash_type_input == "none") {
974 } else {
975 throw JSONRPCError(
977 strprintf("%s is not a valid hash_type", hash_type_input));
978 }
979}
980
982 return RPCHelpMan{
983 "gettxoutsetinfo",
984 "Returns statistics about the unspent transaction output set.\n"
985 "Note this call may take some time if you are not using "
986 "coinstatsindex.\n",
987 {
988 {"hash_type", RPCArg::Type::STR, RPCArg::Default{"hash_serialized"},
989 "Which UTXO set hash should be calculated. Options: "
990 "'hash_serialized' (the legacy algorithm), 'muhash', 'none'."},
992 "The block hash or height of the target height (only available "
993 "with coinstatsindex).",
995 .type_str = {"", "string or numeric"}}},
996 {"use_index", RPCArg::Type::BOOL, RPCArg::Default{true},
997 "Use coinstatsindex, if available."},
998 },
999 RPCResult{
1001 "",
1002 "",
1003 {
1004 {RPCResult::Type::NUM, "height",
1005 "The current block height (index)"},
1006 {RPCResult::Type::STR_HEX, "bestblock",
1007 "The hash of the block at the tip of the chain"},
1008 {RPCResult::Type::NUM, "txouts",
1009 "The number of unspent transaction outputs"},
1010 {RPCResult::Type::NUM, "bogosize",
1011 "Database-independent, meaningless metric indicating "
1012 "the UTXO set size"},
1013 {RPCResult::Type::STR_HEX, "hash_serialized",
1014 /* optional */ true,
1015 "The serialized hash (only present if 'hash_serialized' "
1016 "hash_type is chosen)"},
1017 {RPCResult::Type::STR_HEX, "muhash", /* optional */ true,
1018 "The serialized hash (only present if 'muhash' "
1019 "hash_type is chosen)"},
1020 {RPCResult::Type::NUM, "transactions",
1021 "The number of transactions with unspent outputs (not "
1022 "available when coinstatsindex is used)"},
1023 {RPCResult::Type::NUM, "disk_size",
1024 "The estimated size of the chainstate on disk (not "
1025 "available when coinstatsindex is used)"},
1026 {RPCResult::Type::STR_AMOUNT, "total_amount",
1027 "The total amount"},
1028 {RPCResult::Type::STR_AMOUNT, "total_unspendable_amount",
1029 "The total amount of coins permanently excluded from the UTXO "
1030 "set (only available if coinstatsindex is used)"},
1032 "block_info",
1033 "Info on amounts in the block at this block height (only "
1034 "available if coinstatsindex is used)",
1035 {{RPCResult::Type::STR_AMOUNT, "prevout_spent",
1036 "Total amount of all prevouts spent in this block"},
1037 {RPCResult::Type::STR_AMOUNT, "coinbase",
1038 "Coinbase subsidy amount of this block"},
1039 {RPCResult::Type::STR_AMOUNT, "new_outputs_ex_coinbase",
1040 "Total amount of new outputs created by this block"},
1041 {RPCResult::Type::STR_AMOUNT, "unspendable",
1042 "Total amount of unspendable outputs created in this block"},
1044 "unspendables",
1045 "Detailed view of the unspendable categories",
1046 {
1047 {RPCResult::Type::STR_AMOUNT, "genesis_block",
1048 "The unspendable amount of the Genesis block subsidy"},
1050 "Transactions overridden by duplicates (no longer "
1051 "possible with BIP30)"},
1052 {RPCResult::Type::STR_AMOUNT, "scripts",
1053 "Amounts sent to scripts that are unspendable (for "
1054 "example OP_RETURN outputs)"},
1055 {RPCResult::Type::STR_AMOUNT, "unclaimed_rewards",
1056 "Fee rewards that miners did not claim in their "
1057 "coinbase transaction"},
1058 }}}},
1059 }},
1061 HelpExampleCli("gettxoutsetinfo", "") +
1062 HelpExampleCli("gettxoutsetinfo", R"("none")") +
1063 HelpExampleCli("gettxoutsetinfo", R"("none" 1000)") +
1065 "gettxoutsetinfo",
1066 R"("none" '"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"')") +
1067 HelpExampleRpc("gettxoutsetinfo", "") +
1068 HelpExampleRpc("gettxoutsetinfo", R"("none")") +
1069 HelpExampleRpc("gettxoutsetinfo", R"("none", 1000)") +
1071 "gettxoutsetinfo",
1072 R"("none", "00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09")")},
1073 [&](const RPCHelpMan &self, const Config &config,
1074 const JSONRPCRequest &request) -> UniValue {
1076
1077 const CBlockIndex *pindex{nullptr};
1078 const CoinStatsHashType hash_type{
1079 request.params[0].isNull()
1080 ? CoinStatsHashType::HASH_SERIALIZED
1081 : ParseHashType(request.params[0].get_str())};
1082 bool index_requested =
1083 request.params[2].isNull() || request.params[2].get_bool();
1084
1085 NodeContext &node = EnsureAnyNodeContext(request.context);
1087 Chainstate &active_chainstate = chainman.ActiveChainstate();
1088 active_chainstate.ForceFlushStateToDisk();
1089
1090 CCoinsView *coins_view;
1091 BlockManager *blockman;
1092 {
1093 LOCK(::cs_main);
1094 coins_view = &active_chainstate.CoinsDB();
1095 blockman = &active_chainstate.m_blockman;
1096 pindex = blockman->LookupBlockIndex(coins_view->GetBestBlock());
1097 }
1098
1099 if (!request.params[1].isNull()) {
1100 if (!g_coin_stats_index) {
1102 "Querying specific block heights "
1103 "requires coinstatsindex");
1104 }
1105
1106 if (hash_type == CoinStatsHashType::HASH_SERIALIZED) {
1108 "hash_serialized hash type cannot be "
1109 "queried for a specific block");
1110 }
1111
1112 pindex = ParseHashOrHeight(request.params[1], chainman);
1113 }
1114
1115 if (index_requested && g_coin_stats_index) {
1116 if (!g_coin_stats_index->BlockUntilSyncedToCurrentChain()) {
1117 const IndexSummary summary{
1118 g_coin_stats_index->GetSummary()};
1119
1120 // If a specific block was requested and the index has
1121 // already synced past that height, we can return the data
1122 // already even though the index is not fully synced yet.
1123 if (pindex->nHeight > summary.best_block_height) {
1124 throw JSONRPCError(
1126 strprintf(
1127 "Unable to get data because coinstatsindex is "
1128 "still syncing. Current height: %d",
1129 summary.best_block_height));
1130 }
1131 }
1132 }
1133
1134 const std::optional<CCoinsStats> maybe_stats = GetUTXOStats(
1135 coins_view, *blockman, hash_type, node.rpc_interruption_point,
1136 pindex, index_requested);
1137 if (maybe_stats.has_value()) {
1138 const CCoinsStats &stats = maybe_stats.value();
1139 ret.pushKV("height", int64_t(stats.nHeight));
1140 ret.pushKV("bestblock", stats.hashBlock.GetHex());
1141 ret.pushKV("txouts", int64_t(stats.nTransactionOutputs));
1142 ret.pushKV("bogosize", int64_t(stats.nBogoSize));
1143 if (hash_type == CoinStatsHashType::HASH_SERIALIZED) {
1144 ret.pushKV("hash_serialized",
1145 stats.hashSerialized.GetHex());
1146 }
1147 if (hash_type == CoinStatsHashType::MUHASH) {
1148 ret.pushKV("muhash", stats.hashSerialized.GetHex());
1149 }
1150 CHECK_NONFATAL(stats.total_amount.has_value());
1151 ret.pushKV("total_amount", stats.total_amount.value());
1152 if (!stats.index_used) {
1153 ret.pushKV("transactions",
1154 static_cast<int64_t>(stats.nTransactions));
1155 ret.pushKV("disk_size", stats.nDiskSize);
1156 } else {
1157 ret.pushKV("total_unspendable_amount",
1159
1160 CCoinsStats prev_stats{};
1161 if (pindex->nHeight > 0) {
1162 const std::optional<CCoinsStats> maybe_prev_stats =
1163 GetUTXOStats(coins_view, *blockman, hash_type,
1164 node.rpc_interruption_point,
1165 pindex->pprev, index_requested);
1166 if (!maybe_prev_stats) {
1168 "Unable to read UTXO set");
1169 }
1170 prev_stats = maybe_prev_stats.value();
1171 }
1172
1173 UniValue block_info(UniValue::VOBJ);
1174 block_info.pushKV(
1175 "prevout_spent",
1177 prev_stats.total_prevout_spent_amount);
1178 block_info.pushKV("coinbase",
1179 stats.total_coinbase_amount -
1180 prev_stats.total_coinbase_amount);
1181 block_info.pushKV(
1182 "new_outputs_ex_coinbase",
1184 prev_stats.total_new_outputs_ex_coinbase_amount);
1185 block_info.pushKV("unspendable",
1187 prev_stats.total_unspendable_amount);
1188
1189 UniValue unspendables(UniValue::VOBJ);
1190 unspendables.pushKV(
1191 "genesis_block",
1193 prev_stats.total_unspendables_genesis_block);
1194 unspendables.pushKV(
1195 "bip30", stats.total_unspendables_bip30 -
1196 prev_stats.total_unspendables_bip30);
1197 unspendables.pushKV(
1198 "scripts", stats.total_unspendables_scripts -
1199 prev_stats.total_unspendables_scripts);
1200 unspendables.pushKV(
1201 "unclaimed_rewards",
1203 prev_stats.total_unspendables_unclaimed_rewards);
1204 block_info.pushKV("unspendables", std::move(unspendables));
1205
1206 ret.pushKV("block_info", std::move(block_info));
1207 }
1208 } else {
1210 "Unable to read UTXO set");
1211 }
1212 return ret;
1213 },
1214 };
1215}
1216
1218 return RPCHelpMan{
1219 "gettxout",
1220 "Returns details about an unspent transaction output.\n",
1221 {
1223 "The transaction id"},
1224 {"n", RPCArg::Type::NUM, RPCArg::Optional::NO, "vout number"},
1225 {"include_mempool", RPCArg::Type::BOOL, RPCArg::Default{true},
1226 "Whether to include the mempool. Note that an unspent output that "
1227 "is spent in the mempool won't appear."},
1228 },
1229 {
1230 RPCResult{"If the UTXO was not found", RPCResult::Type::NONE, "",
1231 ""},
1232 RPCResult{
1233 "Otherwise",
1235 "",
1236 "",
1237 {
1238 {RPCResult::Type::STR_HEX, "bestblock",
1239 "The hash of the block at the tip of the chain"},
1240 {RPCResult::Type::NUM, "confirmations",
1241 "The number of confirmations"},
1243 "The transaction value in " + Currency::get().ticker},
1245 "scriptPubKey",
1246 "",
1247 {
1248 {RPCResult::Type::STR_HEX, "asm", ""},
1249 {RPCResult::Type::STR_HEX, "hex", ""},
1250 {RPCResult::Type::NUM, "reqSigs",
1251 "Number of required signatures"},
1252 {RPCResult::Type::STR_HEX, "type",
1253 "The type, eg pubkeyhash"},
1255 "addresses",
1256 "array of eCash addresses",
1257 {{RPCResult::Type::STR, "address", "eCash address"}}},
1258 }},
1259 {RPCResult::Type::BOOL, "coinbase", "Coinbase or not"},
1260 }},
1261 },
1262 RPCExamples{"\nGet unspent transactions\n" +
1263 HelpExampleCli("listunspent", "") + "\nView the details\n" +
1264 HelpExampleCli("gettxout", "\"txid\" 1") +
1265 "\nAs a JSON-RPC call\n" +
1266 HelpExampleRpc("gettxout", "\"txid\", 1")},
1267 [&](const RPCHelpMan &self, const Config &config,
1268 const JSONRPCRequest &request) -> UniValue {
1269 NodeContext &node = EnsureAnyNodeContext(request.context);
1271 LOCK(cs_main);
1272
1274
1275 TxId txid(ParseHashV(request.params[0], "txid"));
1276 int n = request.params[1].getInt<int>();
1277 COutPoint out(txid, n);
1278 bool fMempool = true;
1279 if (!request.params[2].isNull()) {
1280 fMempool = request.params[2].get_bool();
1281 }
1282
1283 Chainstate &active_chainstate = chainman.ActiveChainstate();
1284 CCoinsViewCache *coins_view = &active_chainstate.CoinsTip();
1285
1286 std::optional<Coin> coin;
1287 if (fMempool) {
1288 const CTxMemPool &mempool = EnsureMemPool(node);
1289 LOCK(mempool.cs);
1290 CCoinsViewMemPool view(coins_view, mempool);
1291 if (!mempool.isSpent(out)) {
1292 coin = view.GetCoin(out);
1293 }
1294 } else {
1295 coin = coins_view->GetCoin(out);
1296 }
1297 if (!coin) {
1298 return UniValue::VNULL;
1299 }
1300
1301 const CBlockIndex *pindex =
1302 active_chainstate.m_blockman.LookupBlockIndex(
1303 coins_view->GetBestBlock());
1304 ret.pushKV("bestblock", pindex->GetBlockHash().GetHex());
1305 if (coin->GetHeight() == MEMPOOL_HEIGHT) {
1306 ret.pushKV("confirmations", 0);
1307 } else {
1308 ret.pushKV("confirmations",
1309 int64_t(pindex->nHeight - coin->GetHeight() + 1));
1310 }
1311 ret.pushKV("value", coin->GetTxOut().nValue);
1313 ScriptPubKeyToUniv(coin->GetTxOut().scriptPubKey, o, true);
1314 ret.pushKV("scriptPubKey", std::move(o));
1315 ret.pushKV("coinbase", coin->IsCoinBase());
1316
1317 return ret;
1318 },
1319 };
1320}
1321
1323 return RPCHelpMan{
1324 "verifychain",
1325 "Verifies blockchain database.\n",
1326 {
1327 {"checklevel", RPCArg::Type::NUM,
1329 strprintf("%d, range=0-4", DEFAULT_CHECKLEVEL)},
1330 strprintf("How thorough the block verification is:\n%s",
1332 {"nblocks", RPCArg::Type::NUM,
1334 "The number of blocks to check."},
1335 },
1337 "Verification finished successfully. If false, check "
1338 "debug.log for reason."},
1339 RPCExamples{HelpExampleCli("verifychain", "") +
1340 HelpExampleRpc("verifychain", "")},
1341 [&](const RPCHelpMan &self, const Config &config,
1342 const JSONRPCRequest &request) -> UniValue {
1343 const int check_level{request.params[0].isNull()
1345 : request.params[0].getInt<int>()};
1346 const int check_depth{request.params[1].isNull()
1348 : request.params[1].getInt<int>()};
1349
1350 ChainstateManager &chainman = EnsureAnyChainman(request.context);
1351 LOCK(cs_main);
1352
1353 Chainstate &active_chainstate = chainman.ActiveChainstate();
1354 return CVerifyDB(chainman.GetNotifications())
1355 .VerifyDB(active_chainstate,
1356 active_chainstate.CoinsTip(), check_level,
1357 check_depth) == VerifyDBResult::SUCCESS;
1358 },
1359 };
1360}
1361
1363 return RPCHelpMan{
1364 "getblockchaininfo",
1365 "Returns an object containing various state info regarding blockchain "
1366 "processing.\n",
1367 {},
1368 RPCResult{
1370 "",
1371 "",
1372 {
1373 {RPCResult::Type::STR, "chain",
1374 "current network name (main, test, regtest)"},
1375 {RPCResult::Type::NUM, "blocks",
1376 "the height of the most-work fully-validated "
1377 "non-parked chain. The genesis block has height 0"},
1378 {RPCResult::Type::NUM, "headers",
1379 "the current number of headers we have validated"},
1380 {RPCResult::Type::NUM, "finalized_blockhash",
1381 "the hash of the avalanche finalized tip if any, otherwise "
1382 "the genesis block hash"},
1383 {RPCResult::Type::STR, "bestblockhash",
1384 "the hash of the currently best block"},
1385 {RPCResult::Type::NUM, "difficulty", "the current difficulty"},
1387 "The block time expressed in " + UNIX_EPOCH_TIME},
1388 {RPCResult::Type::NUM_TIME, "mediantime",
1389 "The median block time expressed in " + UNIX_EPOCH_TIME},
1390 {RPCResult::Type::NUM, "verificationprogress",
1391 "estimate of verification progress [0..1]"},
1392 {RPCResult::Type::BOOL, "initialblockdownload",
1393 "(debug information) estimate of whether this node is in "
1394 "Initial Block Download mode"},
1395 {RPCResult::Type::STR_HEX, "chainwork",
1396 "total amount of work in active chain, in hexadecimal"},
1397 {RPCResult::Type::NUM, "size_on_disk",
1398 "the estimated size of the block and undo files on disk"},
1399 {RPCResult::Type::BOOL, "pruned",
1400 "if the blocks are subject to pruning"},
1401 {RPCResult::Type::NUM, "pruneheight",
1402 "lowest-height complete block stored (only present if pruning "
1403 "is enabled)"},
1404 {RPCResult::Type::BOOL, "automatic_pruning",
1405 "whether automatic pruning is enabled (only present if "
1406 "pruning is enabled)"},
1407 {RPCResult::Type::NUM, "prune_target_size",
1408 "the target size used by pruning (only present if automatic "
1409 "pruning is enabled)"},
1410 {RPCResult::Type::STR, "warnings",
1411 "any network and blockchain warnings"},
1412 }},
1413 RPCExamples{HelpExampleCli("getblockchaininfo", "") +
1414 HelpExampleRpc("getblockchaininfo", "")},
1415 [&](const RPCHelpMan &self, const Config &config,
1416 const JSONRPCRequest &request) -> UniValue {
1417 const CChainParams &chainparams = config.GetChainParams();
1418
1419 ChainstateManager &chainman = EnsureAnyChainman(request.context);
1420 LOCK(cs_main);
1421 Chainstate &active_chainstate = chainman.ActiveChainstate();
1422
1423 const CBlockIndex &tip{
1424 *CHECK_NONFATAL(active_chainstate.m_chain.Tip())};
1425 const int height{tip.nHeight};
1426
1428 obj.pushKV("chain", chainparams.GetChainTypeString());
1429 obj.pushKV("blocks", height);
1430 obj.pushKV("headers", chainman.m_best_header
1431 ? chainman.m_best_header->nHeight
1432 : -1);
1433 auto avalanche_finalized_tip{chainman.GetAvalancheFinalizedTip()};
1434 obj.pushKV("finalized_blockhash",
1435 avalanche_finalized_tip
1436 ? avalanche_finalized_tip->GetBlockHash().GetHex()
1437 : chainparams.GenesisBlock().GetHash().GetHex());
1438 obj.pushKV("bestblockhash", tip.GetBlockHash().GetHex());
1439 obj.pushKV("difficulty", GetDifficulty(tip));
1440 obj.pushKV("time", tip.GetBlockTime());
1441 obj.pushKV("mediantime", tip.GetMedianTimePast());
1442 obj.pushKV(
1443 "verificationprogress",
1444 GuessVerificationProgress(chainman.GetParams().TxData(), &tip));
1445 obj.pushKV("initialblockdownload",
1446 chainman.IsInitialBlockDownload());
1447 obj.pushKV("chainwork", tip.nChainWork.GetHex());
1448 obj.pushKV("size_on_disk",
1450 obj.pushKV("pruned", chainman.m_blockman.IsPruneMode());
1451
1452 if (chainman.m_blockman.IsPruneMode()) {
1453 const auto prune_height{GetPruneHeight(
1454 chainman.m_blockman, active_chainstate.m_chain)};
1455 obj.pushKV("pruneheight",
1456 prune_height ? prune_height.value() + 1 : 0);
1457
1458 const bool automatic_pruning{
1459 chainman.m_blockman.GetPruneTarget() !=
1460 BlockManager::PRUNE_TARGET_MANUAL};
1461 obj.pushKV("automatic_pruning", automatic_pruning);
1462 if (automatic_pruning) {
1463 obj.pushKV("prune_target_size",
1464 chainman.m_blockman.GetPruneTarget());
1465 }
1466 }
1467
1468 obj.pushKV("warnings", GetWarnings(false).original);
1469 return obj;
1470 },
1471 };
1472}
1473
1476 bool operator()(const CBlockIndex *a, const CBlockIndex *b) const {
1477 // Make sure that unequal blocks with the same height do not compare
1478 // equal. Use the pointers themselves to make a distinction.
1479 if (a->nHeight != b->nHeight) {
1480 return (a->nHeight > b->nHeight);
1481 }
1482
1483 return a < b;
1484 }
1485};
1486
1488 return RPCHelpMan{
1489 "getchaintips",
1490 "Return information about all known tips in the block tree, including "
1491 "the main chain as well as orphaned branches.\n",
1492 {},
1493 RPCResult{
1495 "",
1496 "",
1498 "",
1499 "",
1500 {
1501 {RPCResult::Type::NUM, "height", "height of the chain tip"},
1502 {RPCResult::Type::STR_HEX, "hash", "block hash of the tip"},
1503 {RPCResult::Type::NUM, "branchlen",
1504 "zero for main chain, otherwise length of branch connecting "
1505 "the tip to the main chain"},
1506 {RPCResult::Type::STR, "status",
1507 "status of the chain, \"active\" for the main chain\n"
1508 "Possible values for status:\n"
1509 "1. \"invalid\" This branch contains at "
1510 "least one invalid block\n"
1511 "2. \"parked\" This branch contains at "
1512 "least one parked block\n"
1513 "3. \"headers-only\" Not all blocks for this "
1514 "branch are available, but the headers are valid\n"
1515 "4. \"valid-headers\" All blocks are available for "
1516 "this branch, but they were never fully validated\n"
1517 "5. \"valid-fork\" This branch is not part of "
1518 "the active chain, but is fully validated\n"
1519 "6. \"active\" This is the tip of the "
1520 "active main chain, which is certainly valid"},
1521 }}}},
1522 RPCExamples{HelpExampleCli("getchaintips", "") +
1523 HelpExampleRpc("getchaintips", "")},
1524 [&](const RPCHelpMan &self, const Config &config,
1525 const JSONRPCRequest &request) -> UniValue {
1526 ChainstateManager &chainman = EnsureAnyChainman(request.context);
1527 LOCK(cs_main);
1528 CChain &active_chain = chainman.ActiveChain();
1529
1541 std::set<const CBlockIndex *, CompareBlocksByHeight> setTips;
1542 std::set<const CBlockIndex *> setOrphans;
1543 std::set<const CBlockIndex *> setPrevs;
1544
1545 for (const auto &[_, block_index] : chainman.BlockIndex()) {
1546 if (!active_chain.Contains(&block_index)) {
1547 setOrphans.insert(&block_index);
1548 setPrevs.insert(block_index.pprev);
1549 }
1550 }
1551
1552 for (std::set<const CBlockIndex *>::iterator it =
1553 setOrphans.begin();
1554 it != setOrphans.end(); ++it) {
1555 if (setPrevs.erase(*it) == 0) {
1556 setTips.insert(*it);
1557 }
1558 }
1559
1560 // Always report the currently active tip.
1561 setTips.insert(active_chain.Tip());
1562
1563 /* Construct the output array. */
1565 for (const CBlockIndex *block : setTips) {
1567 obj.pushKV("height", block->nHeight);
1568 obj.pushKV("hash", block->phashBlock->GetHex());
1569
1570 const int branchLen =
1571 block->nHeight - active_chain.FindFork(block)->nHeight;
1572 obj.pushKV("branchlen", branchLen);
1573
1574 std::string status;
1575 if (active_chain.Contains(block)) {
1576 // This block is part of the currently active chain.
1577 status = "active";
1578 } else if (block->nStatus.isInvalid()) {
1579 // This block or one of its ancestors is invalid.
1580 status = "invalid";
1581 } else if (block->nStatus.isOnParkedChain()) {
1582 // This block or one of its ancestors is parked.
1583 status = "parked";
1584 } else if (!block->HaveNumChainTxs()) {
1585 // This block cannot be connected because full block data
1586 // for it or one of its parents is missing.
1587 status = "headers-only";
1588 } else if (block->IsValid(BlockValidity::SCRIPTS)) {
1589 // This block is fully validated, but no longer part of the
1590 // active chain. It was probably the active block once, but
1591 // was reorganized.
1592 status = "valid-fork";
1593 } else if (block->IsValid(BlockValidity::TREE)) {
1594 // The headers for this block are valid, but it has not been
1595 // validated. It was probably never part of the most-work
1596 // chain.
1597 status = "valid-headers";
1598 } else {
1599 // No clue.
1600 status = "unknown";
1601 }
1602 obj.pushKV("status", status);
1603
1604 res.push_back(std::move(obj));
1605 }
1606
1607 return res;
1608 },
1609 };
1610}
1611
1613 return RPCHelpMan{
1614 "preciousblock",
1615 "Treats a block as if it were received before others with the same "
1616 "work.\n"
1617 "\nA later preciousblock call can override the effect of an earlier "
1618 "one.\n"
1619 "\nThe effects of preciousblock are not retained across restarts.\n",
1620 {
1622 "the hash of the block to mark as precious"},
1623 },
1625 RPCExamples{HelpExampleCli("preciousblock", "\"blockhash\"") +
1626 HelpExampleRpc("preciousblock", "\"blockhash\"")},
1627 [&](const RPCHelpMan &self, const Config &config,
1628 const JSONRPCRequest &request) -> UniValue {
1629 BlockHash hash(ParseHashV(request.params[0], "blockhash"));
1630 CBlockIndex *pblockindex;
1631
1632 NodeContext &node = EnsureAnyNodeContext(request.context);
1634 {
1635 LOCK(cs_main);
1636 pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
1637 if (!pblockindex) {
1639 "Block not found");
1640 }
1641 }
1642
1644 chainman.ActiveChainstate().PreciousBlock(state, pblockindex,
1645 node.avalanche.get());
1646
1647 if (!state.IsValid()) {
1649 }
1650
1651 // Block to make sure wallet/indexers sync before returning
1653
1654 return NullUniValue;
1655 },
1656 };
1657}
1658
1661 const BlockHash &block_hash) {
1663 CBlockIndex *pblockindex;
1664 {
1665 LOCK(chainman.GetMutex());
1666 pblockindex = chainman.m_blockman.LookupBlockIndex(block_hash);
1667 if (!pblockindex) {
1668 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
1669 }
1670 }
1671 chainman.ActiveChainstate().InvalidateBlock(state, pblockindex);
1672
1673 if (state.IsValid()) {
1674 chainman.ActiveChainstate().ActivateBestChain(state, /*pblock=*/nullptr,
1675 avalanche);
1676 }
1677
1678 if (!state.IsValid()) {
1680 }
1681}
1682
1684 return RPCHelpMan{
1685 "invalidateblock",
1686 "Permanently marks a block as invalid, as if it violated a consensus "
1687 "rule.\n",
1688 {
1690 "the hash of the block to mark as invalid"},
1691 },
1693 RPCExamples{HelpExampleCli("invalidateblock", "\"blockhash\"") +
1694 HelpExampleRpc("invalidateblock", "\"blockhash\"")},
1695 [&](const RPCHelpMan &self, const Config &config,
1696 const JSONRPCRequest &request) -> UniValue {
1697 NodeContext &node = EnsureAnyNodeContext(request.context);
1699 const BlockHash hash(ParseHashV(request.params[0], "blockhash"));
1700
1701 InvalidateBlock(chainman, node.avalanche.get(), hash);
1702 // Block to make sure wallet/indexers sync before returning
1704
1705 return NullUniValue;
1706 },
1707 };
1708}
1709
1711 return RPCHelpMan{
1712 "parkblock",
1713 "Marks a block as parked.\n",
1714 {
1716 "the hash of the block to park"},
1717 },
1719 RPCExamples{HelpExampleCli("parkblock", "\"blockhash\"") +
1720 HelpExampleRpc("parkblock", "\"blockhash\"")},
1721 [&](const RPCHelpMan &self, const Config &config,
1722 const JSONRPCRequest &request) -> UniValue {
1723 const std::string strHash = request.params[0].get_str();
1724 const BlockHash hash(uint256S(strHash));
1726
1727 NodeContext &node = EnsureAnyNodeContext(request.context);
1729 Chainstate &active_chainstate = chainman.ActiveChainstate();
1730 CBlockIndex *pblockindex = nullptr;
1731 {
1732 LOCK(cs_main);
1733 pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
1734 if (!pblockindex) {
1736 "Block not found");
1737 }
1738
1739 if (active_chainstate.IsBlockAvalancheFinalized(pblockindex)) {
1740 // Reset avalanche finalization if we park a finalized
1741 // block.
1742 active_chainstate.ClearAvalancheFinalizedBlock();
1743 }
1744 }
1745
1746 active_chainstate.ParkBlock(state, pblockindex);
1747
1748 if (state.IsValid()) {
1749 active_chainstate.ActivateBestChain(state, /*pblock=*/nullptr,
1750 node.avalanche.get());
1751 }
1752
1753 if (!state.IsValid()) {
1755 }
1756
1757 // Block to make sure wallet/indexers sync before returning
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
1812
1813 return NullUniValue;
1814 },
1815 };
1816}
1817
1819 return RPCHelpMan{
1820 "unparkblock",
1821 "Removes parked status of a block and its descendants, reconsider "
1822 "them for activation.\n"
1823 "This can be used to undo the effects of parkblock.\n",
1824 {
1826 "the hash of the block to unpark"},
1827 },
1829 RPCExamples{HelpExampleCli("unparkblock", "\"blockhash\"") +
1830 HelpExampleRpc("unparkblock", "\"blockhash\"")},
1831 [&](const RPCHelpMan &self, const Config &config,
1832 const JSONRPCRequest &request) -> UniValue {
1833 const std::string strHash = request.params[0].get_str();
1834 NodeContext &node = EnsureAnyNodeContext(request.context);
1836 const BlockHash hash(uint256S(strHash));
1837 Chainstate &active_chainstate = chainman.ActiveChainstate();
1838
1839 {
1840 LOCK(cs_main);
1841
1842 CBlockIndex *pblockindex =
1843 chainman.m_blockman.LookupBlockIndex(hash);
1844 if (!pblockindex) {
1846 "Block not found");
1847 }
1848
1849 if (!pblockindex->nStatus.isOnParkedChain()) {
1850 // Block to unpark is not parked so there is nothing to do.
1851 return NullUniValue;
1852 }
1853
1854 const CBlockIndex *tip = active_chainstate.m_chain.Tip();
1855 if (tip) {
1856 const CBlockIndex *ancestor =
1857 LastCommonAncestor(tip, pblockindex);
1858 if (active_chainstate.IsBlockAvalancheFinalized(ancestor)) {
1859 // Only reset avalanche finalization if we unpark a
1860 // block that might conflict with avalanche finalized
1861 // blocks.
1862 active_chainstate.ClearAvalancheFinalizedBlock();
1863 }
1864 }
1865
1866 active_chainstate.UnparkBlockAndChildren(pblockindex);
1867 }
1868
1870 active_chainstate.ActivateBestChain(state, /*pblock=*/nullptr,
1871 node.avalanche.get());
1872
1873 if (!state.IsValid()) {
1875 }
1876
1877 // Block to make sure wallet/indexers sync before returning
1879
1880 return NullUniValue;
1881 },
1882 };
1883}
1884
1886 return RPCHelpMan{
1887 "getchaintxstats",
1888 "Compute statistics about the total number and rate of transactions "
1889 "in the chain.\n",
1890 {
1891 {"nblocks", RPCArg::Type::NUM, RPCArg::DefaultHint{"one month"},
1892 "Size of the window in number of blocks"},
1893 {"blockhash", RPCArg::Type::STR_HEX,
1894 RPCArg::DefaultHint{"chain tip"},
1895 "The hash of the block that ends the window."},
1896 },
1897 RPCResult{
1899 "",
1900 "",
1901 {
1903 "The timestamp for the final block in the window, "
1904 "expressed in " +
1906 {RPCResult::Type::NUM, "txcount", /*optional=*/true,
1907 "The total number of transactions in the chain up to "
1908 "that point, if known. It may be unknown when using "
1909 "assumeutxo."},
1910 {RPCResult::Type::STR_HEX, "window_final_block_hash",
1911 "The hash of the final block in the window"},
1912 {RPCResult::Type::NUM, "window_final_block_height",
1913 "The height of the final block in the window."},
1914 {RPCResult::Type::NUM, "window_block_count",
1915 "Size of the window in number of blocks"},
1916 {RPCResult::Type::NUM, "window_interval",
1917 "The elapsed time in the window in seconds. Only "
1918 "returned if \"window_block_count\" is > 0"},
1919 {RPCResult::Type::NUM, "window_tx_count", /*optional=*/true,
1920 "The number of transactions in the window. Only "
1921 "returned if \"window_block_count\" is > 0 and if "
1922 "txcount exists for the start and end of the window."},
1923 {RPCResult::Type::NUM, "txrate", /*optional=*/true,
1924 "The average rate of transactions per second in the "
1925 "window. Only returned if \"window_interval\" is > 0 "
1926 "and if window_tx_count exists."},
1927 }},
1928 RPCExamples{HelpExampleCli("getchaintxstats", "") +
1929 HelpExampleRpc("getchaintxstats", "2016")},
1930 [&](const RPCHelpMan &self, const Config &config,
1931 const JSONRPCRequest &request) -> UniValue {
1932 ChainstateManager &chainman = EnsureAnyChainman(request.context);
1933 const CBlockIndex *pindex;
1934
1935 // By default: 1 month
1936 int blockcount =
1937 30 * 24 * 60 * 60 /
1938 config.GetChainParams().GetConsensus().nPowTargetSpacing;
1939
1940 if (request.params[1].isNull()) {
1941 LOCK(cs_main);
1942 pindex = chainman.ActiveTip();
1943 } else {
1944 BlockHash hash(ParseHashV(request.params[1], "blockhash"));
1945 LOCK(cs_main);
1946 pindex = chainman.m_blockman.LookupBlockIndex(hash);
1947 if (!pindex) {
1949 "Block not found");
1950 }
1951 if (!chainman.ActiveChain().Contains(pindex)) {
1953 "Block is not in main chain");
1954 }
1955 }
1956
1957 CHECK_NONFATAL(pindex != nullptr);
1958
1959 if (request.params[0].isNull()) {
1960 blockcount =
1961 std::max(0, std::min(blockcount, pindex->nHeight - 1));
1962 } else {
1963 blockcount = request.params[0].getInt<int>();
1964
1965 if (blockcount < 0 ||
1966 (blockcount > 0 && blockcount >= pindex->nHeight)) {
1968 "Invalid block count: "
1969 "should be between 0 and "
1970 "the block's height - 1");
1971 }
1972 }
1973
1974 const CBlockIndex &past_block{*CHECK_NONFATAL(
1975 pindex->GetAncestor(pindex->nHeight - blockcount))};
1976 const int64_t nTimeDiff{pindex->GetMedianTimePast() -
1977 past_block.GetMedianTimePast()};
1978
1980 ret.pushKV("time", pindex->GetBlockTime());
1981 if (pindex->nChainTx) {
1982 ret.pushKV("txcount", pindex->nChainTx);
1983 }
1984 ret.pushKV("window_final_block_hash",
1985 pindex->GetBlockHash().GetHex());
1986 ret.pushKV("window_final_block_height", pindex->nHeight);
1987 ret.pushKV("window_block_count", blockcount);
1988 if (blockcount > 0) {
1989 ret.pushKV("window_interval", nTimeDiff);
1990 if (pindex->nChainTx != 0 && past_block.nChainTx != 0) {
1991 unsigned int window_tx_count =
1992 pindex->nChainTx - past_block.nChainTx;
1993 ret.pushKV("window_tx_count", window_tx_count);
1994 if (nTimeDiff > 0) {
1995 ret.pushKV("txrate",
1996 double(window_tx_count) / nTimeDiff);
1997 }
1998 }
1999 }
2000
2001 return ret;
2002 },
2003 };
2004}
2005
2006template <typename T>
2007static T CalculateTruncatedMedian(std::vector<T> &scores) {
2008 size_t size = scores.size();
2009 if (size == 0) {
2010 return T();
2011 }
2012
2013 std::sort(scores.begin(), scores.end());
2014 if (size % 2 == 0) {
2015 return (scores[size / 2 - 1] + scores[size / 2]) / 2;
2016 } else {
2017 return scores[size / 2];
2018 }
2019}
2020
2021template <typename T> static inline bool SetHasKeys(const std::set<T> &set) {
2022 return false;
2023}
2024template <typename T, typename Tk, typename... Args>
2025static inline bool SetHasKeys(const std::set<T> &set, const Tk &key,
2026 const Args &...args) {
2027 return (set.count(key) != 0) || SetHasKeys(set, args...);
2028}
2029
2030// outpoint (needed for the utxo index) + nHeight + fCoinBase
2031static constexpr size_t PER_UTXO_OVERHEAD =
2032 sizeof(COutPoint) + sizeof(uint32_t) + sizeof(bool);
2033
2035 const auto &ticker = Currency::get().ticker;
2036 return RPCHelpMan{
2037 "getblockstats",
2038 "Compute per block statistics for a given window. All amounts are "
2039 "in " +
2040 ticker +
2041 ".\n"
2042 "It won't work for some heights with pruning.\n",
2043 {
2044 {"hash_or_height", RPCArg::Type::NUM, RPCArg::Optional::NO,
2045 "The block hash or height of the target block",
2047 .type_str = {"", "string or numeric"}}},
2048 {"stats",
2050 RPCArg::DefaultHint{"all values"},
2051 "Values to plot (see result below)",
2052 {
2054 "Selected statistic"},
2056 "Selected statistic"},
2057 },
2059 },
2060 RPCResult{
2062 "",
2063 "",
2064 {
2065 {RPCResult::Type::NUM, "avgfee", "Average fee in the block"},
2066 {RPCResult::Type::NUM, "avgfeerate",
2067 "Average feerate (in satoshis per virtual byte)"},
2068 {RPCResult::Type::NUM, "avgtxsize", "Average transaction size"},
2069 {RPCResult::Type::STR_HEX, "blockhash",
2070 "The block hash (to check for potential reorgs)"},
2071 {RPCResult::Type::NUM, "height", "The height of the block"},
2072 {RPCResult::Type::NUM, "ins",
2073 "The number of inputs (excluding coinbase)"},
2074 {RPCResult::Type::NUM, "maxfee", "Maximum fee in the block"},
2075 {RPCResult::Type::NUM, "maxfeerate",
2076 "Maximum feerate (in satoshis per virtual byte)"},
2077 {RPCResult::Type::NUM, "maxtxsize", "Maximum transaction size"},
2078 {RPCResult::Type::NUM, "medianfee",
2079 "Truncated median fee in the block"},
2080 {RPCResult::Type::NUM, "medianfeerate",
2081 "Truncated median feerate (in " + ticker + " per byte)"},
2082 {RPCResult::Type::NUM, "mediantime",
2083 "The block median time past"},
2084 {RPCResult::Type::NUM, "mediantxsize",
2085 "Truncated median transaction size"},
2086 {RPCResult::Type::NUM, "minfee", "Minimum fee in the block"},
2087 {RPCResult::Type::NUM, "minfeerate",
2088 "Minimum feerate (in satoshis per virtual byte)"},
2089 {RPCResult::Type::NUM, "mintxsize", "Minimum transaction size"},
2090 {RPCResult::Type::NUM, "outs", "The number of outputs"},
2091 {RPCResult::Type::NUM, "subsidy", "The block subsidy"},
2092 {RPCResult::Type::NUM, "time", "The block time"},
2093 {RPCResult::Type::NUM, "total_out",
2094 "Total amount in all outputs (excluding coinbase and thus "
2095 "reward [ie subsidy + totalfee])"},
2096 {RPCResult::Type::NUM, "total_size",
2097 "Total size of all non-coinbase transactions"},
2098 {RPCResult::Type::NUM, "totalfee", "The fee total"},
2099 {RPCResult::Type::NUM, "txs",
2100 "The number of transactions (including coinbase)"},
2101 {RPCResult::Type::NUM, "utxo_increase",
2102 "The increase/decrease in the number of unspent outputs"},
2103 {RPCResult::Type::NUM, "utxo_size_inc",
2104 "The increase/decrease in size for the utxo index (not "
2105 "discounting op_return and similar)"},
2106 }},
2109 "getblockstats",
2110 R"('"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"' '["minfeerate","avgfeerate"]')") +
2111 HelpExampleCli("getblockstats",
2112 R"(1000 '["minfeerate","avgfeerate"]')") +
2114 "getblockstats",
2115 R"("00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09", ["minfeerate","avgfeerate"])") +
2116 HelpExampleRpc("getblockstats",
2117 R"(1000, ["minfeerate","avgfeerate"])")},
2118 [&](const RPCHelpMan &self, const Config &config,
2119 const JSONRPCRequest &request) -> UniValue {
2120 ChainstateManager &chainman = EnsureAnyChainman(request.context);
2121 const CBlockIndex &pindex{*CHECK_NONFATAL(
2122 ParseHashOrHeight(request.params[0], chainman))};
2123
2124 std::set<std::string> stats;
2125 if (!request.params[1].isNull()) {
2126 const UniValue stats_univalue = request.params[1].get_array();
2127 for (unsigned int i = 0; i < stats_univalue.size(); i++) {
2128 const std::string stat = stats_univalue[i].get_str();
2129 stats.insert(stat);
2130 }
2131 }
2132
2133 const CBlock &block = GetBlockChecked(chainman.m_blockman, pindex);
2134 const CBlockUndo &blockUndo =
2135 GetUndoChecked(chainman.m_blockman, pindex);
2136
2137 // Calculate everything if nothing selected (default)
2138 const bool do_all = stats.size() == 0;
2139 const bool do_mediantxsize =
2140 do_all || stats.count("mediantxsize") != 0;
2141 const bool do_medianfee = do_all || stats.count("medianfee") != 0;
2142 const bool do_medianfeerate =
2143 do_all || stats.count("medianfeerate") != 0;
2144 const bool loop_inputs =
2145 do_all || do_medianfee || do_medianfeerate ||
2146 SetHasKeys(stats, "utxo_size_inc", "totalfee", "avgfee",
2147 "avgfeerate", "minfee", "maxfee", "minfeerate",
2148 "maxfeerate");
2149 const bool loop_outputs =
2150 do_all || loop_inputs || stats.count("total_out");
2151 const bool do_calculate_size =
2152 do_mediantxsize || loop_inputs ||
2153 SetHasKeys(stats, "total_size", "avgtxsize", "mintxsize",
2154 "maxtxsize");
2155
2156 const int64_t blockMaxSize = config.GetMaxBlockSize();
2157 Amount maxfee = Amount::zero();
2158 Amount maxfeerate = Amount::zero();
2159 Amount minfee = MAX_MONEY;
2160 Amount minfeerate = MAX_MONEY;
2161 Amount total_out = Amount::zero();
2162 Amount totalfee = Amount::zero();
2163 int64_t inputs = 0;
2164 int64_t maxtxsize = 0;
2165 int64_t mintxsize = blockMaxSize;
2166 int64_t outputs = 0;
2167 int64_t total_size = 0;
2168 int64_t utxo_size_inc = 0;
2169 std::vector<Amount> fee_array;
2170 std::vector<Amount> feerate_array;
2171 std::vector<int64_t> txsize_array;
2172
2173 for (size_t i = 0; i < block.vtx.size(); ++i) {
2174 const auto &tx = block.vtx.at(i);
2175 outputs += tx->vout.size();
2176 Amount tx_total_out = Amount::zero();
2177 if (loop_outputs) {
2178 for (const CTxOut &out : tx->vout) {
2179 tx_total_out += out.nValue;
2180 utxo_size_inc +=
2182 }
2183 }
2184
2185 if (tx->IsCoinBase()) {
2186 continue;
2187 }
2188
2189 // Don't count coinbase's fake input
2190 inputs += tx->vin.size();
2191 // Don't count coinbase reward
2192 total_out += tx_total_out;
2193
2194 int64_t tx_size = 0;
2195 if (do_calculate_size) {
2196 tx_size = tx->GetTotalSize();
2197 if (do_mediantxsize) {
2198 txsize_array.push_back(tx_size);
2199 }
2200 maxtxsize = std::max(maxtxsize, tx_size);
2201 mintxsize = std::min(mintxsize, tx_size);
2202 total_size += tx_size;
2203 }
2204
2205 if (loop_inputs) {
2206 Amount tx_total_in = Amount::zero();
2207 const auto &txundo = blockUndo.vtxundo.at(i - 1);
2208 for (const Coin &coin : txundo.vprevout) {
2209 const CTxOut &prevoutput = coin.GetTxOut();
2210
2211 tx_total_in += prevoutput.nValue;
2212 utxo_size_inc -=
2213 GetSerializeSize(prevoutput) + PER_UTXO_OVERHEAD;
2214 }
2215
2216 Amount txfee = tx_total_in - tx_total_out;
2217 CHECK_NONFATAL(MoneyRange(txfee));
2218 if (do_medianfee) {
2219 fee_array.push_back(txfee);
2220 }
2221 maxfee = std::max(maxfee, txfee);
2222 minfee = std::min(minfee, txfee);
2223 totalfee += txfee;
2224
2225 Amount feerate = txfee / tx_size;
2226 if (do_medianfeerate) {
2227 feerate_array.push_back(feerate);
2228 }
2229 maxfeerate = std::max(maxfeerate, feerate);
2230 minfeerate = std::min(minfeerate, feerate);
2231 }
2232 }
2233
2234 UniValue ret_all(UniValue::VOBJ);
2235 ret_all.pushKV("avgfee",
2236 block.vtx.size() > 1
2237 ? (totalfee / int((block.vtx.size() - 1)))
2238 : Amount::zero());
2239 ret_all.pushKV("avgfeerate", total_size > 0
2240 ? (totalfee / total_size)
2241 : Amount::zero());
2242 ret_all.pushKV("avgtxsize",
2243 (block.vtx.size() > 1)
2244 ? total_size / (block.vtx.size() - 1)
2245 : 0);
2246 ret_all.pushKV("blockhash", pindex.GetBlockHash().GetHex());
2247 ret_all.pushKV("height", (int64_t)pindex.nHeight);
2248 ret_all.pushKV("ins", inputs);
2249 ret_all.pushKV("maxfee", maxfee);
2250 ret_all.pushKV("maxfeerate", maxfeerate);
2251 ret_all.pushKV("maxtxsize", maxtxsize);
2252 ret_all.pushKV("medianfee", CalculateTruncatedMedian(fee_array));
2253 ret_all.pushKV("medianfeerate",
2254 CalculateTruncatedMedian(feerate_array));
2255 ret_all.pushKV("mediantime", pindex.GetMedianTimePast());
2256 ret_all.pushKV("mediantxsize",
2257 CalculateTruncatedMedian(txsize_array));
2258 ret_all.pushKV("minfee",
2259 minfee == MAX_MONEY ? Amount::zero() : minfee);
2260 ret_all.pushKV("minfeerate", minfeerate == MAX_MONEY
2261 ? Amount::zero()
2262 : minfeerate);
2263 ret_all.pushKV("mintxsize",
2264 mintxsize == blockMaxSize ? 0 : mintxsize);
2265 ret_all.pushKV("outs", outputs);
2266 ret_all.pushKV("subsidy", GetBlockSubsidy(pindex.nHeight,
2267 chainman.GetConsensus()));
2268 ret_all.pushKV("time", pindex.GetBlockTime());
2269 ret_all.pushKV("total_out", total_out);
2270 ret_all.pushKV("total_size", total_size);
2271 ret_all.pushKV("totalfee", totalfee);
2272 ret_all.pushKV("txs", (int64_t)block.vtx.size());
2273 ret_all.pushKV("utxo_increase", outputs - inputs);
2274 ret_all.pushKV("utxo_size_inc", utxo_size_inc);
2275
2276 if (do_all) {
2277 return ret_all;
2278 }
2279
2281 for (const std::string &stat : stats) {
2282 const UniValue &value = ret_all[stat];
2283 if (value.isNull()) {
2284 throw JSONRPCError(
2286 strprintf("Invalid selected statistic %s", stat));
2287 }
2288 ret.pushKV(stat, value);
2289 }
2290 return ret;
2291 },
2292 };
2293}
2294
2295namespace {
2297static bool FindScriptPubKey(std::atomic<int> &scan_progress,
2298 const std::atomic<bool> &should_abort,
2299 int64_t &count, CCoinsViewCursor *cursor,
2300 const std::set<CScript> &needles,
2301 std::map<COutPoint, Coin> &out_results,
2302 std::function<void()> &interruption_point) {
2303 scan_progress = 0;
2304 count = 0;
2305 while (cursor->Valid()) {
2306 COutPoint key;
2307 Coin coin;
2308 if (!cursor->GetKey(key) || !cursor->GetValue(coin)) {
2309 return false;
2310 }
2311 if (++count % 8192 == 0) {
2312 interruption_point();
2313 if (should_abort) {
2314 // allow to abort the scan via the abort reference
2315 return false;
2316 }
2317 }
2318 if (count % 256 == 0) {
2319 // update progress reference every 256 item
2320 const TxId &txid = key.GetTxId();
2321 uint32_t high = 0x100 * *txid.begin() + *(txid.begin() + 1);
2322 scan_progress = int(high * 100.0 / 65536.0 + 0.5);
2323 }
2324 if (needles.count(coin.GetTxOut().scriptPubKey)) {
2325 out_results.emplace(key, coin);
2326 }
2327 cursor->Next();
2328 }
2329 scan_progress = 100;
2330 return true;
2331}
2332} // namespace
2333
2335static std::atomic<int> g_scan_progress;
2336static std::atomic<bool> g_scan_in_progress;
2337static std::atomic<bool> g_should_abort_scan;
2339private:
2340 bool m_could_reserve{false};
2341
2342public:
2343 explicit CoinsViewScanReserver() = default;
2344
2345 bool reserve() {
2347 if (g_scan_in_progress.exchange(true)) {
2348 return false;
2349 }
2350 m_could_reserve = true;
2351 return true;
2352 }
2353
2355 if (m_could_reserve) {
2356 g_scan_in_progress = false;
2357 }
2358 }
2359};
2360
2362 const auto &ticker = Currency::get().ticker;
2363 return RPCHelpMan{
2364 "scantxoutset",
2365 "Scans the unspent transaction output set for entries that match "
2366 "certain output descriptors.\n"
2367 "Examples of output descriptors are:\n"
2368 " addr(<address>) Outputs whose scriptPubKey "
2369 "corresponds to the specified address (does not include P2PK)\n"
2370 " raw(<hex script>) Outputs whose scriptPubKey "
2371 "equals the specified hex scripts\n"
2372 " combo(<pubkey>) P2PK and P2PKH outputs for "
2373 "the given pubkey\n"
2374 " pkh(<pubkey>) P2PKH outputs for the given "
2375 "pubkey\n"
2376 " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for "
2377 "the given threshold and pubkeys\n"
2378 "\nIn the above, <pubkey> either refers to a fixed public key in "
2379 "hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
2380 "or more path elements separated by \"/\", and optionally ending in "
2381 "\"/*\" (unhardened), or \"/*'\" or \"/*h\" (hardened) to specify all\n"
2382 "unhardened or hardened child keys.\n"
2383 "In the latter case, a range needs to be specified by below if "
2384 "different from 1000.\n"
2385 "For more information on output descriptors, see the documentation in "
2386 "the doc/descriptors.md file.\n",
2387 {
2389 "The action to execute\n"
2390 " \"start\" for starting a "
2391 "scan\n"
2392 " \"abort\" for aborting the "
2393 "current scan (returns true when abort was successful)\n"
2394 " \"status\" for "
2395 "progress report (in %) of the current scan"},
2396 {"scanobjects",
2399 "Array of scan objects. Required for \"start\" action\n"
2400 " Every scan object is either a "
2401 "string descriptor or an object:",
2402 {
2404 "An output descriptor"},
2405 {
2406 "",
2409 "An object with output descriptor and metadata",
2410 {
2412 "An output descriptor"},
2413 {"range", RPCArg::Type::RANGE, RPCArg::Default{1000},
2414 "The range of HD chain indexes to explore (either "
2415 "end or [begin,end])"},
2416 },
2417 },
2418 },
2419 RPCArgOptions{.oneline_description = "[scanobjects,...]"}},
2420 },
2421 {
2422 RPCResult{"When action=='abort'", RPCResult::Type::BOOL, "", ""},
2423 RPCResult{"When action=='status' and no scan is in progress",
2424 RPCResult::Type::NONE, "", ""},
2425 RPCResult{
2426 "When action=='status' and scan is in progress",
2428 "",
2429 "",
2430 {
2431 {RPCResult::Type::NUM, "progress", "The scan progress"},
2432 }},
2433 RPCResult{
2434 "When action=='start'",
2436 "",
2437 "",
2438 {
2439 {RPCResult::Type::BOOL, "success",
2440 "Whether the scan was completed"},
2441 {RPCResult::Type::NUM, "txouts",
2442 "The number of unspent transaction outputs scanned"},
2443 {RPCResult::Type::NUM, "height",
2444 "The current block height (index)"},
2445 {RPCResult::Type::STR_HEX, "bestblock",
2446 "The hash of the block at the tip of the chain"},
2448 "unspents",
2449 "",
2450 {
2452 "",
2453 "",
2454 {
2455 {RPCResult::Type::STR_HEX, "txid",
2456 "The transaction id"},
2457 {RPCResult::Type::NUM, "vout", "The vout value"},
2458 {RPCResult::Type::STR_HEX, "scriptPubKey",
2459 "The script key"},
2460 {RPCResult::Type::STR, "desc",
2461 "A specialized descriptor for the matched "
2462 "scriptPubKey"},
2463 {RPCResult::Type::STR_AMOUNT, "amount",
2464 "The total amount in " + ticker +
2465 " of the unspent output"},
2466 {RPCResult::Type::BOOL, "coinbase",
2467 "Whether this is a coinbase output"},
2468 {RPCResult::Type::NUM, "height",
2469 "Height of the unspent transaction output"},
2470 }},
2471 }},
2472 {RPCResult::Type::STR_AMOUNT, "total_amount",
2473 "The total amount of all found unspent outputs in " +
2474 ticker},
2475 }},
2476 },
2477 RPCExamples{""},
2478 [&](const RPCHelpMan &self, const Config &config,
2479 const JSONRPCRequest &request) -> UniValue {
2480 UniValue result(UniValue::VOBJ);
2481 const auto action{self.Arg<std::string>("action")};
2482 if (action == "status") {
2483 CoinsViewScanReserver reserver;
2484 if (reserver.reserve()) {
2485 // no scan in progress
2486 return NullUniValue;
2487 }
2488 result.pushKV("progress", g_scan_progress.load());
2489 return result;
2490 } else if (action == "abort") {
2491 CoinsViewScanReserver reserver;
2492 if (reserver.reserve()) {
2493 // reserve was possible which means no scan was running
2494 return false;
2495 }
2496 // set the abort flag
2497 g_should_abort_scan = true;
2498 return true;
2499 } else if (action == "start") {
2500 CoinsViewScanReserver reserver;
2501 if (!reserver.reserve()) {
2503 "Scan already in progress, use action "
2504 "\"abort\" or \"status\"");
2505 }
2506
2507 if (request.params.size() < 2) {
2509 "scanobjects argument is required for "
2510 "the start action");
2511 }
2512
2513 std::set<CScript> needles;
2514 std::map<CScript, std::string> descriptors;
2515 Amount total_in = Amount::zero();
2516
2517 // loop through the scan objects
2518 for (const UniValue &scanobject :
2519 request.params[1].get_array().getValues()) {
2520 FlatSigningProvider provider;
2521 auto scripts =
2522 EvalDescriptorStringOrObject(scanobject, provider);
2523 for (CScript &script : scripts) {
2524 std::string inferred =
2525 InferDescriptor(script, provider)->ToString();
2526 needles.emplace(script);
2527 descriptors.emplace(std::move(script),
2528 std::move(inferred));
2529 }
2530 }
2531
2532 // Scan the unspent transaction output set for inputs
2533 UniValue unspents(UniValue::VARR);
2534 std::vector<CTxOut> input_txos;
2535 std::map<COutPoint, Coin> coins;
2536 g_should_abort_scan = false;
2537 g_scan_progress = 0;
2538 int64_t count = 0;
2539 std::unique_ptr<CCoinsViewCursor> pcursor;
2540 const CBlockIndex *tip;
2541 NodeContext &node = EnsureAnyNodeContext(request.context);
2542 {
2544 LOCK(cs_main);
2545 Chainstate &active_chainstate = chainman.ActiveChainstate();
2546 active_chainstate.ForceFlushStateToDisk();
2547 pcursor = CHECK_NONFATAL(std::unique_ptr<CCoinsViewCursor>(
2548 active_chainstate.CoinsDB().Cursor()));
2549 tip = CHECK_NONFATAL(active_chainstate.m_chain.Tip());
2550 }
2551 bool res = FindScriptPubKey(
2552 g_scan_progress, g_should_abort_scan, count, pcursor.get(),
2553 needles, coins, node.rpc_interruption_point);
2554 result.pushKV("success", res);
2555 result.pushKV("txouts", count);
2556 result.pushKV("height", tip->nHeight);
2557 result.pushKV("bestblock", tip->GetBlockHash().GetHex());
2558
2559 for (const auto &it : coins) {
2560 const COutPoint &outpoint = it.first;
2561 const Coin &coin = it.second;
2562 const CTxOut &txo = coin.GetTxOut();
2563 input_txos.push_back(txo);
2564 total_in += txo.nValue;
2565
2566 UniValue unspent(UniValue::VOBJ);
2567 unspent.pushKV("txid", outpoint.GetTxId().GetHex());
2568 unspent.pushKV("vout", int32_t(outpoint.GetN()));
2569 unspent.pushKV("scriptPubKey", HexStr(txo.scriptPubKey));
2570 unspent.pushKV("desc", descriptors[txo.scriptPubKey]);
2571 unspent.pushKV("amount", txo.nValue);
2572 unspent.pushKV("coinbase", coin.IsCoinBase());
2573 unspent.pushKV("height", int32_t(coin.GetHeight()));
2574
2575 unspents.push_back(std::move(unspent));
2576 }
2577 result.pushKV("unspents", std::move(unspents));
2578 result.pushKV("total_amount", total_in);
2579 } else {
2581 strprintf("Invalid action '%s'", action));
2582 }
2583 return result;
2584 },
2585 };
2586}
2587
2589 return RPCHelpMan{
2590 "getblockfilter",
2591 "Retrieve a BIP 157 content filter for a particular block.\n",
2592 {
2594 "The hash of the block"},
2595 {"filtertype", RPCArg::Type::STR, RPCArg::Default{"basic"},
2596 "The type name of the filter"},
2597 },
2599 "",
2600 "",
2601 {
2602 {RPCResult::Type::STR_HEX, "filter",
2603 "the hex-encoded filter data"},
2604 {RPCResult::Type::STR_HEX, "header",
2605 "the hex-encoded filter header"},
2606 }},
2608 HelpExampleCli("getblockfilter",
2609 "\"00000000c937983704a73af28acdec37b049d214a"
2610 "dbda81d7e2a3dd146f6ed09\" \"basic\"") +
2611 HelpExampleRpc("getblockfilter",
2612 "\"00000000c937983704a73af28acdec37b049d214adbda81d7"
2613 "e2a3dd146f6ed09\", \"basic\"")},
2614 [&](const RPCHelpMan &self, const Config &config,
2615 const JSONRPCRequest &request) -> UniValue {
2616 const BlockHash block_hash(
2617 ParseHashV(request.params[0], "blockhash"));
2618 std::string filtertype_name = "basic";
2619 if (!request.params[1].isNull()) {
2620 filtertype_name = request.params[1].get_str();
2621 }
2622
2623 BlockFilterType filtertype;
2624 if (!BlockFilterTypeByName(filtertype_name, filtertype)) {
2626 "Unknown filtertype");
2627 }
2628
2629 BlockFilterIndex *index = GetBlockFilterIndex(filtertype);
2630 if (!index) {
2632 "Index is not enabled for filtertype " +
2633 filtertype_name);
2634 }
2635
2636 const CBlockIndex *block_index;
2637 bool block_was_connected;
2638 {
2639 ChainstateManager &chainman =
2640 EnsureAnyChainman(request.context);
2641 LOCK(cs_main);
2642 block_index = chainman.m_blockman.LookupBlockIndex(block_hash);
2643 if (!block_index) {
2645 "Block not found");
2646 }
2647 block_was_connected =
2648 block_index->IsValid(BlockValidity::SCRIPTS);
2649 }
2650
2651 bool index_ready = index->BlockUntilSyncedToCurrentChain();
2652
2653 BlockFilter filter;
2654 uint256 filter_header;
2655 if (!index->LookupFilter(block_index, filter) ||
2656 !index->LookupFilterHeader(block_index, filter_header)) {
2657 int err_code;
2658 std::string errmsg = "Filter not found.";
2659
2660 if (!block_was_connected) {
2661 err_code = RPC_INVALID_ADDRESS_OR_KEY;
2662 errmsg += " Block was not connected to active chain.";
2663 } else if (!index_ready) {
2664 err_code = RPC_MISC_ERROR;
2665 errmsg += " Block filters are still in the process of "
2666 "being indexed.";
2667 } else {
2668 err_code = RPC_INTERNAL_ERROR;
2669 errmsg += " This error is unexpected and indicates index "
2670 "corruption.";
2671 }
2672
2673 throw JSONRPCError(err_code, errmsg);
2674 }
2675
2677 ret.pushKV("filter", HexStr(filter.GetEncodedFilter()));
2678 ret.pushKV("header", filter_header.GetHex());
2679 return ret;
2680 },
2681 };
2682}
2683
2690
2691public:
2692 NetworkDisable(CConnman &connman) : m_connman(connman) {
2696 "Network activity could not be suspended.");
2697 }
2698 };
2700};
2701
2710
2711public:
2714 const CBlockIndex &index)
2715 : m_chainman(chainman), m_avalanche(avalanche),
2716 m_invalidate_index(index) {
2719 };
2723 };
2724};
2725
2732 return RPCHelpMan{
2733 "dumptxoutset",
2734 "Write the serialized UTXO set to a file. This can be used in "
2735 "loadtxoutset afterwards if this snapshot height is supported in the "
2736 "chainparams as well.\n\n"
2737 "Unless the the \"latest\" type is requested, the node will roll back "
2738 "to the requested height and network activity will be suspended during "
2739 "this process. "
2740 "Because of this it is discouraged to interact with the node in any "
2741 "other way during the execution of this call to avoid inconsistent "
2742 "results and race conditions, particularly RPCs that interact with "
2743 "blockstorage.\n\n"
2744 "This call may take several minutes. Make sure to use no RPC timeout "
2745 "(bitcoin-cli -rpcclienttimeout=0)",
2746
2747 {
2749 "path to the output file. If relative, will be prefixed by "
2750 "datadir."},
2751 {"type", RPCArg::Type::STR, RPCArg::Default(""),
2752 "The type of snapshot to create. Can be \"latest\" to create a "
2753 "snapshot of the current UTXO set or \"rollback\" to temporarily "
2754 "roll back the state of the node to a historical block before "
2755 "creating the snapshot of a historical UTXO set. This parameter "
2756 "can be omitted if a separate \"rollback\" named parameter is "
2757 "specified indicating the height or hash of a specific historical "
2758 "block. If \"rollback\" is specified and separate \"rollback\" "
2759 "named parameter is not specified, this will roll back to the "
2760 "latest valid snapshot block that can currently be loaded with "
2761 "loadtxoutset."},
2762 {
2763 "options",
2766 "",
2767 {
2769 "Height or hash of the block to roll back to before "
2770 "creating the snapshot. Note: The further this number is "
2771 "from the tip, the longer this process will take. "
2772 "Consider setting a higher -rpcclienttimeout value in "
2773 "this case.",
2775 .type_str = {"", "string or numeric"}}},
2776 },
2777 },
2778 },
2780 "",
2781 "",
2782 {
2783 {RPCResult::Type::NUM, "coins_written",
2784 "the number of coins written in the snapshot"},
2785 {RPCResult::Type::STR_HEX, "base_hash",
2786 "the hash of the base of the snapshot"},
2787 {RPCResult::Type::NUM, "base_height",
2788 "the height of the base of the snapshot"},
2789 {RPCResult::Type::STR, "path",
2790 "the absolute path that the snapshot was written to"},
2791 {RPCResult::Type::STR_HEX, "txoutset_hash",
2792 "the hash of the UTXO set contents"},
2793 {RPCResult::Type::NUM, "nchaintx",
2794 "the number of transactions in the chain up to and "
2795 "including the base block"},
2796 }},
2797 RPCExamples{HelpExampleCli("-rpcclienttimeout=0 dumptxoutset",
2798 "utxo.dat latest") +
2799 HelpExampleCli("-rpcclienttimeout=0 dumptxoutset",
2800 "utxo.dat rollback") +
2801 HelpExampleCli("-rpcclienttimeout=0 -named dumptxoutset",
2802 R"(utxo.dat rollback=853456)")},
2803 [&](const RPCHelpMan &self, const Config &config,
2804 const JSONRPCRequest &request) -> UniValue {
2805 NodeContext &node = EnsureAnyNodeContext(request.context);
2806 const CBlockIndex *tip{WITH_LOCK(
2807 ::cs_main, return node.chainman->ActiveChain().Tip())};
2808 const CBlockIndex *target_index{nullptr};
2809 const std::string snapshot_type{self.Arg<std::string>("type")};
2810 const UniValue options{request.params[2].isNull()
2812 : request.params[2]};
2813 if (options.exists("rollback")) {
2814 if (!snapshot_type.empty() && snapshot_type != "rollback") {
2815 throw JSONRPCError(
2817 strprintf("Invalid snapshot type \"%s\" specified with "
2818 "rollback option",
2819 snapshot_type));
2820 }
2821 target_index =
2822 ParseHashOrHeight(options["rollback"], *node.chainman);
2823 } else if (snapshot_type == "rollback") {
2824 auto snapshot_heights =
2825 node.chainman->GetParams().GetAvailableSnapshotHeights();
2826 CHECK_NONFATAL(snapshot_heights.size() > 0);
2827 auto max_height = std::max_element(snapshot_heights.begin(),
2828 snapshot_heights.end());
2829 target_index = ParseHashOrHeight(*max_height, *node.chainman);
2830 } else if (snapshot_type == "latest") {
2831 target_index = tip;
2832 } else {
2833 throw JSONRPCError(
2835 strprintf("Invalid snapshot type \"%s\" specified. Please "
2836 "specify \"rollback\" or \"latest\"",
2837 snapshot_type));
2838 }
2839
2840 const ArgsManager &args{EnsureAnyArgsman(request.context)};
2841 const fs::path path = fsbridge::AbsPathJoin(
2842 args.GetDataDirNet(), fs::u8path(request.params[0].get_str()));
2843 // Write to a temporary path and then move into `path` on completion
2844 // to avoid confusion due to an interruption.
2845 const fs::path temppath = fsbridge::AbsPathJoin(
2846 args.GetDataDirNet(),
2847 fs::u8path(request.params[0].get_str() + ".incomplete"));
2848
2849 if (fs::exists(path)) {
2851 path.u8string() +
2852 " already exists. If you are sure this "
2853 "is what you want, "
2854 "move it out of the way first");
2855 }
2856
2857 FILE *file{fsbridge::fopen(temppath, "wb")};
2858 AutoFile afile{file};
2859
2860 CConnman &connman = EnsureConnman(node);
2861 const CBlockIndex *invalidate_index{nullptr};
2862 std::optional<NetworkDisable> disable_network;
2863 std::optional<TemporaryRollback> temporary_rollback;
2864
2865 // If the user wants to dump the txoutset of the current tip, we
2866 // don't have to roll back at all
2867 if (target_index != tip) {
2868 // If the node is running in pruned mode we ensure all necessary
2869 // block data is available before starting to roll back.
2870 if (node.chainman->m_blockman.IsPruneMode()) {
2871 LOCK(node.chainman->GetMutex());
2872 const CBlockIndex *current_tip{
2873 node.chainman->ActiveChain().Tip()};
2874 const CBlockIndex *first_block{
2875 node.chainman->m_blockman.GetFirstBlock(
2876 *current_tip,
2877 /*status_test=*/[](const BlockStatus &status) {
2878 return status.hasData() && status.hasUndo();
2879 })};
2880 if (first_block->nHeight > target_index->nHeight) {
2881 throw JSONRPCError(
2883 "Could not roll back to requested height since "
2884 "necessary block data is already pruned.");
2885 }
2886 }
2887
2888 // Suspend network activity for the duration of the process when
2889 // we are rolling back the chain to get a utxo set from a past
2890 // height. We do this so we don't punish peers that send us that
2891 // send us data that seems wrong in this temporary state. For
2892 // example a normal new block would be classified as a block
2893 // connecting an invalid block.
2894 // Skip if the network is already disabled because this
2895 // automatically re-enables the network activity at the end of
2896 // the process which may not be what the user wants.
2897 if (connman.GetNetworkActive()) {
2898 disable_network.emplace(connman);
2899 }
2900
2901 invalidate_index = WITH_LOCK(
2902 ::cs_main,
2903 return node.chainman->ActiveChain().Next(target_index));
2904 temporary_rollback.emplace(*node.chainman, node.avalanche.get(),
2905 *invalidate_index);
2906 }
2907
2908 Chainstate *chainstate;
2909 std::unique_ptr<CCoinsViewCursor> cursor;
2910 CCoinsStats stats;
2911 {
2912 // Lock the chainstate before calling PrepareUtxoSnapshot, to
2913 // be able to get a UTXO database cursor while the chain is
2914 // pointing at the target block. After that, release the lock
2915 // while calling WriteUTXOSnapshot. The cursor will remain
2916 // valid and be used by WriteUTXOSnapshot to write a consistent
2917 // snapshot even if the chainstate changes.
2918 LOCK(node.chainman->GetMutex());
2919 chainstate = &node.chainman->ActiveChainstate();
2920
2921 // In case there is any issue with a block being read from disk
2922 // we need to stop here, otherwise the dump could still be
2923 // created for the wrong height. The new tip could also not be
2924 // the target block if we have a stale sister block of
2925 // invalidate_index. This block (or a descendant) would be
2926 // activated as the new tip and we would not get to
2927 // new_tip_index.
2928 if (target_index != chainstate->m_chain.Tip()) {
2930 "Failed to roll back to requested height, "
2931 "reverting to tip.\n");
2932 throw JSONRPCError(
2934 "Could not roll back to requested height.");
2935 } else {
2936 std::tie(cursor, stats, tip) = PrepareUTXOSnapshot(
2937 *chainstate, node.rpc_interruption_point);
2938 }
2939 }
2940
2941 UniValue result =
2942 WriteUTXOSnapshot(*chainstate, cursor.get(), &stats, tip, afile,
2943 path, temppath, node.rpc_interruption_point);
2944 fs::rename(temppath, path);
2945
2946 return result;
2947 },
2948 };
2949}
2950
2951std::tuple<std::unique_ptr<CCoinsViewCursor>, CCoinsStats, const CBlockIndex *>
2953 const std::function<void()> &interruption_point) {
2954 std::unique_ptr<CCoinsViewCursor> pcursor;
2955 std::optional<CCoinsStats> maybe_stats;
2956 const CBlockIndex *tip;
2957
2958 {
2959 // We need to lock cs_main to ensure that the coinsdb isn't
2960 // written to between (i) flushing coins cache to disk
2961 // (coinsdb), (ii) getting stats based upon the coinsdb, and
2962 // (iii) constructing a cursor to the coinsdb for use in
2963 // WriteUTXOSnapshot.
2964 //
2965 // Cursors returned by leveldb iterate over snapshots, so the
2966 // contents of the pcursor will not be affected by simultaneous
2967 // writes during use below this block.
2968 //
2969 // See discussion here:
2970 // https://github.com/bitcoin/bitcoin/pull/15606#discussion_r274479369
2971 //
2973
2974 chainstate.ForceFlushStateToDisk();
2975
2976 maybe_stats = GetUTXOStats(&chainstate.CoinsDB(), chainstate.m_blockman,
2977 CoinStatsHashType::HASH_SERIALIZED,
2978 interruption_point);
2979 if (!maybe_stats) {
2980 throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set");
2981 }
2982
2983 pcursor =
2984 std::unique_ptr<CCoinsViewCursor>(chainstate.CoinsDB().Cursor());
2985 tip = CHECK_NONFATAL(
2986 chainstate.m_blockman.LookupBlockIndex(maybe_stats->hashBlock));
2987 }
2988
2989 return {std::move(pcursor), *CHECK_NONFATAL(maybe_stats), tip};
2990}
2991
2993 CCoinsStats *maybe_stats, const CBlockIndex *tip,
2994 AutoFile &afile, const fs::path &path,
2995 const fs::path &temppath,
2996 const std::function<void()> &interruption_point) {
2998 strprintf("writing UTXO snapshot at height %s (%s) to file %s (via %s)",
2999 tip->nHeight, tip->GetBlockHash().ToString(),
3000 fs::PathToString(path), fs::PathToString(temppath)));
3001
3002 SnapshotMetadata metadata{tip->GetBlockHash(), maybe_stats->coins_count};
3003
3004 afile << metadata;
3005
3006 COutPoint key;
3007 TxId last_txid;
3008 Coin coin;
3009 unsigned int iter{0};
3010 size_t written_coins_count{0};
3011 std::vector<std::pair<uint32_t, Coin>> coins;
3012
3013 // To reduce space the serialization format of the snapshot avoids
3014 // duplication of tx hashes. The code takes advantage of the guarantee by
3015 // leveldb that keys are lexicographically sorted.
3016 // In the coins vector we collect all coins that belong to a certain tx hash
3017 // (key.hash) and when we have them all (key.hash != last_hash) we write
3018 // them to file using the below lambda function.
3019 // See also https://github.com/bitcoin/bitcoin/issues/25675
3020 auto write_coins_to_file =
3021 [&](AutoFile &afile, const TxId &last_txid,
3022 const std::vector<std::pair<uint32_t, Coin>> &coins,
3023 size_t &written_coins_count) {
3024 afile << last_txid;
3025 WriteCompactSize(afile, coins.size());
3026 for (const auto &[n, coin_] : coins) {
3027 WriteCompactSize(afile, n);
3028 afile << coin_;
3029 ++written_coins_count;
3030 }
3031 };
3032
3033 pcursor->GetKey(key);
3034 last_txid = key.GetTxId();
3035 while (pcursor->Valid()) {
3036 if (iter % 5000 == 0) {
3037 interruption_point();
3038 }
3039 ++iter;
3040 if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
3041 if (key.GetTxId() != last_txid) {
3042 write_coins_to_file(afile, last_txid, coins,
3043 written_coins_count);
3044 last_txid = key.GetTxId();
3045 coins.clear();
3046 }
3047 coins.emplace_back(key.GetN(), coin);
3048 }
3049 pcursor->Next();
3050 }
3051
3052 if (!coins.empty()) {
3053 write_coins_to_file(afile, last_txid, coins, written_coins_count);
3054 }
3055
3056 CHECK_NONFATAL(written_coins_count == maybe_stats->coins_count);
3057
3058 afile.fclose();
3059
3060 UniValue result(UniValue::VOBJ);
3061 result.pushKV("coins_written", written_coins_count);
3062 result.pushKV("base_hash", tip->GetBlockHash().ToString());
3063 result.pushKV("base_height", tip->nHeight);
3064 result.pushKV("path", path.u8string());
3065 result.pushKV("txoutset_hash", maybe_stats->hashSerialized.ToString());
3066 result.pushKV("nchaintx", tip->nChainTx);
3067 return result;
3068}
3069
3071 AutoFile &afile, const fs::path &path,
3072 const fs::path &tmppath) {
3073 auto [cursor, stats, tip]{WITH_LOCK(
3074 ::cs_main,
3075 return PrepareUTXOSnapshot(chainstate, node.rpc_interruption_point))};
3076 return WriteUTXOSnapshot(chainstate, cursor.get(), &stats, tip, afile, path,
3077 tmppath, node.rpc_interruption_point);
3078}
3079
3081 return RPCHelpMan{
3082 "loadtxoutset",
3083 "Load the serialized UTXO set from a file.\n"
3084 "Once this snapshot is loaded, its contents will be deserialized into "
3085 "a second chainstate data structure, which is then used to sync to the "
3086 "network's tip. "
3087 "Meanwhile, the original chainstate will complete the initial block "
3088 "download process in the background, eventually validating up to the "
3089 "block that the snapshot is based upon.\n\n"
3090 "The result is a usable bitcoind instance that is current with the "
3091 "network tip in a matter of minutes rather than hours. UTXO snapshot "
3092 "are typically obtained from third-party sources (HTTP, torrent, etc.) "
3093 "which is reasonable since their contents are always checked by "
3094 "hash.\n\n"
3095 "This RPC is incompatible with the -chronik init option, and a node "
3096 "with multiple chainstates may not be restarted with -chronik. After "
3097 "the background validation is finished and the chainstates are merged, "
3098 "the node can be restarted again with Chronik.\n\n"
3099 "You can find more information on this process in the `assumeutxo` "
3100 "design document (https://www.bitcoinabc.org/doc/assumeutxo.html).",
3101 {
3103 "path to the snapshot file. If relative, will be prefixed by "
3104 "datadir."},
3105 },
3107 "",
3108 "",
3109 {
3110 {RPCResult::Type::NUM, "coins_loaded",
3111 "the number of coins loaded from the snapshot"},
3112 {RPCResult::Type::STR_HEX, "tip_hash",
3113 "the hash of the base of the snapshot"},
3114 {RPCResult::Type::NUM, "base_height",
3115 "the height of the base of the snapshot"},
3116 {RPCResult::Type::STR, "path",
3117 "the absolute path that the snapshot was loaded from"},
3118 }},
3120 HelpExampleCli("loadtxoutset -rpcclienttimeout=0", "utxo.dat")},
3121 [&](const RPCHelpMan &self, const Config &config,
3122 const JSONRPCRequest &request) -> UniValue {
3123 NodeContext &node = EnsureAnyNodeContext(request.context);
3126 const fs::path path{AbsPathForConfigVal(
3127 args, fs::u8path(self.Arg<std::string>("path")))};
3128
3129 if (args.GetBoolArg("-chronik", false)) {
3130 throw JSONRPCError(
3132 "loadtxoutset is not compatible with Chronik.");
3133 }
3134
3135 FILE *file{fsbridge::fopen(path, "rb")};
3136 AutoFile afile{file};
3137 if (afile.IsNull()) {
3139 "Couldn't open file " + path.u8string() +
3140 " for reading.");
3141 }
3142
3143 SnapshotMetadata metadata;
3144 try {
3145 afile >> metadata;
3146 } catch (const std::ios_base::failure &e) {
3147 throw JSONRPCError(
3149 strprintf("Unable to parse metadata: %s", e.what()));
3150 }
3151
3152 auto activation_result{
3153 chainman.ActivateSnapshot(afile, metadata, false)};
3154 if (!activation_result) {
3155 throw JSONRPCError(
3157 strprintf("Unable to load UTXO snapshot: %s. (%s)",
3158 util::ErrorString(activation_result).original,
3159 path.u8string()));
3160 }
3161
3162 CBlockIndex &snapshot_index{*CHECK_NONFATAL(*activation_result)};
3163
3164 // Because we can't provide historical blocks during tip or
3165 // background sync. Update local services to reflect we are a
3166 // limited peer until we are fully sync.
3167 node.connman->RemoveLocalServices(NODE_NETWORK);
3168 // Setting the limited state is usually redundant because the node
3169 // can always provide the last 288 blocks, but it doesn't hurt to
3170 // set it.
3171 node.connman->AddLocalServices(NODE_NETWORK_LIMITED);
3172
3173 UniValue result(UniValue::VOBJ);
3174 result.pushKV("coins_loaded", metadata.m_coins_count);
3175 result.pushKV("tip_hash", snapshot_index.GetBlockHash().ToString());
3176 result.pushKV("base_height", snapshot_index.nHeight);
3177 result.pushKV("path", fs::PathToString(path));
3178 return result;
3179 },
3180 };
3181}
3182
3183const std::vector<RPCResult> RPCHelpForChainstate{
3184 {RPCResult::Type::NUM, "blocks", "number of blocks in this chainstate"},
3185 {RPCResult::Type::STR_HEX, "bestblockhash", "blockhash of the tip"},
3186 {RPCResult::Type::NUM, "difficulty", "difficulty of the tip"},
3187 {RPCResult::Type::NUM, "verificationprogress",
3188 "progress towards the network tip"},
3189 {RPCResult::Type::STR_HEX, "snapshot_blockhash", /*optional=*/true,
3190 "the base block of the snapshot this chainstate is based on, if any"},
3191 {RPCResult::Type::NUM, "coins_db_cache_bytes", "size of the coinsdb cache"},
3192 {RPCResult::Type::NUM, "coins_tip_cache_bytes",
3193 "size of the coinstip cache"},
3194 {RPCResult::Type::BOOL, "validated",
3195 "whether the chainstate is fully validated. True if all blocks in the "
3196 "chainstate were validated, false if the chain is based on a snapshot and "
3197 "the snapshot has not yet been validated."},
3198
3199};
3200
3202 return RPCHelpMan{
3203 "getchainstates",
3204 "\nReturn information about chainstates.\n",
3205 {},
3207 "",
3208 "",
3209 {
3210 {RPCResult::Type::NUM, "headers",
3211 "the number of headers seen so far"},
3213 "chainstates",
3214 "list of the chainstates ordered by work, with the "
3215 "most-work (active) chainstate last",
3216 {
3218 }},
3219 }},
3220 RPCExamples{HelpExampleCli("getchainstates", "") +
3221 HelpExampleRpc("getchainstates", "")},
3222 [&](const RPCHelpMan &self, const Config &config,
3223 const JSONRPCRequest &request) -> UniValue {
3224 LOCK(cs_main);
3226
3227 ChainstateManager &chainman = EnsureAnyChainman(request.context);
3228
3229 auto make_chain_data =
3230 [&](const Chainstate &chainstate,
3231 bool validated) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
3234 if (!chainstate.m_chain.Tip()) {
3235 return data;
3236 }
3237 const CChain &chain = chainstate.m_chain;
3238 const CBlockIndex *tip = chain.Tip();
3239
3240 data.pushKV("blocks", chain.Height());
3241 data.pushKV("bestblockhash", tip->GetBlockHash().GetHex());
3242 data.pushKV("difficulty", GetDifficulty(*tip));
3243 data.pushKV(
3244 "verificationprogress",
3245 GuessVerificationProgress(Params().TxData(), tip));
3246 data.pushKV("coins_db_cache_bytes",
3247 chainstate.m_coinsdb_cache_size_bytes);
3248 data.pushKV("coins_tip_cache_bytes",
3249 chainstate.m_coinstip_cache_size_bytes);
3250 if (chainstate.m_from_snapshot_blockhash) {
3251 data.pushKV(
3252 "snapshot_blockhash",
3253 chainstate.m_from_snapshot_blockhash->ToString());
3254 }
3255 data.pushKV("validated", validated);
3256 return data;
3257 };
3258
3259 obj.pushKV("headers", chainman.m_best_header
3260 ? chainman.m_best_header->nHeight
3261 : -1);
3262
3263 const auto &chainstates = chainman.GetAll();
3264 UniValue obj_chainstates{UniValue::VARR};
3265 for (Chainstate *cs : chainstates) {
3266 obj_chainstates.push_back(
3267 make_chain_data(*cs, !cs->m_from_snapshot_blockhash ||
3268 chainstates.size() == 1));
3269 }
3270 obj.pushKV("chainstates", std::move(obj_chainstates));
3271 return obj;
3272 }};
3273}
3274
3276 // clang-format off
3277 static const CRPCCommand commands[] = {
3278 // category actor (function)
3279 // ------------------ ----------------------
3280 { "blockchain", getbestblockhash, },
3281 { "blockchain", getblock, },
3282 { "blockchain", getblockfrompeer, },
3283 { "blockchain", getblockchaininfo, },
3284 { "blockchain", getblockcount, },
3285 { "blockchain", getblockhash, },
3286 { "blockchain", getblockheader, },
3287 { "blockchain", getblockstats, },
3288 { "blockchain", getchaintips, },
3289 { "blockchain", getchaintxstats, },
3290 { "blockchain", getdifficulty, },
3291 { "blockchain", gettxout, },
3292 { "blockchain", gettxoutsetinfo, },
3293 { "blockchain", pruneblockchain, },
3294 { "blockchain", verifychain, },
3295 { "blockchain", preciousblock, },
3296 { "blockchain", scantxoutset, },
3297 { "blockchain", getblockfilter, },
3298 { "blockchain", dumptxoutset, },
3299 { "blockchain", loadtxoutset, },
3300 { "blockchain", getchainstates, },
3301
3302 /* Not shown in help */
3303 { "hidden", invalidateblock, },
3304 { "hidden", parkblock, },
3305 { "hidden", reconsiderblock, },
3306 { "hidden", syncwithvalidationinterfacequeue, },
3307 { "hidden", unparkblock, },
3308 { "hidden", waitfornewblock, },
3309 { "hidden", waitforblock, },
3310 { "hidden", waitforblockheight, },
3311 };
3312 // clang-format on
3313 for (const auto &c : commands) {
3314 t.appendCommand(c.name, &c);
3315 }
3316}
bool MoneyRange(const Amount nValue)
Definition: amount.h:171
static constexpr Amount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:170
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...
Definition: configfile.cpp:239
RPCHelpMan gettxout()
static RPCHelpMan getblock()
Definition: blockchain.cpp:704
static RPCHelpMan getdifficulty()
Definition: blockchain.cpp:461
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)
Definition: blockchain.cpp:104
static RPCHelpMan syncwithvalidationinterfacequeue()
Definition: blockchain.cpp:444
static CBlockUndo GetUndoChecked(BlockManager &blockman, const CBlockIndex &blockindex)
Definition: blockchain.cpp:685
static RPCHelpMan getchaintips()
static RPCHelpMan loadtxoutset()
static RPCHelpMan gettxoutsetinfo()
Definition: blockchain.cpp:981
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)
Definition: blockchain.cpp:967
static RPCHelpMan preciousblock()
static constexpr size_t PER_UTXO_OVERHEAD
double GetDifficulty(const CBlockIndex &blockindex)
Calculate the difficulty for a given block index.
Definition: blockchain.cpp:88
static RPCHelpMan scantxoutset()
static std::condition_variable cond_blockchange
Definition: blockchain.cpp:70
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)
Definition: blockchain.cpp:663
std::optional< int > GetPruneHeight(const BlockManager &blockman, const CChain &chain)
Definition: blockchain.cpp:855
static void ReconsiderBlock(ChainstateManager &chainman, avalanche::Processor *const avalanche, const BlockHash &block_hash)
static RPCHelpMan getblockfilter()
static RPCHelpMan getbestblockhash()
Definition: blockchain.cpp:238
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()
Definition: blockchain.cpp:322
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()
Definition: blockchain.cpp:481
static RPCHelpMan getblockhash()
Definition: blockchain.cpp:538
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.
Definition: blockchain.cpp:147
RPCHelpMan unparkblock()
static RPCHelpMan waitforblockheight()
Definition: blockchain.cpp:384
static const CBlockIndex * ParseHashOrHeight(const UniValue &param, ChainstateManager &chainman)
Definition: blockchain.cpp:115
UniValue blockToJSON(BlockManager &blockman, const CBlock &block, const CBlockIndex &tip, const CBlockIndex &blockindex, TxVerbosity verbosity)
Block description to JSON.
Definition: blockchain.cpp:181
static RPCHelpMan pruneblockchain()
Definition: blockchain.cpp:893
static CUpdatedBlock latestblock GUARDED_BY(cs_blockchange)
static RPCHelpMan getblockheader()
Definition: blockchain.cpp:567
RPCHelpMan parkblock()
static GlobalMutex cs_blockchange
Definition: blockchain.cpp:69
static RPCHelpMan dumptxoutset()
Serialize the UTXO set to a file for loading elsewhere.
static RPCHelpMan getblockcount()
Definition: blockchain.cpp:220
static RPCHelpMan waitfornewblock()
Definition: blockchain.cpp:265
void RPCNotifyBlockChange(const CBlockIndex *pindex)
Callback for when block tip changed.
Definition: blockchain.cpp:256
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.
Definition: chainparams.cpp:21
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:53
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:430
bool IsNull() const
Return true if the wrapped FILE* is nullptr, false otherwise.
Definition: streams.h:472
int fclose()
Definition: streams.h:445
Complete block filter struct as defined in BIP 157.
Definition: blockfilter.h:111
const std::vector< uint8_t > & GetEncodedFilter() const
Definition: blockfilter.h:134
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:191
uint256 hashMerkleRoot
Definition: blockindex.h:75
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: blockindex.h:32
CBlockHeader GetBlockHeader() const
Definition: blockindex.h:117
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:76
uint32_t nNonce
Definition: blockindex.h:78
int64_t GetBlockTime() const
Definition: blockindex.h:160
int64_t GetMedianTimePast() const
Definition: blockindex.h:172
uint32_t nBits
Definition: blockindex.h:77
unsigned int nTx
Number of transactions in this block.
Definition: blockindex.h:55
int32_t nVersion
block header
Definition: blockindex.h:74
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: blockindex.cpp:62
BlockHash GetBlockHash() const
Definition: blockindex.h:130
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:38
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block.
Definition: blockindex.h:68
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.
Definition: chainparams.h:134
const CBlock & GenesisBlock() const
Definition: chainparams.h:112
const ChainTxData & TxData() const
Definition: chainparams.h:158
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:358
BlockHash GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:218
std::optional< Coin > GetCoin(const COutPoint &outpoint) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:90
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:304
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:652
std::optional< Coin > GetCoin(const COutPoint &outpoint) const override
GetCoin, returning whether it exists and is not spent.
Definition: txmempool.cpp:779
Definition: net.h:841
bool GetNetworkActive() const
Definition: net.h:933
void SetNetworkActive(bool active)
Definition: net.cpp:2473
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
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:221
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:317
bool isSpent(const COutPoint &outpoint) const
Definition: txmempool.cpp:136
An output of a transaction.
Definition: transaction.h:128
CScript scriptPubKey
Definition: transaction.h:131
Amount nValue
Definition: transaction.h:130
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:655
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:739
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:846
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:838
size_t m_coinstip_cache_size_bytes
The cache size of the in-memory coins view.
Definition: validation.h:898
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:865
size_t m_coinsdb_cache_size_bytes
The cache size of the on-disk coins view.
Definition: validation.h:895
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:872
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:1001
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
Definition: validation.h:796
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...
Definition: validation.h:1191
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:1468
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...
Definition: validation.h:1442
kernel::Notifications & GetNotifications() const
Definition: validation.h:1299
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.
Definition: validation.h:1323
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1449
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1446
const CChainParams & GetParams() const
Definition: validation.h:1284
const Consensus::Params & GetConsensus() const
Definition: validation.h:1287
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())
Definition: validation.h:1443
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
Definition: validation.h:1408
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1332
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
Definition: config.h:19
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:416
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
@ VNULL
Definition: univalue.h:30
@ VOBJ
Definition: univalue.h:31
@ VARR
Definition: univalue.h:32
bool isNull() const
Definition: univalue.h:104
size_t size() const
Definition: univalue.h:92
const std::vector< UniValue > & getValues() const
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
uint8_t * begin()
Definition: uint256.h:85
std::string ToString() const
Definition: uint256.h:80
std::string GetHex() const
Definition: uint256.cpp:16
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...
Definition: blockstorage.h:116
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.
Definition: blockstorage.h:353
uint64_t CalculateCurrentUsage()
Calculate the amount of disk space the block & undo files currently use.
bool IsPruneMode() const
Whether running in -prune mode.
Definition: blockstorage.h:350
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...
Definition: utxo_snapshot.h:30
uint64_t m_coins_count
The number of coins in the UTXO set contained in this snapshot.
Definition: utxo_snapshot.h:41
256-bit opaque blob.
Definition: uint256.h:129
std::unique_ptr< CoinStatsIndex > g_coin_stats_index
The global UTXO set hash object.
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
Definition: core_write.cpp:194
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={})
Definition: core_write.cpp:221
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 LogPrint(category,...)
Definition: logging.h:452
unsigned int nHeight
static void pool cs
@ RPC
Definition: logging.h:76
@ NONE
Definition: logging.h:68
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
Definition: messages.h:12
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:132
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:315
@ NODE_NETWORK_LIMITED
Definition: protocol.h:365
@ 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:163
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:180
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:1382
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:35
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded values (throws error if not hex).
Definition: util.cpp:86
size_t GetSerializeSize(const T &t)
Definition: serialize.h:1262
void WriteCompactSize(SizeComputer &os, uint64_t nSize)
Definition: serialize.h:1258
bool IsRPCRunning()
Query whether RPC is running.
Definition: server.cpp:381
ChainstateManager & EnsureAnyChainman(const std::any &context)
Definition: server_util.cpp:59
NodeContext & EnsureAnyNodeContext(const std::any &context)
Definition: server_util.cpp:21
CTxMemPool & EnsureMemPool(const NodeContext &node)
Definition: server_util.cpp:29
PeerManager & EnsurePeerman(const NodeContext &node)
Definition: server_util.cpp:72
ChainstateManager & EnsureChainman(const NodeContext &node)
Definition: server_util.cpp:52
ArgsManager & EnsureArgsman(const NodeContext &node)
Definition: server_util.cpp:41
CConnman & EnsureConnman(const NodeContext &node)
Definition: server_util.cpp:63
ArgsManager & EnsureAnyArgsman(const std::any &context)
Definition: server_util.cpp:48
Definition: amount.h:21
static constexpr Amount zero() noexcept
Definition: amount.h:34
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
Definition: blockchain.cpp:65
Comparison function for sorting the getchaintips heads.
bool operator()(const CBlockIndex *a, const CBlockIndex *b) const
static const Currency & get()
Definition: amount.cpp:18
std::string ticker
Definition: amount.h:155
@ 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:212
@ 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:214
std::string oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
Definition: util.h:149
bool skip_type_check
Definition: util.h:146
@ 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
uint64_t nDiskSize
Definition: coinstats.h:37
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
uint64_t nBogoSize
Definition: coinstats.h:35
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:48
#define WAIT_LOCK(cs, name)
Definition: sync.h:317
#define AssertLockNotHeld(cs)
Definition: sync.h:163
#define LOCK(cs)
Definition: sync.h:306
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:357
static int count
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
#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...
Definition: tinyformat.h:1202
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:55
uint256 uint256S(const char *str)
uint256 from const char *.
Definition: uint256.h:143
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'.
Definition: validation.cpp:99
void PruneBlockFilesManual(Chainstate &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
AssertLockHeld(pool.cs)
static constexpr int DEFAULT_CHECKLEVEL
Definition: validation.h:101
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:99
static const signed int DEFAULT_CHECKBLOCKS
Definition: validation.h:100
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.
Definition: warnings.cpp:43